blob: 659fe741544a97268d0ab3093672ffc6ed6ddf6f [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 {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 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 */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 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,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000255 ValueDecl *VD, bool def=false);
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
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000407 void convertToUnqualifiedObjCType(QualType &T) {
408 if (T->isObjCQualifiedIdType())
409 T = Context->getObjCIdType();
410 else if (T->isObjCQualifiedClassType())
411 T = Context->getObjCClassType();
412 else if (T->isObjCObjectPointerType() &&
413 T->getPointeeType()->isObjCQualifiedInterfaceType())
414 T = Context->getObjCIdType();
415 }
416
Steve Naroff54055232008-10-27 17:20:55 +0000417 // FIXME: This predicate seems like it would be useful to add to ASTContext.
418 bool isObjCType(QualType T) {
419 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
420 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Steve Naroff54055232008-10-27 17:20:55 +0000422 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Steve Naroff54055232008-10-27 17:20:55 +0000424 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
425 OCT == Context->getCanonicalType(Context->getObjCClassType()))
426 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Ted Kremenek6217b802009-07-29 21:53:49 +0000428 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000430 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000431 return true;
432 }
433 return false;
434 }
435 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000436 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000437 void GetExtentOfArgList(const char *Name, const char *&LParen,
438 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000439 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Daniel Dunbar4087f272010-08-17 22:39:59 +0000441 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000442 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
443 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Steve Naroff621edce2009-04-29 16:37:50 +0000445 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000446 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000447 if (From[i] == '"')
448 To += "\\\"";
449 else
450 To += From[i];
451 }
452 }
John McCalle23cf432010-12-14 08:05:40 +0000453
454 QualType getSimpleFunctionType(QualType result,
455 const QualType *args,
456 unsigned numArgs,
457 bool variadic = false) {
458 FunctionProtoType::ExtProtoInfo fpi;
459 fpi.Variadic = variadic;
460 return Context->getFunctionType(result, args, numArgs, fpi);
461 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000462 };
John McCall9d125032010-01-15 18:39:57 +0000463
464 // Helper function: create a CStyleCastExpr with trivial type source info.
465 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000466 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000467 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000468 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000469 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000470 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000471}
472
Mike Stump1eb44332009-09-09 15:08:12 +0000473void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
474 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000475 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000476 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000478 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000479 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000480 // All the args are checked/rewritten. Don't call twice!
481 RewriteBlockPointerDecl(D);
482 break;
483 }
484 }
485}
486
487void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000488 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000489 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000490 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000491}
492
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000493static bool IsHeaderFile(const std::string &Filename) {
494 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000496 if (DotPos == std::string::npos) {
497 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000498 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000501 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
502 // C header: .h
503 // C++ header: .hh or .H;
504 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000505}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000506
Eli Friedman66d6f042009-05-18 22:20:00 +0000507RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000508 Diagnostic &D, const LangOptions &LOpts,
509 bool silenceMacroWarn)
510 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
511 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000512 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000513 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000514 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000515 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000516 "rewriter doesn't support user-specified control flow semantics "
517 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000518}
519
Eli Friedmanbce831b2009-05-18 22:29:17 +0000520ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
521 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000522 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000523 const LangOptions &LOpts,
524 bool SilenceRewriteMacroWarning) {
525 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000526}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000527
Steve Naroffb29b4272008-04-14 22:03:09 +0000528void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000529 Context = &context;
530 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000531 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000532 MsgSendFunctionDecl = 0;
533 MsgSendSuperFunctionDecl = 0;
534 MsgSendStretFunctionDecl = 0;
535 MsgSendSuperStretFunctionDecl = 0;
536 MsgSendFpretFunctionDecl = 0;
537 GetClassFunctionDecl = 0;
538 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000539 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000540 SelGetUidFunctionDecl = 0;
541 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000542 ConstantStringClassReference = 0;
543 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000544 CurMethodDef = 0;
545 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000546 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000547 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000549 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000550 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000551 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000552 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000553 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000554 PropParentMap = 0;
555 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000556 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000557 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000559 // Get the ID and start/end of the main file.
560 MainFileID = SM->getMainFileID();
561 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
562 MainFileStart = MainBuf->getBufferStart();
563 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner2c78b872009-04-14 23:22:57 +0000565 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000567 // declaring objc_selector outside the parameter list removes a silly
568 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000570 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000572 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000574 if (LangOpts.Microsoft) {
575 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000576 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
577 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000579 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000580 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
582 Preamble += "typedef struct objc_object Protocol;\n";
583 Preamble += "#define _REWRITER_typedef_Protocol\n";
584 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 if (LangOpts.Microsoft) {
586 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
587 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
588 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000589 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000590 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000594 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000598 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
603 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000611 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000612 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
617 Preamble += "struct __objcFastEnumerationState {\n\t";
618 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000619 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "unsigned long *mutationsPtr;\n\t";
621 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000622 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000623 Preamble += "#define __FASTENUMERATIONSTATE\n";
624 Preamble += "#endif\n";
625 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
626 Preamble += "struct __NSConstantStringImpl {\n";
627 Preamble += " int *isa;\n";
628 Preamble += " int flags;\n";
629 Preamble += " char *str;\n";
630 Preamble += " long length;\n";
631 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000632 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
633 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
634 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000635 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000636 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000637 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
638 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000639 // Blocks preamble.
640 Preamble += "#ifndef BLOCK_IMPL\n";
641 Preamble += "#define BLOCK_IMPL\n";
642 Preamble += "struct __block_impl {\n";
643 Preamble += " void *isa;\n";
644 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000645 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000646 Preamble += " void *FuncPtr;\n";
647 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000648 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000649 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000650 Preamble += "extern \"C\" __declspec(dllexport) "
651 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000652 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
653 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
655 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000656 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000658 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
660 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000661 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000662 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000663 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
664 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000665 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000666 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000667 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000668 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000669 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000670 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000671 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000672 Preamble += "#define __weak\n";
673 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000674 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
675 // as this avoids warning in any 64bit/32bit compilation model.
676 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000677}
678
679
Chris Lattnerf04da132007-10-24 17:06:59 +0000680//===----------------------------------------------------------------------===//
681// Top Level Driver Code
682//===----------------------------------------------------------------------===//
683
Chris Lattner682bf922009-03-29 16:50:03 +0000684void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000685 if (Diags.hasErrorOccurred())
686 return;
687
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000688 // Two cases: either the decl could be in the main file, or it could be in a
689 // #included file. If the former, rewrite it now. If the later, check to see
690 // if we rewrote the #include/#import.
691 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000692 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000694 // If this is for a builtin, ignore it.
695 if (Loc.isInvalid()) return;
696
Steve Naroffebf2b562007-10-23 23:50:29 +0000697 // Look for built-in declarations that we need to refer during the rewrite.
698 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000699 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000700 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000701 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000702 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000703 ConstantStringClassReference = FVD;
704 return;
705 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000707 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000708 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000709 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000710 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000711 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000712 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000713 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000714 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000715 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
716 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000717 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
718 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000719 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000720 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000721 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000723 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000724 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725}
726
Chris Lattnerf04da132007-10-24 17:06:59 +0000727//===----------------------------------------------------------------------===//
728// Syntactic (non-AST) Rewriting Code
729//===----------------------------------------------------------------------===//
730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000733 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000736 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000738 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
742 return;
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
745 return;
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000748 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000749 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000750 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000751 BufPtr += ImportLen;
752 }
753 }
754 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000755}
756
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000757static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 std::string S;
760 S = "((struct ";
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000763 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 return S;
765}
766
Steve Naroffa0876e82008-12-02 17:36:43 +0000767void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000772 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000773 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000778 SourceLocation onePastSemiLoc =
779 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000790 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000791 if (!PD->getGetterMethodDecl()->isDefined()) {
792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794 ObjCPropertyDecl::OBJC_PR_copy));
795 std::string Getr;
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000801 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
804 Getr += "{ ";
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 Getr += "typedef ";
810 const FunctionType *FPRetType = 0;
811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
812 FPRetType);
813 Getr += " _TYPE";
814 if (FPRetType) {
815 Getr += ")"; // close the precedence "scope" for "*".
816
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 Getr += "(";
820 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
821 if (i) Getr += ", ";
822 std::string ParamStr = FT->getArgType(i).getAsString(
823 Context->PrintingPolicy);
824 Getr += ParamStr;
825 }
826 if (FT->isVariadic()) {
827 if (FT->getNumArgs()) Getr += ", ";
828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
837 SynthesizeIvarOffsetComputation(OID, Getr);
838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000847 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Steve Naroffeb0646c2008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000867 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000870 Setr += ", ";
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872 Setr += "0, ";
873 else
874 Setr += "1, ";
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000883 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000886}
Chris Lattner8a12c272007-10-11 18:38:32 +0000887
Steve Naroffb29b4272008-04-14 22:03:09 +0000888void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000889 // Get the start location and compute the semi location.
890 SourceLocation startLoc = ClassDecl->getLocation();
891 const char *startBuf = SM->getCharacterData(startLoc);
892 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Chris Lattnerf04da132007-10-24 17:06:59 +0000894 // Translate to typedef's that forward reference structs with the same name
895 // as the class. As a convenience, we include the original declaration
896 // as a comment.
897 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000898 typedefString += "// @class ";
899 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
900 I != E; ++I) {
901 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
902 typedefString += ForwardDecl->getNameAsString();
903 if (I+1 != E)
904 typedefString += ", ";
905 else
906 typedefString += ";\n";
907 }
908
Chris Lattner67956052009-02-20 18:04:31 +0000909 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
910 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000911 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000912 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000913 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000914 typedefString += "\n";
915 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000917 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000918 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000920 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Steve Naroff934f2762007-10-24 22:48:43 +0000923 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000924 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000925}
926
Steve Naroffb29b4272008-04-14 22:03:09 +0000927void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000928 // When method is a synthesized one, such as a getter/setter there is
929 // nothing to rewrite.
930 if (Method->isSynthesized())
931 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000932 SourceLocation LocStart = Method->getLocStart();
933 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattner30fc9332009-02-04 01:06:56 +0000935 if (SM->getInstantiationLineNumber(LocEnd) >
936 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000937 InsertText(LocStart, "#if 0\n");
938 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000939 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000941 }
942}
943
Mike Stump1eb44332009-09-09 15:08:12 +0000944void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000945 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Benjamin Kramerd999b372010-02-14 14:14:16 +0000947 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000948 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000949}
950
Steve Naroffb29b4272008-04-14 22:03:09 +0000951void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000952 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Steve Naroff423cb562007-10-30 13:30:57 +0000954 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000955 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000957 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
958 E = CatDecl->prop_end(); I != E; ++I)
959 RewriteProperty(*I);
960
Mike Stump1eb44332009-09-09 15:08:12 +0000961 for (ObjCCategoryDecl::instmeth_iterator
962 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000963 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000964 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000965 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000966 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000967 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000968 RewriteMethodDeclaration(*I);
969
Steve Naroff423cb562007-10-30 13:30:57 +0000970 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000971 ReplaceText(CatDecl->getAtEndRange().getBegin(),
972 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000973}
974
Steve Naroffb29b4272008-04-14 22:03:09 +0000975void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000976 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Steve Naroff752d6ef2007-10-30 16:42:30 +0000978 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000979 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000980
981 for (ObjCProtocolDecl::instmeth_iterator
982 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000985 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000986 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000988 RewriteMethodDeclaration(*I);
989
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000990 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
991 E = PDecl->prop_end(); I != E; ++I)
992 RewriteProperty(*I);
993
Steve Naroff752d6ef2007-10-30 16:42:30 +0000994 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000995 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000996 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000997
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000998 // Must comment out @optional/@required
999 const char *startBuf = SM->getCharacterData(LocStart);
1000 const char *endBuf = SM->getCharacterData(LocEnd);
1001 for (const char *p = startBuf; p < endBuf; p++) {
1002 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001003 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001004 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001006 }
1007 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001008 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001009 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001011 }
1012 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001013}
1014
Steve Naroffb29b4272008-04-14 22:03:09 +00001015void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001016 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001017 if (LocStart.isInvalid())
1018 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001019 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001020 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001021}
1022
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001023void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1024 const FunctionType *&FPRetType) {
1025 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001026 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027 else if (T->isFunctionPointerType() ||
1028 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001029 // needs special handling, since pointer-to-functions have special
1030 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001031 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001032 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001034 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001035 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001036 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001037 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001038 ResultStr += FPRetType->getResultType().getAsString(
1039 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001040 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001041 }
1042 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001043 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001044}
1045
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001046void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1047 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048 std::string &ResultStr) {
1049 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1050 const FunctionType *FPRetType = 0;
1051 ResultStr += "\nstatic ";
1052 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001053 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001055 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001056 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001058 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 NameStr += "_I_";
1060 else
1061 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001063 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001064 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001065
1066 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001067 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001068 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001069 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 }
Mike Stump1eb44332009-09-09 15:08:12 +00001071 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001072 {
1073 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 int len = selString.size();
1075 for (int i = 0; i < len; i++)
1076 if (selString[i] == ':')
1077 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001078 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001079 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001080 // Remember this name for metadata emission
1081 MethodInternalNames[OMD] = NameStr;
1082 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 // Rewrite arguments
1085 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001087 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001088 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001091 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001092 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001093 ResultStr += "struct ";
1094 }
1095 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001096 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001097 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 }
1099 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001100 ResultStr += Context->getObjCClassType().getAsString(
1101 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001103 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001104 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001108 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1109 E = OMD->param_end(); PI != E; ++PI) {
1110 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001112 if (PDecl->getType()->isObjCQualifiedIdType()) {
1113 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001114 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001115 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001116 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001117 QualType QT = PDecl->getType();
1118 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1119 if (convertBlockPointerToFunctionPointer(QT))
1120 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1121 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001122 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001123 ResultStr += Name;
1124 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001125 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001126 if (OMD->isVariadic())
1127 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001128 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Steve Naroff76e429d2008-07-16 14:40:40 +00001130 if (FPRetType) {
1131 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Steve Naroff76e429d2008-07-16 14:40:40 +00001133 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001134 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001135 ResultStr += "(";
1136 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1137 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001138 std::string ParamStr = FT->getArgType(i).getAsString(
1139 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001140 ResultStr += ParamStr;
1141 }
1142 if (FT->isVariadic()) {
1143 if (FT->getNumArgs()) ResultStr += ", ";
1144 ResultStr += "...";
1145 }
1146 ResultStr += ")";
1147 } else {
1148 ResultStr += "()";
1149 }
1150 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001151}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001152void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1154 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001156 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001159 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1160 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001161 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001164 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001166 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001167
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001168 const char *startBuf = SM->getCharacterData(LocStart);
1169 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001170 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001173 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001174 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1175 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001176 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001178 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001179 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001180 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001181 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001183 const char *startBuf = SM->getCharacterData(LocStart);
1184 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001185 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001187 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001188 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001189 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001190 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001191 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001192 }
1193
Benjamin Kramerd999b372010-02-14 14:14:16 +00001194 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001195}
1196
Steve Naroffb29b4272008-04-14 22:03:09 +00001197void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001198 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001200 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001201 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001202 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001203 ResultStr += "\n";
1204 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001205 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001206 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001207 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001208 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001209 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001210 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001211 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001212 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001213 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
1215 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001216 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001217 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001218 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001219 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001220 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001221 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001222 for (ObjCInterfaceDecl::classmeth_iterator
1223 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001224 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001225 RewriteMethodDeclaration(*I);
1226
Steve Naroff2feac5e2007-10-30 03:43:13 +00001227 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001228 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1229 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001230}
1231
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001232Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001233 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001234 ObjCMethodDecl *OMD = 0;
1235 QualType Ty;
1236 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001237 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001238 bool Super = false;
1239 QualType SuperTy;
1240 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001241 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001242 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001243 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001244 if (ObjCPropertyRefExpr *PropRefExpr =
1245 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001246 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001247 if (PropRefExpr->isExplicitProperty()) {
1248 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1249 OMD = PDecl->getSetterMethodDecl();
1250 Ty = PDecl->getType();
1251 Sel = PDecl->getSetterName();
1252 } else {
1253 OMD = PropRefExpr->getImplicitPropertySetter();
1254 Sel = OMD->getSelector();
1255 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001256 }
John McCall12f78a62010-12-02 01:19:52 +00001257 Super = PropRefExpr->isSuperReceiver();
1258 if (!Super) {
1259 Receiver = PropRefExpr->getBase();
1260 } else {
1261 SuperTy = PropRefExpr->getSuperReceiverType();
1262 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001263 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001264 }
1265
1266 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001267 llvm::SmallVector<Expr *, 1> ExprVec;
1268 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001270 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001271 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001272 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001273 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001274 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001275 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001276 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001277 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001278 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001279 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001280 &ExprVec[0], 1,
1281 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001282 else {
1283 // FIXME. Refactor this into common code with that in
1284 // RewritePropertyOrImplicitGetter
1285 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1286 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1287 if (PropGetters[Exp])
1288 // This allows us to handle chain/nested property/implicit getters.
1289 Receiver = PropGetters[Exp];
1290
Douglas Gregor04badcf2010-04-21 00:45:42 +00001291 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001292 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001293 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001294 /*FIXME: */SourceLocation(),
1295 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001296 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001297 &ExprVec[0], 1,
1298 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001299 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001300 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Steve Naroffc77a6362008-12-04 16:24:46 +00001302 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001303 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001304 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001305 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1306 // to things that stay around.
1307 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001308 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001309}
1310
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001311Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1312 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001313 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001314 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001315 ObjCMethodDecl *OMD = 0;
1316 QualType Ty;
1317 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001318 bool Super = false;
1319 QualType SuperTy;
1320 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001321 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001322 if (ObjCPropertyRefExpr *PropRefExpr =
1323 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001324 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001325 if (PropRefExpr->isExplicitProperty()) {
1326 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1327 OMD = PDecl->getGetterMethodDecl();
1328 Ty = PDecl->getType();
1329 Sel = PDecl->getGetterName();
1330 } else {
1331 OMD = PropRefExpr->getImplicitPropertyGetter();
1332 Sel = OMD->getSelector();
1333 Ty = PropRefExpr->getType();
1334 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001335 Super = PropRefExpr->isSuperReceiver();
1336 if (!Super)
1337 Receiver = PropRefExpr->getBase();
1338 else {
John McCall12f78a62010-12-02 01:19:52 +00001339 SuperTy = PropRefExpr->getSuperReceiverType();
1340 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001341 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001342 }
1343
1344 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1345
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001346 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001347 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001348 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001349 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001350 Expr::getValueKindForType(Ty),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001351 /*FIXME?*/SourceLocation(),
1352 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001353 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001354 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001355 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001356 0, 0,
1357 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001358 else {
1359 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1360 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1361 if (PropGetters[Exp])
1362 // This allows us to handle chain/nested property/implicit getters.
1363 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001364 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001366 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001367 /*FIXME:*/SourceLocation(),
1368 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001369 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001370 0, 0,
1371 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001372 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001373
Steve Naroff4c3580e2008-12-04 23:50:32 +00001374 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001375
1376 if (!PropParentMap)
1377 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001378 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001379 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001380 ImplicitCastExpr*ICE=0;
1381 if (Parent)
1382 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1383 assert((ICE->getCastKind() == CK_GetObjCProperty)
1384 && "RewritePropertyOrImplicitGetter");
1385 Parent = PropParentMap->getParent(Parent);
1386 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1387 }
1388 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001389 // We stash away the ReplacingStmt since actually doing the
1390 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001391 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001392 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1393 // to things that stay around.
1394 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001395 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001396 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001397 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001398 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001399 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1400 // to things that stay around.
1401 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001402 return ReplacingStmt;
1403 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001404}
1405
Mike Stump1eb44332009-09-09 15:08:12 +00001406Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001407 SourceLocation OrigStart,
1408 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001409 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001410 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001411 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001412 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001413 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001414 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001415 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001416 // lookup which class implements the instance variable.
1417 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001418 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001419 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001420 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Steve Narofff0757612008-05-08 17:52:16 +00001422 // Synthesize an explicit cast to gain access to the ivar.
1423 std::string RecName = clsDeclared->getIdentifier()->getName();
1424 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001425 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001426 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001427 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001428 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1429 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001430 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001431 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001432 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001433 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001434 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001435 IV->getBase()->getLocEnd(),
1436 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001437 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001438 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001439 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001440 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001441 IV->getLocation(),
1442 D->getType(),
1443 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001444 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001445 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001446 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001447 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001448 // Cannot delete IV->getBase(), since PE points to it.
1449 // Replace the old base with the cast. This is important when doing
1450 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001451 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001452 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001453 }
Steve Naroff84472a82008-04-18 21:55:08 +00001454 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001455 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Steve Naroff9f525972008-05-06 23:20:07 +00001457 // Explicit ivar refs need to have a cast inserted.
1458 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001459 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001460 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001461 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001462 // lookup which class implements the instance variable.
1463 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001464 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001465 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001466 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Steve Naroff9f525972008-05-06 23:20:07 +00001468 // Synthesize an explicit cast to gain access to the ivar.
1469 std::string RecName = clsDeclared->getIdentifier()->getName();
1470 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001471 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001472 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001473 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001474 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1475 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001476 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001477 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001478 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001479 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001480 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001481 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001482 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001483 // Cannot delete IV->getBase(), since PE points to it.
1484 // Replace the old base with the cast. This is important when doing
1485 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001486 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001487 return IV;
1488 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001489 }
Steve Naroff84472a82008-04-18 21:55:08 +00001490 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001491}
1492
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001493Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1494 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1495 CI != E; ++CI) {
1496 if (*CI) {
1497 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1498 if (newStmt)
1499 *CI = newStmt;
1500 }
1501 }
1502 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1503 SourceRange OrigStmtRange = S->getSourceRange();
1504 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1505 replaced);
1506 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001507 }
1508 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1509 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1510 return newStmt;
1511 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001512 return S;
1513}
1514
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001515/// SynthCountByEnumWithState - To print:
1516/// ((unsigned int (*)
1517/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001518/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001519/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001520/// "countByEnumeratingWithState:objects:count:"),
1521/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001522/// (id *)items, (unsigned int)16)
1523///
Steve Naroffb29b4272008-04-14 22:03:09 +00001524void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1526 "id *, unsigned int))(void *)objc_msgSend)";
1527 buf += "\n\t\t";
1528 buf += "((id)l_collection,\n\t\t";
1529 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1530 buf += "\n\t\t";
1531 buf += "&enumState, "
1532 "(id *)items, (unsigned int)16)";
1533}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001534
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001535/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1536/// statement to exit to its outer synthesized loop.
1537///
Steve Naroffb29b4272008-04-14 22:03:09 +00001538Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001539 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1540 return S;
1541 // replace break with goto __break_label
1542 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001544 SourceLocation startLoc = S->getLocStart();
1545 buf = "goto __break_label_";
1546 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001547 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001548
1549 return 0;
1550}
1551
1552/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1553/// statement to continue with its inner synthesized loop.
1554///
Steve Naroffb29b4272008-04-14 22:03:09 +00001555Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001556 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1557 return S;
1558 // replace continue with goto __continue_label
1559 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001560
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001561 SourceLocation startLoc = S->getLocStart();
1562 buf = "goto __continue_label_";
1563 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001564 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001566 return 0;
1567}
1568
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001569/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001570/// It rewrites:
1571/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001573/// Into:
1574/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001575/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001577/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001579/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001580/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001581/// if (limit) {
1582/// unsigned long startMutations = *enumState.mutationsPtr;
1583/// do {
1584/// unsigned long counter = 0;
1585/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001586/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001588/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001589/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001590/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001591/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001592/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593/// objects:items count:16]);
1594/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001595/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001596/// }
1597/// else
1598/// elem = nil;
1599/// }
1600///
Steve Naroffb29b4272008-04-14 22:03:09 +00001601Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001602 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001603 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001604 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001605 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001606 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001607 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001611 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001612 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 std::string buf;
1614 buf = "\n{\n\t";
1615 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1616 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001617 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001618 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001619 if (ElementType->isObjCQualifiedIdType() ||
1620 ElementType->isObjCQualifiedInterfaceType())
1621 // Simply use 'id' for all qualified types.
1622 elementTypeAsString = "id";
1623 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001624 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001625 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001626 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001627 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628 buf += elementName;
1629 buf += ";\n\t";
1630 }
Chris Lattner06767512008-04-08 05:52:18 +00001631 else {
1632 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001633 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001634 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1635 if (VD->getType()->isObjCQualifiedIdType() ||
1636 VD->getType()->isObjCQualifiedInterfaceType())
1637 // Simply use 'id' for all qualified types.
1638 elementTypeAsString = "id";
1639 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001640 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001641 }
Mike Stump1eb44332009-09-09 15:08:12 +00001642
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001643 // struct __objcFastEnumerationState enumState = { 0 };
1644 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1645 // id items[16];
1646 buf += "id items[16];\n\t";
1647 // id l_collection = (id)
1648 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001649 // Find start location of 'collection' the hard way!
1650 const char *startCollectionBuf = startBuf;
1651 startCollectionBuf += 3; // skip 'for'
1652 startCollectionBuf = strchr(startCollectionBuf, '(');
1653 startCollectionBuf++; // skip '('
1654 // find 'in' and skip it.
1655 while (*startCollectionBuf != ' ' ||
1656 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1657 (*(startCollectionBuf+3) != ' ' &&
1658 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1659 startCollectionBuf++;
1660 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001661
1662 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001663 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001665 SourceLocation rightParenLoc = S->getRParenLoc();
1666 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1667 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001668 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001670 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1671 // objects:items count:16];
1672 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001673 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001674 // ((unsigned int (*)
1675 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001676 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001677 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001678 // "countByEnumeratingWithState:objects:count:"),
1679 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 // (id *)items, (unsigned int)16);
1681 buf += "unsigned long limit =\n\t\t";
1682 SynthCountByEnumWithState(buf);
1683 buf += ";\n\t";
1684 /// if (limit) {
1685 /// unsigned long startMutations = *enumState.mutationsPtr;
1686 /// do {
1687 /// unsigned long counter = 0;
1688 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001689 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001690 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001691 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001692 buf += "if (limit) {\n\t";
1693 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1694 buf += "do {\n\t\t";
1695 buf += "unsigned long counter = 0;\n\t\t";
1696 buf += "do {\n\t\t\t";
1697 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1698 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1699 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001700 buf += " = (";
1701 buf += elementTypeAsString;
1702 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001703 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001704 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001705
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001706 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001707 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001708 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 /// objects:items count:16]);
1710 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001711 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001712 /// }
1713 /// else
1714 /// elem = nil;
1715 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001716 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001717 buf = ";\n\t";
1718 buf += "__continue_label_";
1719 buf += utostr(ObjCBcLabelNo.back());
1720 buf += ": ;";
1721 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 buf += "} while (counter < limit);\n\t";
1723 buf += "} while (limit = ";
1724 SynthCountByEnumWithState(buf);
1725 buf += ");\n\t";
1726 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001727 buf += " = ((";
1728 buf += elementTypeAsString;
1729 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001730 buf += "__break_label_";
1731 buf += utostr(ObjCBcLabelNo.back());
1732 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001733 buf += "}\n\t";
1734 buf += "else\n\t\t";
1735 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001736 buf += " = ((";
1737 buf += elementTypeAsString;
1738 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001739 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001741 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001742 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001743 if (isa<CompoundStmt>(S->getBody())) {
1744 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001745 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001746 } else {
1747 /* Need to treat single statements specially. For example:
1748 *
1749 * for (A *a in b) if (stuff()) break;
1750 * for (A *a in b) xxxyy;
1751 *
1752 * The following code simply scans ahead to the semi to find the actual end.
1753 */
1754 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1755 const char *semiBuf = strchr(stmtBuf, ';');
1756 assert(semiBuf && "Can't find ';'");
1757 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001758 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001759 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001760 Stmts.pop_back();
1761 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001762 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001763}
1764
Mike Stump1eb44332009-09-09 15:08:12 +00001765/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001766/// This routine rewrites @synchronized(expr) stmt;
1767/// into:
1768/// objc_sync_enter(expr);
1769/// @try stmt @finally { objc_sync_exit(expr); }
1770///
Steve Naroffb29b4272008-04-14 22:03:09 +00001771Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001772 // Get the start location and compute the semi location.
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001776 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001777
1778 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001779 buf = "objc_sync_enter((id)";
1780 const char *lparenBuf = startBuf;
1781 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001782 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001783 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1784 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001785 // been rewritten! (which implies the SourceLocation's are invalid).
1786 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001787 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001788 while (*endBuf != ')') endBuf--;
1789 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001790 buf = ");\n";
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
1797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001798 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001799 startLoc = S->getSynchBody()->getLocEnd();
1800 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Steve Naroffc7089f12008-08-19 13:04:19 +00001802 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001803 SourceLocation lastCurlyLoc = startLoc;
1804 buf = "}\nelse {\n";
1805 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001806 buf += "}\n";
1807 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001808 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001809
1810 std::string syncBuf;
1811 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001812 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001813 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001814 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001815 std::string syncExprBufS;
1816 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001817 syncExpr->printPretty(syncExprBuf, *Context, 0,
1818 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001819 syncBuf += syncExprBuf.str();
1820 syncBuf += ");";
1821
1822 buf += syncBuf;
1823 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001824 buf += "}\n";
1825 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Benjamin Kramerd999b372010-02-14 14:14:16 +00001827 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001828
1829 bool hasReturns = false;
1830 HasReturnStmts(S->getSynchBody(), hasReturns);
1831 if (hasReturns)
1832 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1833
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001834 return 0;
1835}
1836
Steve Naroffb85e77a2009-12-05 21:43:12 +00001837void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1838{
Steve Naroff8c565152008-12-05 17:03:39 +00001839 // Perform a bottom up traversal of all children.
1840 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1841 CI != E; ++CI)
1842 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001843 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001844
Steve Naroffb85e77a2009-12-05 21:43:12 +00001845 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001846 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001847 TryFinallyContainsReturnDiag);
1848 }
1849 return;
1850}
1851
Steve Naroffb85e77a2009-12-05 21:43:12 +00001852void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1853{
1854 // Perform a bottom up traversal of all children.
1855 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1856 CI != E; ++CI)
1857 if (*CI)
1858 HasReturnStmts(*CI, hasReturns);
1859
1860 if (isa<ReturnStmt>(S))
1861 hasReturns = true;
1862 return;
1863}
1864
1865void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1866 // Perform a bottom up traversal of all children.
1867 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1868 CI != E; ++CI)
1869 if (*CI) {
1870 RewriteTryReturnStmts(*CI);
1871 }
1872 if (isa<ReturnStmt>(S)) {
1873 SourceLocation startLoc = S->getLocStart();
1874 const char *startBuf = SM->getCharacterData(startLoc);
1875
1876 const char *semiBuf = strchr(startBuf, ';');
1877 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1878 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1879
1880 std::string buf;
1881 buf = "{ objc_exception_try_exit(&_stack); return";
1882
Benjamin Kramerd999b372010-02-14 14:14:16 +00001883 ReplaceText(startLoc, 6, buf);
1884 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001885 }
1886 return;
1887}
1888
1889void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1890 // Perform a bottom up traversal of all children.
1891 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1892 CI != E; ++CI)
1893 if (*CI) {
1894 RewriteSyncReturnStmts(*CI, syncExitBuf);
1895 }
1896 if (isa<ReturnStmt>(S)) {
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
1899
1900 const char *semiBuf = strchr(startBuf, ';');
1901 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1902 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1903
1904 std::string buf;
1905 buf = "{ objc_exception_try_exit(&_stack);";
1906 buf += syncExitBuf;
1907 buf += " return";
1908
Benjamin Kramerd999b372010-02-14 14:14:16 +00001909 ReplaceText(startLoc, 6, buf);
1910 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001911 }
1912 return;
1913}
1914
Steve Naroffb29b4272008-04-14 22:03:09 +00001915Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001916 // Get the start location and compute the semi location.
1917 SourceLocation startLoc = S->getLocStart();
1918 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Steve Naroff75730982007-11-07 04:08:17 +00001920 assert((*startBuf == '@') && "bogus @try location");
1921
1922 std::string buf;
1923 // declare a new scope with two variables, _stack and _rethrow.
1924 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1925 buf += "int buf[18/*32-bit i386*/];\n";
1926 buf += "char *pointers[4];} _stack;\n";
1927 buf += "id volatile _rethrow = 0;\n";
1928 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001929 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001930
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Steve Naroff75730982007-11-07 04:08:17 +00001933 startLoc = S->getTryBody()->getLocEnd();
1934 startBuf = SM->getCharacterData(startLoc);
1935
1936 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Steve Naroff75730982007-11-07 04:08:17 +00001938 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001939 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001940 startLoc = startLoc.getFileLocWithOffset(1);
1941 buf = " /* @catch begin */ else {\n";
1942 buf += " id _caught = objc_exception_extract(&_stack);\n";
1943 buf += " objc_exception_try_enter (&_stack);\n";
1944 buf += " if (_setjmp(_stack.buf))\n";
1945 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1946 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Benjamin Kramerd999b372010-02-14 14:14:16 +00001948 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001949 } else { /* no catch list */
1950 buf = "}\nelse {\n";
1951 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1952 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001953 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001954 }
Steve Naroff75730982007-11-07 04:08:17 +00001955 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001956 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1957 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001958 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001959
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001960 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001961 buf = "if ("; // we are generating code for the first catch clause
1962 else
1963 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001964 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001965 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff75730982007-11-07 04:08:17 +00001967 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Steve Naroff75730982007-11-07 04:08:17 +00001969 const char *lParenLoc = strchr(startBuf, '(');
1970
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001971 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001972 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001973 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001974 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1975 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001976 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001977 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001978 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Steve Naroffe12e6922008-02-01 20:02:07 +00001980 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001981 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001982 } else if (catchDecl) {
1983 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001984 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001985 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001986 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001987 } else if (const ObjCObjectPointerType *Ptr =
1988 t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001992 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001993 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001994 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001995 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001996 }
1997 }
1998 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001999 lastCatchBody = Catch->getCatchBody();
2000 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002001 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2002 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2003 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2004 assert((*rParenBuf == ')') && "bogus @catch paren location");
2005 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Mike Stump1eb44332009-09-09 15:08:12 +00002007 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002008 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002009 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002010 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002011 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002012 }
Steve Naroff75730982007-11-07 04:08:17 +00002013 }
2014 // Complete the catch list...
2015 if (lastCatchBody) {
2016 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002017 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2018 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002019
Steve Naroff378f47a2008-09-11 15:29:03 +00002020 // Insert the last (implicit) else clause *before* the right curly brace.
2021 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2022 buf = "} /* last catch end */\n";
2023 buf += "else {\n";
2024 buf += " _rethrow = _caught;\n";
2025 buf += " objc_exception_try_exit(&_stack);\n";
2026 buf += "} } /* @catch end */\n";
2027 if (!S->getFinallyStmt())
2028 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002029 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Steve Naroff75730982007-11-07 04:08:17 +00002031 // Set lastCurlyLoc
2032 lastCurlyLoc = lastCatchBody->getLocEnd();
2033 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002034 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002035 startLoc = finalStmt->getLocStart();
2036 startBuf = SM->getCharacterData(startLoc);
2037 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Benjamin Kramerd999b372010-02-14 14:14:16 +00002039 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Steve Naroff75730982007-11-07 04:08:17 +00002041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startLoc = body->getLocStart();
2043 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002044 assert(*SM->getCharacterData(startLoc) == '{' &&
2045 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002046 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002047 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroff75730982007-11-07 04:08:17 +00002049 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002050 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002051 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002052 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroff75730982007-11-07 04:08:17 +00002054 // Set lastCurlyLoc
2055 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Steve Naroff8c565152008-12-05 17:03:39 +00002057 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002058 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002059 } else { /* no finally clause - make sure we synthesize an implicit one */
2060 buf = "{ /* implicit finally clause */\n";
2061 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2062 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2063 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002064 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002065
2066 // Now check for any return/continue/go statements within the @try.
2067 // The implicit finally clause won't called if the @try contains any
2068 // jump statements.
2069 bool hasReturns = false;
2070 HasReturnStmts(S->getTryBody(), hasReturns);
2071 if (hasReturns)
2072 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002073 }
2074 // Now emit the final closing curly brace...
2075 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002076 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002077 return 0;
2078}
2079
Mike Stump1eb44332009-09-09 15:08:12 +00002080// This can't be done with ReplaceStmt(S, ThrowExpr), since
2081// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002082// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002083Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002084 // Get the start location and compute the semi location.
2085 SourceLocation startLoc = S->getLocStart();
2086 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Steve Naroff2bd03922007-11-07 15:32:26 +00002088 assert((*startBuf == '@') && "bogus @throw location");
2089
2090 std::string buf;
2091 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002092 if (S->getThrowExpr())
2093 buf = "objc_exception_throw(";
2094 else // add an implicit argument
2095 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002097 // handle "@ throw" correctly.
2098 const char *wBuf = strchr(startBuf, 'w');
2099 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002100 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Steve Naroff2bd03922007-11-07 15:32:26 +00002102 const char *semiBuf = strchr(startBuf, ';');
2103 assert((*semiBuf == ';') && "@throw: can't find ';'");
2104 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002105 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002106 return 0;
2107}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002108
Steve Naroffb29b4272008-04-14 22:03:09 +00002109Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002110 // Create a new string expression.
2111 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002112 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002113 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002114 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2115 StrEncoding.length(), false,StrType,
2116 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002117 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Chris Lattner07506182007-11-30 22:53:43 +00002119 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002120 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002121 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002122}
2123
Steve Naroffb29b4272008-04-14 22:03:09 +00002124Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002125 if (!SelGetUidFunctionDecl)
2126 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002127 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2128 // Create a call to sel_registerName("selName").
2129 llvm::SmallVector<Expr*, 8> SelExprs;
2130 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002131 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002132 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002133 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002134 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002135 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2136 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002137 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002138 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002139 return SelExp;
2140}
2141
Steve Naroffb29b4272008-04-14 22:03:09 +00002142CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002143 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2144 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002145 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002146 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Steve Naroffebf2b562007-10-23 23:50:29 +00002148 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002149 DeclRefExpr *DRE =
2150 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Steve Naroffebf2b562007-10-23 23:50:29 +00002152 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002153 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002154 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002155 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002156 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002157
John McCall183700f2009-09-21 23:43:11 +00002158 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002160 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002161 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002162 FT->getCallResultType(*Context),
2163 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002164 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002165}
2166
Steve Naroffd5255f52007-11-01 13:24:47 +00002167static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2168 const char *&startRef, const char *&endRef) {
2169 while (startBuf < endBuf) {
2170 if (*startBuf == '<')
2171 startRef = startBuf; // mark the start.
2172 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002173 if (startRef && *startRef == '<') {
2174 endRef = startBuf; // mark the end.
2175 return true;
2176 }
2177 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002178 }
2179 startBuf++;
2180 }
2181 return false;
2182}
2183
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002184static void scanToNextArgument(const char *&argRef) {
2185 int angle = 0;
2186 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2187 if (*argRef == '<')
2188 angle++;
2189 else if (*argRef == '>')
2190 angle--;
2191 argRef++;
2192 }
2193 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2194}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002195
Steve Naroffb29b4272008-04-14 22:03:09 +00002196bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002197 if (T->isObjCQualifiedIdType())
2198 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002199 if (const PointerType *PT = T->getAs<PointerType>()) {
2200 if (PT->getPointeeType()->isObjCQualifiedIdType())
2201 return true;
2202 }
2203 if (T->isObjCObjectPointerType()) {
2204 T = T->getPointeeType();
2205 return T->isObjCQualifiedInterfaceType();
2206 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002207 if (T->isArrayType()) {
2208 QualType ElemTy = Context->getBaseElementType(T);
2209 return needToScanForQualifiers(ElemTy);
2210 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002211 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002212}
2213
Steve Naroff4f95b752008-07-29 18:15:38 +00002214void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2215 QualType Type = E->getType();
2216 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002217 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002218
Steve Naroffcda658e2008-11-19 21:15:47 +00002219 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2220 Loc = ECE->getLParenLoc();
2221 EndLoc = ECE->getRParenLoc();
2222 } else {
2223 Loc = E->getLocStart();
2224 EndLoc = E->getLocEnd();
2225 }
2226 // This will defend against trying to rewrite synthesized expressions.
2227 if (Loc.isInvalid() || EndLoc.isInvalid())
2228 return;
2229
Steve Naroff4f95b752008-07-29 18:15:38 +00002230 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002231 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002232 const char *startRef = 0, *endRef = 0;
2233 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2234 // Get the locations of the startRef, endRef.
2235 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2236 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2237 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002238 InsertText(LessLoc, "/*");
2239 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002240 }
2241 }
2242}
2243
Steve Naroffb29b4272008-04-14 22:03:09 +00002244void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002245 SourceLocation Loc;
2246 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002247 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002248 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2249 Loc = VD->getLocation();
2250 Type = VD->getType();
2251 }
2252 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2253 Loc = FD->getLocation();
2254 // Check for ObjC 'id' and class types that have been adorned with protocol
2255 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002256 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002257 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002258 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002259 if (!proto)
2260 return;
2261 Type = proto->getResultType();
2262 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002263 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2264 Loc = FD->getLocation();
2265 Type = FD->getType();
2266 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002267 else
2268 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002270 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002271 // 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 = SM->getCharacterData(Loc);
2274 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002275 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002276 startBuf--; // scan backward (from the decl location) for return type.
2277 const char *startRef = 0, *endRef = 0;
2278 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2279 // Get the locations of the startRef, endRef.
2280 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2281 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2282 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002283 InsertText(LessLoc, "/*");
2284 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002285 }
2286 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002287 if (!proto)
2288 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002289 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002290 const char *startBuf = SM->getCharacterData(Loc);
2291 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002292 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2293 if (needToScanForQualifiers(proto->getArgType(i))) {
2294 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Steve Naroffd5255f52007-11-01 13:24:47 +00002296 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002297 // scan forward (from the decl location) for argument types.
2298 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002299 const char *startRef = 0, *endRef = 0;
2300 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2301 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002302 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002303 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002304 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002305 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002306 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002307 InsertText(LessLoc, "/*");
2308 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002309 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002310 startBuf = ++endBuf;
2311 }
2312 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002313 // If the function name is derived from a macro expansion, then the
2314 // argument buffer will not follow the name. Need to speak with Chris.
2315 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002316 startBuf++; // scan forward (from the decl location) for argument types.
2317 startBuf++;
2318 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002319 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002320}
2321
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002322void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2323 QualType QT = ND->getType();
2324 const Type* TypePtr = QT->getAs<Type>();
2325 if (!isa<TypeOfExprType>(TypePtr))
2326 return;
2327 while (isa<TypeOfExprType>(TypePtr)) {
2328 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2329 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2330 TypePtr = QT->getAs<Type>();
2331 }
2332 // FIXME. This will not work for multiple declarators; as in:
2333 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002334 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002335 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2336 const char *startBuf = SM->getCharacterData(DeclLoc);
2337 if (ND->getInit()) {
2338 std::string Name(ND->getNameAsString());
2339 TypeAsString += " " + Name + " = ";
2340 Expr *E = ND->getInit();
2341 SourceLocation startLoc;
2342 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2343 startLoc = ECE->getLParenLoc();
2344 else
2345 startLoc = E->getLocStart();
2346 startLoc = SM->getInstantiationLoc(startLoc);
2347 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002348 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002349 }
2350 else {
2351 SourceLocation X = ND->getLocEnd();
2352 X = SM->getInstantiationLoc(X);
2353 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002354 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002355 }
2356}
2357
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002358// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002359void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002360 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2361 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002362 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002363 QualType getFuncType =
2364 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002365 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002366 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002367 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002368 SC_Extern,
2369 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002370}
2371
Steve Naroffb29b4272008-04-14 22:03:09 +00002372void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002374 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002375 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002376 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002377 return;
2378 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002379 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002380}
2381
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002382void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2383 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002384 const char *argPtr = TypeString.c_str();
2385 if (!strchr(argPtr, '^')) {
2386 Str += TypeString;
2387 return;
2388 }
2389 while (*argPtr) {
2390 Str += (*argPtr == '^' ? '*' : *argPtr);
2391 argPtr++;
2392 }
2393}
2394
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002395// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002396void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2397 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002398 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002399 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002400 const char *argPtr = TypeString.c_str();
2401 int paren = 0;
2402 while (*argPtr) {
2403 switch (*argPtr) {
2404 case '(':
2405 Str += *argPtr;
2406 paren++;
2407 break;
2408 case ')':
2409 Str += *argPtr;
2410 paren--;
2411 break;
2412 case '^':
2413 Str += '*';
2414 if (paren == 1)
2415 Str += VD->getNameAsString();
2416 break;
2417 default:
2418 Str += *argPtr;
2419 break;
2420 }
2421 argPtr++;
2422 }
2423}
2424
2425
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002426void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2427 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2428 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2429 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2430 if (!proto)
2431 return;
2432 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002433 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002434 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002435 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002436 FdStr += "(";
2437 unsigned numArgs = proto->getNumArgs();
2438 for (unsigned i = 0; i < numArgs; i++) {
2439 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002440 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002441 if (i+1 < numArgs)
2442 FdStr += ", ";
2443 }
2444 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002445 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002446 CurFunctionDeclToDeclareForBlock = 0;
2447}
2448
Steve Naroffc0a123c2008-03-11 17:37:02 +00002449// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002450void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002451 if (SuperContructorFunctionDecl)
2452 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002453 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002454 llvm::SmallVector<QualType, 16> ArgTys;
2455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002459 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2460 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002461 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002462 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002463 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002464 SC_Extern,
2465 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002466}
2467
Steve Naroff09b266e2007-10-30 23:14:51 +00002468// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002469void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002470 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2471 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002473 assert(!argT.isNull() && "Can't find 'id' type");
2474 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002476 assert(!argT.isNull() && "Can't find 'SEL' type");
2477 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2479 &ArgTys[0], ArgTys.size(),
2480 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002481 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002482 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002483 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002484 SC_Extern,
2485 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002486}
2487
Steve Naroff874e2322007-11-15 10:28:18 +00002488// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002489void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002490 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2491 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002492 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002493 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002494 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002495 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2496 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2497 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002498 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002499 assert(!argT.isNull() && "Can't find 'SEL' type");
2500 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002501 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2502 &ArgTys[0], ArgTys.size(),
2503 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002504 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002505 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002506 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002507 SC_Extern,
2508 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002509}
2510
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002511// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002512void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002513 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2514 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002515 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 assert(!argT.isNull() && "Can't find 'id' type");
2517 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002518 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002519 assert(!argT.isNull() && "Can't find 'SEL' type");
2520 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002521 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2522 &ArgTys[0], ArgTys.size(),
2523 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002524 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002525 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002526 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002527 SC_Extern,
2528 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529}
2530
Mike Stump1eb44332009-09-09 15:08:12 +00002531// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002532// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002533void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002534 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 &Context->Idents.get("objc_msgSendSuper_stret");
2536 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002537 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002538 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002539 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2541 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2542 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002543 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002544 assert(!argT.isNull() && "Can't find 'SEL' type");
2545 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002546 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2547 &ArgTys[0], ArgTys.size(),
2548 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002549 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002550 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002551 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002552 SC_Extern,
2553 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002554}
2555
Steve Naroff1284db82008-05-08 22:02:18 +00002556// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002557void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2559 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002560 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002561 assert(!argT.isNull() && "Can't find 'id' type");
2562 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002564 assert(!argT.isNull() && "Can't find 'SEL' type");
2565 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002566 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2567 &ArgTys[0], ArgTys.size(),
2568 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002569 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002570 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002571 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002572 SC_Extern,
2573 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002574}
2575
Steve Naroff09b266e2007-10-30 23:14:51 +00002576// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002577void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002578 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2579 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002580 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002581 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2582 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002583 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002584 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002585 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002586 SC_Extern,
2587 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002588}
2589
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002590// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2591void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2592 IdentifierInfo *getSuperClassIdent =
2593 &Context->Idents.get("class_getSuperclass");
2594 llvm::SmallVector<QualType, 16> ArgTys;
2595 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002596 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2597 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002598 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002599 SourceLocation(),
2600 getSuperClassIdent,
2601 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002602 SC_Extern,
2603 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002604 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002605}
2606
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002607// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002608void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002609 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2610 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002611 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002612 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2613 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002614 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002615 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002616 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002617 SC_Extern,
2618 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002619}
2620
Steve Naroffb29b4272008-04-14 22:03:09 +00002621Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002622 QualType strType = getConstantStringStructType();
2623
2624 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002625
2626 std::string tmpName = InFileName;
2627 unsigned i;
2628 for (i=0; i < tmpName.length(); i++) {
2629 char c = tmpName.at(i);
2630 // replace any non alphanumeric characters with '_'.
2631 if (!isalpha(c) && (c < '0' || c > '9'))
2632 tmpName[i] = '_';
2633 }
2634 S += tmpName;
2635 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002636 S += utostr(NumObjCStringLiterals++);
2637
Steve Naroffba92b2e2008-03-27 22:29:16 +00002638 Preamble += "static __NSConstantStringImpl " + S;
2639 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2640 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002641 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002642 std::string prettyBufS;
2643 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002644 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2645 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002646 Preamble += prettyBuf.str();
2647 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002648 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002649
2650 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002651 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002652 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002653 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2654 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002655 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002656 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002657 VK_RValue, OK_Ordinary,
2658 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 McCalla5bbc502010-11-15 09:46:46 +00002661 CK_BitCast, 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 McCalla5bbc502010-11-15 09:46:46 +00002775 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002777 Context->getObjCIdType(),
2778 VK_RValue,
2779 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002781
Douglas Gregor04badcf2010-04-21 00:45:42 +00002782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 llvm::SmallVector<Expr*, 8> ClsExprs;
2784 QualType argType = Context->getPointerType(Context->CharTy);
2785 ClsExprs.push_back(StringLiteral::Create(*Context,
2786 ClassDecl->getIdentifier()->getNameStart(),
2787 ClassDecl->getIdentifier()->getLength(),
2788 false, argType, SourceLocation()));
2789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2790 &ClsExprs[0],
2791 ClsExprs.size(),
2792 StartLoc,
2793 EndLoc);
2794 // (Class)objc_getClass("CurrentClass")
2795 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2796 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002797 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 ClsExprs.clear();
2799 ClsExprs.push_back(ArgExpr);
2800 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2801 &ClsExprs[0], ClsExprs.size(),
2802 StartLoc, EndLoc);
2803
2804 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2805 // To turn off a warning, type-cast to 'id'
2806 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2807 NoTypeInfoCStyleCastExpr(Context,
2808 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002809 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002810 // struct objc_super
2811 QualType superType = getSuperStructType();
2812 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002813
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 if (LangOpts.Microsoft) {
2815 SynthSuperContructorFunctionDecl();
2816 // Simulate a contructor call...
2817 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002818 superType, VK_LValue,
2819 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2821 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002822 superType, VK_LValue,
2823 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 // The code for super is a little tricky to prevent collision with
2825 // the structure definition in the header. The rewriter has it's own
2826 // internal definition (__rw_objc_super) that is uses. This is why
2827 // we need the cast below. For example:
2828 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2829 //
John McCall2de56d12010-08-25 11:45:40 +00002830 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002832 VK_RValue, OK_Ordinary,
2833 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2835 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002836 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002837 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 // (struct objc_super) { <exprs from above> }
2839 InitListExpr *ILE =
2840 new (Context) InitListExpr(*Context, SourceLocation(),
2841 &InitExprs[0], InitExprs.size(),
2842 SourceLocation());
2843 TypeSourceInfo *superTInfo
2844 = Context->getTrivialTypeSourceInfo(superType);
2845 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002846 superType, VK_LValue,
2847 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002848 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002849 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002851 VK_RValue, OK_Ordinary,
2852 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002853 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 MsgExprs.push_back(SuperRep);
2855 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002856 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857
2858 case ObjCMessageExpr::Class: {
2859 llvm::SmallVector<Expr*, 8> ClsExprs;
2860 QualType argType = Context->getPointerType(Context->CharTy);
2861 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002862 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002863 IdentifierInfo *clsName = Class->getIdentifier();
2864 ClsExprs.push_back(StringLiteral::Create(*Context,
2865 clsName->getNameStart(),
2866 clsName->getLength(),
2867 false, argType,
2868 SourceLocation()));
2869 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2870 &ClsExprs[0],
2871 ClsExprs.size(),
2872 StartLoc, EndLoc);
2873 MsgExprs.push_back(Cls);
2874 break;
2875 }
2876
2877 case ObjCMessageExpr::SuperInstance:{
2878 MsgSendFlavor = MsgSendSuperFunctionDecl;
2879 if (MsgSendStretFlavor)
2880 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2881 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2882 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2883 llvm::SmallVector<Expr*, 4> InitExprs;
2884
2885 InitExprs.push_back(
2886 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002887 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002888 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002889 Context->getObjCIdType(),
2890 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002891 ); // set the 'receiver'.
2892
2893 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2894 llvm::SmallVector<Expr*, 8> ClsExprs;
2895 QualType argType = Context->getPointerType(Context->CharTy);
2896 ClsExprs.push_back(StringLiteral::Create(*Context,
2897 ClassDecl->getIdentifier()->getNameStart(),
2898 ClassDecl->getIdentifier()->getLength(),
2899 false, argType, SourceLocation()));
2900 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2901 &ClsExprs[0],
2902 ClsExprs.size(),
2903 StartLoc, EndLoc);
2904 // (Class)objc_getClass("CurrentClass")
2905 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2906 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002907 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 ClsExprs.clear();
2909 ClsExprs.push_back(ArgExpr);
2910 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2911 &ClsExprs[0], ClsExprs.size(),
2912 StartLoc, EndLoc);
2913
2914 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2915 // To turn off a warning, type-cast to 'id'
2916 InitExprs.push_back(
2917 // set 'super class', using class_getSuperclass().
2918 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002919 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002920 // struct objc_super
2921 QualType superType = getSuperStructType();
2922 Expr *SuperRep;
2923
2924 if (LangOpts.Microsoft) {
2925 SynthSuperContructorFunctionDecl();
2926 // Simulate a contructor call...
2927 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002928 superType, VK_LValue,
2929 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2931 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002932 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002933 // The code for super is a little tricky to prevent collision with
2934 // the structure definition in the header. The rewriter has it's own
2935 // internal definition (__rw_objc_super) that is uses. This is why
2936 // we need the cast below. For example:
2937 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2938 //
John McCall2de56d12010-08-25 11:45:40 +00002939 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002940 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002941 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002942 SourceLocation());
2943 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2944 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002945 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002946 } else {
2947 // (struct objc_super) { <exprs from above> }
2948 InitListExpr *ILE =
2949 new (Context) InitListExpr(*Context, SourceLocation(),
2950 &InitExprs[0], InitExprs.size(),
2951 SourceLocation());
2952 TypeSourceInfo *superTInfo
2953 = Context->getTrivialTypeSourceInfo(superType);
2954 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002955 superType, VK_RValue, ILE,
2956 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002957 }
2958 MsgExprs.push_back(SuperRep);
2959 break;
2960 }
2961
2962 case ObjCMessageExpr::Instance: {
2963 // Remove all type-casts because it may contain objc-style types; e.g.
2964 // Foo<Proto> *.
2965 Expr *recExpr = Exp->getInstanceReceiver();
2966 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2967 recExpr = CE->getSubExpr();
2968 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002969 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002970 MsgExprs.push_back(recExpr);
2971 break;
2972 }
2973 }
2974
Steve Naroffbeaf2992007-11-03 11:27:19 +00002975 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002976 llvm::SmallVector<Expr*, 8> SelExprs;
2977 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002978 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002979 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002980 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002981 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002982 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002983 &SelExprs[0], SelExprs.size(),
2984 StartLoc,
2985 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002986 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Steve Naroff934f2762007-10-24 22:48:43 +00002988 // Now push any user supplied arguments.
2989 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002990 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002991 // Make all implicit casts explicit...ICE comes in handy:-)
2992 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2993 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002994 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002995 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002996 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002997 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002998 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00002999 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003000 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003001 }
3002 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003003 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003004 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003005 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003006 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003007 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003008 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003009 }
Mike Stump1eb44332009-09-09 15:08:12 +00003010 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003011 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003012 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3013 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003014 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003015 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003016 }
Steve Naroffab972d32007-11-04 22:37:50 +00003017 // Generate the funky cast.
3018 CastExpr *cast;
3019 llvm::SmallVector<QualType, 8> ArgTypes;
3020 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Steve Naroffab972d32007-11-04 22:37:50 +00003022 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003023 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3024 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3025 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003026 ArgTypes.push_back(Context->getObjCIdType());
3027 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003028 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003029 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003030 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3031 E = OMD->param_end(); PI != E; ++PI) {
3032 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003033 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003034 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003035 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003036 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003037 ArgTypes.push_back(t);
3038 }
Chris Lattner89951a82009-02-20 18:43:26 +00003039 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3040 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003041 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003042 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003043 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003044 }
3045 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003046 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Steve Naroffab972d32007-11-04 22:37:50 +00003048 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003049 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003050 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003051
Mike Stump1eb44332009-09-09 15:08:12 +00003052 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003053 // If we don't do this cast, we get the following bizarre warning/note:
3054 // xx.m:13: warning: function called through a non-compatible type
3055 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003056 cast = NoTypeInfoCStyleCastExpr(Context,
3057 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003058 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Steve Naroffab972d32007-11-04 22:37:50 +00003060 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003061 QualType castType =
3062 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3063 // If we don't have a method decl, force a variadic cast.
3064 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003065 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003066 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003067 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003068
3069 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003070 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003071
John McCall183700f2009-09-21 23:43:11 +00003072 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003073 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003074 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003075 FT->getResultType(), VK_RValue,
3076 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003077 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003078 if (MsgSendStretFlavor) {
3079 // We have the method which returns a struct/union. Must also generate
3080 // call to objc_msgSend_stret and hang both varieties on a conditional
3081 // expression which dictate which one to envoke depending on size of
3082 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003084 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003085 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003086 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003087 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003088 cast = NoTypeInfoCStyleCastExpr(Context,
3089 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003090 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003091 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003092 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3093 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003094 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003095 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003096 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003098 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003099 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003100
John McCall183700f2009-09-21 23:43:11 +00003101 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003102 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003103 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003104 FT->getResultType(), VK_RValue,
3105 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003107 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003108 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003109 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003110 Context->getSizeType(),
3111 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003112 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3113 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3114 // For X86 it is more complicated and some kind of target specific routine
3115 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003116 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003117 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003118 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3119 llvm::APInt(IntSize, 8),
3120 Context->IntTy,
3121 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003122 BinaryOperator *lessThanExpr =
3123 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3124 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003125 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003126 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003127 new (Context) ConditionalOperator(lessThanExpr,
3128 SourceLocation(), CE,
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003129 SourceLocation(), STCE, (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00003130 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003131 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3132 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003133 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003134 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003135 return ReplacingStmt;
3136}
3137
Steve Naroffb29b4272008-04-14 22:03:09 +00003138Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003139 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3140 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Steve Naroff934f2762007-10-24 22:48:43 +00003142 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003143 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003145 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003146 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003147}
3148
Steve Naroff621edce2009-04-29 16:37:50 +00003149// typedef struct objc_object Protocol;
3150QualType RewriteObjC::getProtocolType() {
3151 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003152 TypeSourceInfo *TInfo
3153 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003154 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003155 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003156 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003157 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003158 }
3159 return Context->getTypeDeclType(ProtocolTypeDecl);
3160}
3161
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003162/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003163/// a synthesized/forward data reference (to the protocol's metadata).
3164/// The forward references (and metadata) are generated in
3165/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003166Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003167 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3168 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003169 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003170 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003171 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003172 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3173 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003174 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003175 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003176 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003177 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003178 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003179 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003180 ReplaceStmt(Exp, castExpr);
3181 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003182 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003183 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003184
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003185}
3186
Mike Stump1eb44332009-09-09 15:08:12 +00003187bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003188 const char *endBuf) {
3189 while (startBuf < endBuf) {
3190 if (*startBuf == '#') {
3191 // Skip whitespace.
3192 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3193 ;
3194 if (!strncmp(startBuf, "if", strlen("if")) ||
3195 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3196 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3197 !strncmp(startBuf, "define", strlen("define")) ||
3198 !strncmp(startBuf, "undef", strlen("undef")) ||
3199 !strncmp(startBuf, "else", strlen("else")) ||
3200 !strncmp(startBuf, "elif", strlen("elif")) ||
3201 !strncmp(startBuf, "endif", strlen("endif")) ||
3202 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3203 !strncmp(startBuf, "include", strlen("include")) ||
3204 !strncmp(startBuf, "import", strlen("import")) ||
3205 !strncmp(startBuf, "include_next", strlen("include_next")))
3206 return true;
3207 }
3208 startBuf++;
3209 }
3210 return false;
3211}
3212
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003213/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003214/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003215void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003216 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003217 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003218 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003219 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003220 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003221 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003222 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003223 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003224 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003225 SourceLocation LocStart = CDecl->getLocStart();
3226 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Steve Narofffea763e82007-11-14 19:25:57 +00003228 const char *startBuf = SM->getCharacterData(LocStart);
3229 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003231 // If no ivars and no root or if its root, directly or indirectly,
3232 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003233 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3234 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003235 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003236 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003237 return;
3238 }
Mike Stump1eb44332009-09-09 15:08:12 +00003239
3240 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003241 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003242 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003243 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003244 if (LangOpts.Microsoft)
3245 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003246
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003247 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003248 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003249 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003250 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003251 // If the buffer contains preprocessor directives, we do more fine-grained
3252 // rewrites. This is intended to fix code that looks like (which occurs in
3253 // NSURL.h, for example):
3254 //
3255 // #ifdef XYZ
3256 // @interface Foo : NSObject
3257 // #else
3258 // @interface FooBar : NSObject
3259 // #endif
3260 // {
3261 // int i;
3262 // }
3263 // @end
3264 //
3265 // This clause is segregated to avoid breaking the common case.
3266 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003267 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003268 CDecl->getClassLoc();
3269 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003270 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003271
Chris Lattnercafeb352009-02-20 18:18:36 +00003272 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003273 // advance to the end of the referenced protocols.
3274 while (endHeader < cursor && *endHeader != '>') endHeader++;
3275 endHeader++;
3276 }
3277 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003278 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003279 } else {
3280 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003281 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003282 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003283 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003284 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003285 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003286 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003287 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003288 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003289
Steve Narofffea763e82007-11-14 19:25:57 +00003290 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003291 SourceLocation OnePastCurly =
3292 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003293 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003294 }
3295 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003296
Steve Narofffea763e82007-11-14 19:25:57 +00003297 // Now comment out any visibility specifiers.
3298 while (cursor < endBuf) {
3299 if (*cursor == '@') {
3300 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003301 // Skip whitespace.
3302 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3303 /*scan*/;
3304
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003305 // FIXME: presence of @public, etc. inside comment results in
3306 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003307 if (!strncmp(cursor, "public", strlen("public")) ||
3308 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003309 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003310 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003311 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003312 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003313 // FIXME: If there are cases where '<' is used in ivar declaration part
3314 // of user code, then scan the ivar list and use needToScanForQualifiers
3315 // for type checking.
3316 else if (*cursor == '<') {
3317 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003318 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003319 cursor = strchr(cursor, '>');
3320 cursor++;
3321 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003322 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003323 } else if (*cursor == '^') { // rewrite block specifier.
3324 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003325 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003326 }
Steve Narofffea763e82007-11-14 19:25:57 +00003327 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003328 }
Steve Narofffea763e82007-11-14 19:25:57 +00003329 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003330 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003331 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003332 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003333 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003334 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003335 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003336 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003337 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003338 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003339 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003340 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003341 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003342 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003343}
3344
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003345// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003346/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003347template<typename MethodIterator>
3348void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3349 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003350 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003351 llvm::StringRef prefix,
3352 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003353 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003354 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003355
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003356 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003357 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003358 SEL _cmd;
3359 char *method_types;
3360 void *_imp;
3361 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003362 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003363 Result += "\nstruct _objc_method {\n";
3364 Result += "\tSEL _cmd;\n";
3365 Result += "\tchar *method_types;\n";
3366 Result += "\tvoid *_imp;\n";
3367 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003369 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003370 }
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003372 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003373
Steve Naroff946a6932008-03-11 00:12:29 +00003374 /* struct {
3375 struct _objc_method_list *next_method;
3376 int method_count;
3377 struct _objc_method method_list[];
3378 }
3379 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003380 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003381 Result += "\nstatic struct {\n";
3382 Result += "\tstruct _objc_method_list *next_method;\n";
3383 Result += "\tint method_count;\n";
3384 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003385 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003386 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003387 Result += prefix;
3388 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3389 Result += "_METHODS_";
3390 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003391 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003392 Result += IsInstanceMethod ? "inst" : "cls";
3393 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003394 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003395
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003396 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003397 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003398 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003399 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003400 Result += "\", \"";
3401 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003402 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003403 Result += MethodInternalNames[*MethodBegin];
3404 Result += "}\n";
3405 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3406 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003407 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003408 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003409 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003410 Result += "\", \"";
3411 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003412 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003413 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003414 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003415 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003416 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003417}
3418
Steve Naroff621edce2009-04-29 16:37:50 +00003419/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003420void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003421RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3422 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003423 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003424
3425 // Output struct protocol_methods holder of method selector and type.
3426 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3427 /* struct protocol_methods {
3428 SEL _cmd;
3429 char *method_types;
3430 }
3431 */
3432 Result += "\nstruct _protocol_methods {\n";
3433 Result += "\tstruct objc_selector *_cmd;\n";
3434 Result += "\tchar *method_types;\n";
3435 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Steve Naroff621edce2009-04-29 16:37:50 +00003437 objc_protocol_methods = true;
3438 }
3439 // Do not synthesize the protocol more than once.
3440 if (ObjCSynthesizedProtocols.count(PDecl))
3441 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003443 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3444 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3445 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003446 /* struct _objc_protocol_method_list {
3447 int protocol_method_count;
3448 struct protocol_methods protocols[];
3449 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003450 */
Steve Naroff621edce2009-04-29 16:37:50 +00003451 Result += "\nstatic struct {\n";
3452 Result += "\tint protocol_method_count;\n";
3453 Result += "\tstruct _protocol_methods protocol_methods[";
3454 Result += utostr(NumMethods);
3455 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3456 Result += PDecl->getNameAsString();
3457 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3458 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003459
Steve Naroff621edce2009-04-29 16:37:50 +00003460 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003461 for (ObjCProtocolDecl::instmeth_iterator
3462 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003463 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003464 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003465 Result += "\t ,{{(struct objc_selector *)\"";
3466 else
3467 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003468 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003469 std::string MethodTypeString;
3470 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3471 Result += "\", \"";
3472 Result += MethodTypeString;
3473 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003474 }
Steve Naroff621edce2009-04-29 16:37:50 +00003475 Result += "\t }\n};\n";
3476 }
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Steve Naroff621edce2009-04-29 16:37:50 +00003478 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003479 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3480 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003481 if (NumMethods > 0) {
3482 /* struct _objc_protocol_method_list {
3483 int protocol_method_count;
3484 struct protocol_methods protocols[];
3485 }
3486 */
3487 Result += "\nstatic struct {\n";
3488 Result += "\tint protocol_method_count;\n";
3489 Result += "\tstruct _protocol_methods protocol_methods[";
3490 Result += utostr(NumMethods);
3491 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3492 Result += PDecl->getNameAsString();
3493 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3494 "{\n\t";
3495 Result += utostr(NumMethods);
3496 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Steve Naroff621edce2009-04-29 16:37:50 +00003498 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003499 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003500 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003501 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003502 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003503 Result += "\t ,{{(struct objc_selector *)\"";
3504 else
3505 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003506 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003507 std::string MethodTypeString;
3508 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3509 Result += "\", \"";
3510 Result += MethodTypeString;
3511 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003512 }
Steve Naroff621edce2009-04-29 16:37:50 +00003513 Result += "\t }\n};\n";
3514 }
3515
3516 // Output:
3517 /* struct _objc_protocol {
3518 // Objective-C 1.0 extensions
3519 struct _objc_protocol_extension *isa;
3520 char *protocol_name;
3521 struct _objc_protocol **protocol_list;
3522 struct _objc_protocol_method_list *instance_methods;
3523 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003524 };
Steve Naroff621edce2009-04-29 16:37:50 +00003525 */
3526 static bool objc_protocol = false;
3527 if (!objc_protocol) {
3528 Result += "\nstruct _objc_protocol {\n";
3529 Result += "\tstruct _objc_protocol_extension *isa;\n";
3530 Result += "\tchar *protocol_name;\n";
3531 Result += "\tstruct _objc_protocol **protocol_list;\n";
3532 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3533 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003534 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Steve Naroff621edce2009-04-29 16:37:50 +00003536 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003537 }
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Steve Naroff621edce2009-04-29 16:37:50 +00003539 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3540 Result += PDecl->getNameAsString();
3541 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3542 "{\n\t0, \"";
3543 Result += PDecl->getNameAsString();
3544 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003545 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003546 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3547 Result += PDecl->getNameAsString();
3548 Result += ", ";
3549 }
3550 else
3551 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003552 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003553 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3554 Result += PDecl->getNameAsString();
3555 Result += "\n";
3556 }
3557 else
3558 Result += "0\n";
3559 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003560
Steve Naroff621edce2009-04-29 16:37:50 +00003561 // Mark this protocol as having been generated.
3562 if (!ObjCSynthesizedProtocols.insert(PDecl))
3563 assert(false && "protocol already synthesized");
3564
3565}
3566
3567void RewriteObjC::
3568RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003569 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003570 std::string &Result) {
3571 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Steve Naroff621edce2009-04-29 16:37:50 +00003573 for (unsigned i = 0; i != Protocols.size(); i++)
3574 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3575
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003576 // Output the top lovel protocol meta-data for the class.
3577 /* struct _objc_protocol_list {
3578 struct _objc_protocol_list *next;
3579 int protocol_count;
3580 struct _objc_protocol *class_protocols[];
3581 }
3582 */
3583 Result += "\nstatic struct {\n";
3584 Result += "\tstruct _objc_protocol_list *next;\n";
3585 Result += "\tint protocol_count;\n";
3586 Result += "\tstruct _objc_protocol *class_protocols[";
3587 Result += utostr(Protocols.size());
3588 Result += "];\n} _OBJC_";
3589 Result += prefix;
3590 Result += "_PROTOCOLS_";
3591 Result += ClassName;
3592 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3593 "{\n\t0, ";
3594 Result += utostr(Protocols.size());
3595 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003597 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003598 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003599 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003600
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003601 for (unsigned i = 1; i != Protocols.size(); i++) {
3602 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003603 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003604 Result += "\n";
3605 }
3606 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003607}
3608
Steve Naroff621edce2009-04-29 16:37:50 +00003609
Mike Stump1eb44332009-09-09 15:08:12 +00003610/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003611/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003612void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003613 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003614 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003615 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003616 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003617 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003618 CDecl = CDecl->getNextClassCategory())
3619 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3620 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003622 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003623 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003624 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003626 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003627 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003628 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003629
3630 // If any of our property implementations have associated getters or
3631 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003632 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3633 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003634 Prop != PropEnd; ++Prop) {
3635 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3636 continue;
3637 if (!(*Prop)->getPropertyIvarDecl())
3638 continue;
3639 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3640 if (!PD)
3641 continue;
3642 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3643 InstanceMethods.push_back(Getter);
3644 if (PD->isReadOnly())
3645 continue;
3646 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3647 InstanceMethods.push_back(Setter);
3648 }
3649 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003650 true, "CATEGORY_", FullCategoryName.c_str(),
3651 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003653 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003654 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003655 false, "CATEGORY_", FullCategoryName.c_str(),
3656 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003658 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003659 // Null CDecl is case of a category implementation with no category interface
3660 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003661 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003662 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003663 /* struct _objc_category {
3664 char *category_name;
3665 char *class_name;
3666 struct _objc_method_list *instance_methods;
3667 struct _objc_method_list *class_methods;
3668 struct _objc_protocol_list *protocols;
3669 // Objective-C 1.0 extensions
3670 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003671 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003672 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003673 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003674 */
Mike Stump1eb44332009-09-09 15:08:12 +00003675
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003676 static bool objc_category = false;
3677 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003678 Result += "\nstruct _objc_category {\n";
3679 Result += "\tchar *category_name;\n";
3680 Result += "\tchar *class_name;\n";
3681 Result += "\tstruct _objc_method_list *instance_methods;\n";
3682 Result += "\tstruct _objc_method_list *class_methods;\n";
3683 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003684 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003685 Result += "\tstruct _objc_property_list *instance_properties;\n";
3686 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003687 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003688 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003689 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3690 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003691 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003693 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003694 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003695 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003696
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003697 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003698 Result += "\t, (struct _objc_method_list *)"
3699 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3700 Result += FullCategoryName;
3701 Result += "\n";
3702 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003703 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003704 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003705 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003706 Result += "\t, (struct _objc_method_list *)"
3707 "&_OBJC_CATEGORY_CLASS_METHODS_";
3708 Result += FullCategoryName;
3709 Result += "\n";
3710 }
3711 else
3712 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003713
Chris Lattnercafeb352009-02-20 18:18:36 +00003714 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003715 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003716 Result += FullCategoryName;
3717 Result += "\n";
3718 }
3719 else
3720 Result += "\t, 0\n";
3721 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003722}
3723
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003724/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3725/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003726void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003727 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003728 if (ivar->isBitField()) {
3729 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3730 // place all bitfields at offset 0.
3731 Result += "0";
3732 } else {
3733 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003734 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003735 if (LangOpts.Microsoft)
3736 Result += "_IMPL";
3737 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003738 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003739 Result += ")";
3740 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003741}
3742
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003743//===----------------------------------------------------------------------===//
3744// Meta Data Emission
3745//===----------------------------------------------------------------------===//
3746
Steve Naroffb29b4272008-04-14 22:03:09 +00003747void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003748 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003749 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003750
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003751 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003752 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003753 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003754 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003755 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003756 }
Mike Stump1eb44332009-09-09 15:08:12 +00003757
Chris Lattnerbe6df082007-12-12 07:56:42 +00003758 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003759 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003760 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003761 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003762 if (NumIvars > 0) {
3763 static bool objc_ivar = false;
3764 if (!objc_ivar) {
3765 /* struct _objc_ivar {
3766 char *ivar_name;
3767 char *ivar_type;
3768 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003769 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003770 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003771 Result += "\nstruct _objc_ivar {\n";
3772 Result += "\tchar *ivar_name;\n";
3773 Result += "\tchar *ivar_type;\n";
3774 Result += "\tint ivar_offset;\n";
3775 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003777 objc_ivar = true;
3778 }
3779
Steve Naroff946a6932008-03-11 00:12:29 +00003780 /* struct {
3781 int ivar_count;
3782 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003783 };
Steve Naroff946a6932008-03-11 00:12:29 +00003784 */
Mike Stump1eb44332009-09-09 15:08:12 +00003785 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003786 Result += "\tint ivar_count;\n";
3787 Result += "\tstruct _objc_ivar ivar_list[";
3788 Result += utostr(NumIvars);
3789 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003790 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003791 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003792 "{\n\t";
3793 Result += utostr(NumIvars);
3794 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003796 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003797 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003798 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003799 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003800 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003801 IV != IVEnd; ++IV)
3802 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003803 IVI = IDecl->ivar_begin();
3804 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003805 } else {
3806 IVI = CDecl->ivar_begin();
3807 IVE = CDecl->ivar_end();
3808 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003809 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003810 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003811 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003812 std::string TmpString, StrEncoding;
3813 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3814 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003815 Result += StrEncoding;
3816 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003817 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003818 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003819 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003820 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003821 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003822 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003823 std::string TmpString, StrEncoding;
3824 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3825 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003826 Result += StrEncoding;
3827 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003828 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003829 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003830 }
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003832 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003833 }
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003835 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003836 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003837 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003838
3839 // If any of our property implementations have associated getters or
3840 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003841 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3842 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003843 Prop != PropEnd; ++Prop) {
3844 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3845 continue;
3846 if (!(*Prop)->getPropertyIvarDecl())
3847 continue;
3848 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3849 if (!PD)
3850 continue;
3851 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003852 if (!Getter->isDefined())
3853 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003854 if (PD->isReadOnly())
3855 continue;
3856 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003857 if (!Setter->isDefined())
3858 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003859 }
3860 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003861 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003863 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003864 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003865 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003867 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003868 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003869 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003871 // Declaration of class/meta-class metadata
3872 /* struct _objc_class {
3873 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003874 const char *super_class_name;
3875 char *name;
3876 long version;
3877 long info;
3878 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003879 struct _objc_ivar_list *ivars;
3880 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003881 struct objc_cache *cache;
3882 struct objc_protocol_list *protocols;
3883 const char *ivar_layout;
3884 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003885 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003886 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003887 static bool objc_class = false;
3888 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003889 Result += "\nstruct _objc_class {\n";
3890 Result += "\tstruct _objc_class *isa;\n";
3891 Result += "\tconst char *super_class_name;\n";
3892 Result += "\tchar *name;\n";
3893 Result += "\tlong version;\n";
3894 Result += "\tlong info;\n";
3895 Result += "\tlong instance_size;\n";
3896 Result += "\tstruct _objc_ivar_list *ivars;\n";
3897 Result += "\tstruct _objc_method_list *methods;\n";
3898 Result += "\tstruct objc_cache *cache;\n";
3899 Result += "\tstruct _objc_protocol_list *protocols;\n";
3900 Result += "\tconst char *ivar_layout;\n";
3901 Result += "\tstruct _objc_class_ext *ext;\n";
3902 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003903 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003904 }
Mike Stump1eb44332009-09-09 15:08:12 +00003905
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003906 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003907 ObjCInterfaceDecl *RootClass = 0;
3908 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003909 while (SuperClass) {
3910 RootClass = SuperClass;
3911 SuperClass = SuperClass->getSuperClass();
3912 }
3913 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003916 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003917 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003918 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003919 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003920 Result += "\"";
3921
3922 if (SuperClass) {
3923 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003924 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003925 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003926 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003927 Result += "\"";
3928 }
3929 else {
3930 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003931 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003932 Result += "\"";
3933 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003934 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003935 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003936 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003937 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003938 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003939 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003940 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003941 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003942 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003943 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003944 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003945 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 Result += ",0,0\n";
3948 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003949 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 Result += "\t,0,0,0,0\n";
3951 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003952
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003953 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003955 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003956 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003958 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003959 if (SuperClass) {
3960 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003961 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003962 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003963 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003964 Result += "\"";
3965 }
3966 else {
3967 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003969 Result += "\"";
3970 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003971 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003972 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003973 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003974 Result += ",0";
3975 else {
3976 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003977 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003978 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003979 if (LangOpts.Microsoft)
3980 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003981 Result += ")";
3982 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003984 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003985 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003986 Result += "\n\t";
3987 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003988 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003990 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003991 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003992 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003993 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003994 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003995 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003996 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003997 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003998 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003999 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 Result += ", 0,0\n";
4001 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004002 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004003 Result += ",0,0,0\n";
4004 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004005}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004006
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004007/// RewriteImplementations - This routine rewrites all method implementations
4008/// and emits meta-data.
4009
Steve Narofface66252008-11-13 20:07:04 +00004010void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004011 int ClsDefCount = ClassImplementation.size();
4012 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004014 // Rewrite implemented methods
4015 for (int i = 0; i < ClsDefCount; i++)
4016 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004018 for (int i = 0; i < CatDefCount; i++)
4019 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004020}
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Steve Narofface66252008-11-13 20:07:04 +00004022void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4023 int ClsDefCount = ClassImplementation.size();
4024 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004025
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004026 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004027 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004028 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004029
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004030 // For each implemented category, write out all its meta data.
4031 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004032 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004033
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004034 // Write objc_symtab metadata
4035 /*
4036 struct _objc_symtab
4037 {
4038 long sel_ref_cnt;
4039 SEL *refs;
4040 short cls_def_cnt;
4041 short cat_def_cnt;
4042 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004043 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004044 */
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 Result += "\nstruct _objc_symtab {\n";
4047 Result += "\tlong sel_ref_cnt;\n";
4048 Result += "\tSEL *refs;\n";
4049 Result += "\tshort cls_def_cnt;\n";
4050 Result += "\tshort cat_def_cnt;\n";
4051 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4052 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004055 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004056 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 + ", " + utostr(CatDefCount) + "\n";
4058 for (int i = 0; i < ClsDefCount; i++) {
4059 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004060 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 Result += "\n";
4062 }
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 for (int i = 0; i < CatDefCount; i++) {
4065 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004066 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004067 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004068 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004069 Result += "\n";
4070 }
Mike Stump1eb44332009-09-09 15:08:12 +00004071
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004072 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004074 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004075
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004076 /*
4077 struct _objc_module {
4078 long version;
4079 long size;
4080 const char *name;
4081 struct _objc_symtab *symtab;
4082 }
4083 */
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += "\nstruct _objc_module {\n";
4086 Result += "\tlong version;\n";
4087 Result += "\tlong size;\n";
4088 Result += "\tconst char *name;\n";
4089 Result += "\tstruct _objc_symtab *symtab;\n";
4090 Result += "};\n\n";
4091 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004092 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004093 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004094 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004095 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004096
4097 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004098 if (ProtocolExprDecls.size()) {
4099 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4100 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004101 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004102 E = ProtocolExprDecls.end(); I != E; ++I) {
4103 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4104 Result += (*I)->getNameAsString();
4105 Result += " = &_OBJC_PROTOCOL_";
4106 Result += (*I)->getNameAsString();
4107 Result += ";\n";
4108 }
4109 Result += "#pragma data_seg(pop)\n\n";
4110 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004111 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004112 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004113 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4114 Result += "&_OBJC_MODULES;\n";
4115 Result += "#pragma data_seg(pop)\n\n";
4116 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004117}
Chris Lattner311ff022007-10-16 22:36:42 +00004118
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004119void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4120 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004121 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004122 assert(BlockByRefDeclNo.count(VD) &&
4123 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004124 if (def)
4125 ResultStr += "struct ";
4126 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004127 "_" + utostr(BlockByRefDeclNo[VD]) ;
4128}
4129
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004130static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4131 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4132 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4133 return false;
4134}
4135
Steve Naroff54055232008-10-27 17:20:55 +00004136std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004137 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004138 std::string Tag) {
4139 const FunctionType *AFT = CE->getFunctionType();
4140 QualType RT = AFT->getResultType();
4141 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004142 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004143 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004144
Steve Naroff54055232008-10-27 17:20:55 +00004145 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004146
Douglas Gregor72564e72009-02-26 23:50:07 +00004147 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004148 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004149 // block (to reference imported block decl refs).
4150 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004151 } else if (BD->param_empty()) {
4152 S += "(" + StructRef + " *__cself)";
4153 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004154 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004155 assert(FT && "SynthesizeBlockFunc: No function proto");
4156 S += '(';
4157 // first add the implicit argument.
4158 S += StructRef + " *__cself, ";
4159 std::string ParamStr;
4160 for (BlockDecl::param_iterator AI = BD->param_begin(),
4161 E = BD->param_end(); AI != E; ++AI) {
4162 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004163 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004164 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004165 if (convertBlockPointerToFunctionPointer(QT))
4166 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004167 else
4168 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004169 S += ParamStr;
4170 }
4171 if (FT->isVariadic()) {
4172 if (!BD->param_empty()) S += ", ";
4173 S += "...";
4174 }
4175 S += ')';
4176 }
4177 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Steve Naroff54055232008-10-27 17:20:55 +00004179 // Create local declarations to avoid rewriting all closure decl ref exprs.
4180 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004181 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004182 E = BlockByRefDecls.end(); I != E; ++I) {
4183 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004184 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004185 std::string TypeString;
4186 RewriteByRefString(TypeString, Name, (*I));
4187 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004188 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004189 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004190 }
Steve Naroff54055232008-10-27 17:20:55 +00004191 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004192 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004193 E = BlockByCopyDecls.end(); I != E; ++I) {
4194 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004195 // Handle nested closure invocation. For example:
4196 //
4197 // void (^myImportedClosure)(void);
4198 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004199 //
Steve Naroff54055232008-10-27 17:20:55 +00004200 // void (^anotherClosure)(void);
4201 // anotherClosure = ^(void) {
4202 // myImportedClosure(); // import and invoke the closure
4203 // };
4204 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004205 if (isTopLevelBlockPointerType((*I)->getType())) {
4206 RewriteBlockPointerTypeVariable(S, (*I));
4207 S += " = (";
4208 RewriteBlockPointerType(S, (*I)->getType());
4209 S += ")";
4210 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4211 }
4212 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004213 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004214 QualType QT = (*I)->getType();
4215 if (HasLocalVariableExternalStorage(*I))
4216 QT = Context->getPointerType(QT);
4217 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004218 S += Name + " = __cself->" +
4219 (*I)->getNameAsString() + "; // bound by copy\n";
4220 }
Steve Naroff54055232008-10-27 17:20:55 +00004221 }
4222 std::string RewrittenStr = RewrittenBlockExprs[CE];
4223 const char *cstr = RewrittenStr.c_str();
4224 while (*cstr++ != '{') ;
4225 S += cstr;
4226 S += "\n";
4227 return S;
4228}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004229
Steve Naroff54055232008-10-27 17:20:55 +00004230std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004231 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004232 std::string Tag) {
4233 std::string StructRef = "struct " + Tag;
4234 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Steve Naroff54055232008-10-27 17:20:55 +00004236 S += funcName;
4237 S += "_block_copy_" + utostr(i);
4238 S += "(" + StructRef;
4239 S += "*dst, " + StructRef;
4240 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004241 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004242 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004243 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004244 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004245 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004246 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004247 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004248 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004249 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004250 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004251 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004252 S += "}\n";
4253
Steve Naroff54055232008-10-27 17:20:55 +00004254 S += "\nstatic void __";
4255 S += funcName;
4256 S += "_block_dispose_" + utostr(i);
4257 S += "(" + StructRef;
4258 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004259 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004260 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004261 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004262 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004263 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004264 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004265 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004266 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004267 }
Mike Stump1eb44332009-09-09 15:08:12 +00004268 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004269 return S;
4270}
4271
Steve Naroff01aec112009-12-06 21:14:13 +00004272std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4273 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004274 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004275 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Steve Naroff54055232008-10-27 17:20:55 +00004277 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004278 S += " struct " + Desc;
4279 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004280
Steve Naroff01aec112009-12-06 21:14:13 +00004281 Constructor += "(void *fp, "; // Invoke function pointer.
4282 Constructor += "struct " + Desc; // Descriptor pointer.
4283 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Steve Naroff54055232008-10-27 17:20:55 +00004285 if (BlockDeclRefs.size()) {
4286 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004287 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004288 E = BlockByCopyDecls.end(); I != E; ++I) {
4289 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004290 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004291 std::string ArgName = "_" + FieldName;
4292 // Handle nested closure invocation. For example:
4293 //
4294 // void (^myImportedBlock)(void);
4295 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004296 //
Steve Naroff54055232008-10-27 17:20:55 +00004297 // void (^anotherBlock)(void);
4298 // anotherBlock = ^(void) {
4299 // myImportedBlock(); // import and invoke the closure
4300 // };
4301 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004302 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004303 S += "struct __block_impl *";
4304 Constructor += ", void *" + ArgName;
4305 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004306 QualType QT = (*I)->getType();
4307 if (HasLocalVariableExternalStorage(*I))
4308 QT = Context->getPointerType(QT);
4309 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4310 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004311 Constructor += ", " + ArgName;
4312 }
4313 S += FieldName + ";\n";
4314 }
4315 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004316 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004317 E = BlockByRefDecls.end(); I != E; ++I) {
4318 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004319 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004320 std::string ArgName = "_" + FieldName;
4321 // Handle nested closure invocation. For example:
4322 //
4323 // void (^myImportedBlock)(void);
4324 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004325 //
Steve Naroff54055232008-10-27 17:20:55 +00004326 // void (^anotherBlock)(void);
4327 // anotherBlock = ^(void) {
4328 // myImportedBlock(); // import and invoke the closure
4329 // };
4330 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004331 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004332 S += "struct __block_impl *";
4333 Constructor += ", void *" + ArgName;
4334 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004335 std::string TypeString;
4336 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004337 TypeString += " *";
4338 FieldName = TypeString + FieldName;
4339 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004340 Constructor += ", " + ArgName;
4341 }
4342 S += FieldName + "; // by ref\n";
4343 }
4344 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004345 Constructor += ", int flags=0)";
4346 // Initialize all "by copy" arguments.
4347 bool firsTime = true;
4348 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4349 E = BlockByCopyDecls.end(); I != E; ++I) {
4350 std::string Name = (*I)->getNameAsString();
4351 if (firsTime) {
4352 Constructor += " : ";
4353 firsTime = false;
4354 }
4355 else
4356 Constructor += ", ";
4357 if (isTopLevelBlockPointerType((*I)->getType()))
4358 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4359 else
4360 Constructor += Name + "(_" + Name + ")";
4361 }
4362 // Initialize all "by ref" arguments.
4363 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4364 E = BlockByRefDecls.end(); I != E; ++I) {
4365 std::string Name = (*I)->getNameAsString();
4366 if (firsTime) {
4367 Constructor += " : ";
4368 firsTime = false;
4369 }
4370 else
4371 Constructor += ", ";
4372 if (isTopLevelBlockPointerType((*I)->getType()))
4373 Constructor += Name + "((struct __block_impl *)_"
4374 + Name + "->__forwarding)";
4375 else
4376 Constructor += Name + "(_" + Name + "->__forwarding)";
4377 }
4378
4379 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004380 if (GlobalVarDecl)
4381 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4382 else
4383 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004384 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Steve Naroff01aec112009-12-06 21:14:13 +00004386 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004387 } else {
4388 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004389 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004390 if (GlobalVarDecl)
4391 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4392 else
4393 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004394 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4395 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004396 }
4397 Constructor += " ";
4398 Constructor += "}\n";
4399 S += Constructor;
4400 S += "};\n";
4401 return S;
4402}
4403
Steve Naroff01aec112009-12-06 21:14:13 +00004404std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4405 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004406 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004407 unsigned hasCopy) {
4408 std::string S = "\nstatic struct " + DescTag;
4409
4410 S += " {\n unsigned long reserved;\n";
4411 S += " unsigned long Block_size;\n";
4412 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004413 S += " void (*copy)(struct ";
4414 S += ImplTag; S += "*, struct ";
4415 S += ImplTag; S += "*);\n";
4416
4417 S += " void (*dispose)(struct ";
4418 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004419 }
4420 S += "} ";
4421
4422 S += DescTag + "_DATA = { 0, sizeof(struct ";
4423 S += ImplTag + ")";
4424 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004425 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4426 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004427 }
4428 S += "};\n";
4429 return S;
4430}
4431
Steve Naroff54055232008-10-27 17:20:55 +00004432void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004433 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004434 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004435 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004436 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004437 bool RewriteSC = (GlobalVarDecl &&
4438 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004439 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004440 GlobalVarDecl->getType().getCVRQualifiers());
4441 if (RewriteSC) {
4442 std::string SC(" void __");
4443 SC += GlobalVarDecl->getNameAsString();
4444 SC += "() {}";
4445 InsertText(FunLocStart, SC);
4446 }
4447
Steve Naroff54055232008-10-27 17:20:55 +00004448 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004449 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4450 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004451 // Need to copy-in the inner copied-in variables not actually used in this
4452 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004453 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4454 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4455 ValueDecl *VD = Exp->getDecl();
4456 BlockDeclRefs.push_back(Exp);
4457 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4458 BlockByCopyDeclsPtrSet.insert(VD);
4459 BlockByCopyDecls.push_back(VD);
4460 }
4461 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4462 BlockByRefDeclsPtrSet.insert(VD);
4463 BlockByRefDecls.push_back(VD);
4464 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004465 // imported objects in the inner blocks not used in the outer
4466 // blocks must be copied/disposed in the outer block as well.
4467 if (Exp->isByRef() ||
4468 VD->getType()->isObjCObjectPointerType() ||
4469 VD->getType()->isBlockPointerType())
4470 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004471 }
Steve Naroff54055232008-10-27 17:20:55 +00004472
Daniel Dunbar4087f272010-08-17 22:39:59 +00004473 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4474 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004475
Steve Naroff01aec112009-12-06 21:14:13 +00004476 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004477
Benjamin Kramerd999b372010-02-14 14:14:16 +00004478 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004479
Steve Naroff01aec112009-12-06 21:14:13 +00004480 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004481
Benjamin Kramerd999b372010-02-14 14:14:16 +00004482 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004483
4484 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004485 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004486 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004487 }
Steve Naroff01aec112009-12-06 21:14:13 +00004488 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4489 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004490 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004491
Steve Naroff54055232008-10-27 17:20:55 +00004492 BlockDeclRefs.clear();
4493 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004494 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004495 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004496 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004497 ImportedBlockDecls.clear();
4498 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004499 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004500 // Must insert any 'const/volatile/static here. Since it has been
4501 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004502 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004503 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004504 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004505 if (GlobalVarDecl->getType().isConstQualified())
4506 SC += "const ";
4507 if (GlobalVarDecl->getType().isVolatileQualified())
4508 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004509 if (GlobalVarDecl->getType().isRestrictQualified())
4510 SC += "restrict ";
4511 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004512 }
4513
Steve Naroff54055232008-10-27 17:20:55 +00004514 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004515 InnerDeclRefsCount.clear();
4516 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004517 RewrittenBlockExprs.clear();
4518}
4519
4520void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4521 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004522 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Steve Naroff54055232008-10-27 17:20:55 +00004524 SynthesizeBlockLiterals(FunLocStart, FuncName);
4525}
4526
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004527static void BuildUniqueMethodName(std::string &Name,
4528 ObjCMethodDecl *MD) {
4529 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004530 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004531 Name += "__" + MD->getSelector().getAsString();
4532 // Convert colons to underscores.
4533 std::string::size_type loc = 0;
4534 while ((loc = Name.find(":", loc)) != std::string::npos)
4535 Name.replace(loc, 1, "_");
4536}
4537
Steve Naroff54055232008-10-27 17:20:55 +00004538void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004539 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4540 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004541 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004542 std::string FuncName;
4543 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004544 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004545}
4546
4547void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4548 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4549 CI != E; ++CI)
4550 if (*CI) {
4551 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4552 GetBlockDeclRefExprs(CBE->getBody());
4553 else
4554 GetBlockDeclRefExprs(*CI);
4555 }
4556 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004557 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004558 // FIXME: Handle enums.
4559 if (!isa<FunctionDecl>(CDRE->getDecl()))
4560 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004561 }
4562 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4563 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4564 BlockDeclRefExpr *BDRE =
4565 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004566 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004567 BlockDeclRefs.push_back(BDRE);
4568 }
4569
Steve Naroff54055232008-10-27 17:20:55 +00004570 return;
4571}
4572
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004573void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4574 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004575 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004576 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4577 CI != E; ++CI)
4578 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004579 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4580 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004581 GetInnerBlockDeclRefExprs(CBE->getBody(),
4582 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004583 InnerContexts);
4584 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004585 else
4586 GetInnerBlockDeclRefExprs(*CI,
4587 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004588 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589
4590 }
4591 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004592 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004593 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004594 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004595 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004596 }
4597 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4598 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4599 if (Var->isFunctionOrMethodVarDecl())
4600 ImportedLocalExternalDecls.insert(Var);
4601 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004602
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004603 return;
4604}
4605
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004606/// convertFunctionTypeOfBlocks - This routine converts a function type
4607/// whose result type may be a block pointer or whose argument type(s)
4608/// might be block pointers to an equivalent funtion type replacing
4609/// all block pointers to function pointers.
4610QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4611 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4612 // FTP will be null for closures that don't take arguments.
4613 // Generate a funky cast.
4614 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004615 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004616 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004617
4618 if (FTP) {
4619 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4620 E = FTP->arg_type_end(); I && (I != E); ++I) {
4621 QualType t = *I;
4622 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004623 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004624 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004625 ArgTypes.push_back(t);
4626 }
4627 }
4628 QualType FuncType;
4629 // FIXME. Does this work if block takes no argument but has a return type
4630 // which is of block type?
4631 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004632 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004633 else FuncType = QualType(FT, 0);
4634 return FuncType;
4635}
4636
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004637Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004638 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004639 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004641 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004642 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004643 } else if (const BlockDeclRefExpr *CDRE =
4644 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004645 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004646 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004647 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004648 }
4649 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4650 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4651 }
4652 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4653 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4654 else if (const ConditionalOperator *CEXPR =
4655 dyn_cast<ConditionalOperator>(BlockExp)) {
4656 Expr *LHSExp = CEXPR->getLHS();
4657 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4658 Expr *RHSExp = CEXPR->getRHS();
4659 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4660 Expr *CONDExp = CEXPR->getCond();
4661 ConditionalOperator *CondExpr =
4662 new (Context) ConditionalOperator(CONDExp,
4663 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004664 SourceLocation(), cast<Expr>(RHSStmt),
4665 (Expr*)0,
John McCall09431682010-11-18 19:01:18 +00004666 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004667 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004668 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4669 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004670 } else {
4671 assert(1 && "RewriteBlockClass: Bad type");
4672 }
4673 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004674 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004675 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004676 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004677 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004679 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004680 SourceLocation(),
4681 &Context->Idents.get("__block_impl"));
4682 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004683
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004684 // Generate a funky cast.
4685 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004686
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004687 // Push the block argument type.
4688 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004689 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004690 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 E = FTP->arg_type_end(); I && (I != E); ++I) {
4692 QualType t = *I;
4693 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004694 if (!convertBlockPointerToFunctionPointer(t))
4695 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004696 ArgTypes.push_back(t);
4697 }
Steve Naroff54055232008-10-27 17:20:55 +00004698 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004699 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004700 QualType PtrToFuncCastType
4701 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004703 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004704
John McCall9d125032010-01-15 18:39:57 +00004705 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004706 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004707 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004708 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004709 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4710 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004711 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Douglas Gregor44b43212008-12-11 16:49:14 +00004713 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004714 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004715 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004716 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004717 FD->getType(), VK_LValue,
4718 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004719
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004720
John McCall9d125032010-01-15 18:39:57 +00004721 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004722 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004723 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004725 llvm::SmallVector<Expr*, 8> BlkExprs;
4726 // Add the implicit argument.
4727 BlkExprs.push_back(BlkCast);
4728 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004729 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004730 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004731 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004732 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004733 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4734 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004735 Exp->getType(), VK_RValue,
4736 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004737 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004738}
4739
Steve Naroff621edce2009-04-29 16:37:50 +00004740// We need to return the rewritten expression to handle cases where the
4741// BlockDeclRefExpr is embedded in another expression being rewritten.
4742// For example:
4743//
4744// int main() {
4745// __block Foo *f;
4746// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004747//
Steve Naroff621edce2009-04-29 16:37:50 +00004748// void (^myblock)() = ^() {
4749// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4750// i = 77;
4751// };
4752//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004753Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004754 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004755 // for each DeclRefExp where BYREFVAR is name of the variable.
4756 ValueDecl *VD;
4757 bool isArrow = true;
4758 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4759 VD = BDRE->getDecl();
4760 else {
4761 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4762 isArrow = false;
4763 }
4764
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004765 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4766 &Context->Idents.get("__forwarding"),
4767 Context->VoidPtrTy, 0,
4768 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004769 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4770 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004771 FD->getType(), VK_LValue,
4772 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004773
Daniel Dunbar4087f272010-08-17 22:39:59 +00004774 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004775 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4776 &Context->Idents.get(Name),
4777 Context->VoidPtrTy, 0,
4778 /*BitWidth=*/0, /*Mutable=*/true);
4779 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004780 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004781
4782
4783
Steve Naroffdf8570d2009-02-02 17:19:26 +00004784 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004785 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4786 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004787 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004788 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004789}
4790
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004791// Rewrites the imported local variable V with external storage
4792// (static, extern, etc.) as *V
4793//
4794Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4795 ValueDecl *VD = DRE->getDecl();
4796 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4797 if (!ImportedLocalExternalDecls.count(Var))
4798 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004799 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4800 VK_LValue, OK_Ordinary,
4801 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004802 // Need parens to enforce precedence.
4803 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4804 Exp);
4805 ReplaceStmt(DRE, PE);
4806 return PE;
4807}
4808
Steve Naroffb2f9e512008-11-03 23:29:32 +00004809void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4810 SourceLocation LocStart = CE->getLParenLoc();
4811 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004812
4813 // Need to avoid trying to rewrite synthesized casts.
4814 if (LocStart.isInvalid())
4815 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004816 // Need to avoid trying to rewrite casts contained in macros.
4817 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4818 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Steve Naroff54055232008-10-27 17:20:55 +00004820 const char *startBuf = SM->getCharacterData(LocStart);
4821 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004822 QualType QT = CE->getType();
4823 const Type* TypePtr = QT->getAs<Type>();
4824 if (isa<TypeOfExprType>(TypePtr)) {
4825 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4826 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4827 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004828 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004829 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004830 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004831 return;
4832 }
Steve Naroff54055232008-10-27 17:20:55 +00004833 // advance the location to startArgList.
4834 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004835
Steve Naroff54055232008-10-27 17:20:55 +00004836 while (*argPtr++ && (argPtr < endBuf)) {
4837 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004838 case '^':
4839 // Replace the '^' with '*'.
4840 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004841 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004842 break;
Steve Naroff54055232008-10-27 17:20:55 +00004843 }
4844 }
4845 return;
4846}
4847
4848void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4849 SourceLocation DeclLoc = FD->getLocation();
4850 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Steve Naroff54055232008-10-27 17:20:55 +00004852 // We have 1 or more arguments that have closure pointers.
4853 const char *startBuf = SM->getCharacterData(DeclLoc);
4854 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Steve Naroff54055232008-10-27 17:20:55 +00004856 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Steve Naroff54055232008-10-27 17:20:55 +00004858 parenCount++;
4859 // advance the location to startArgList.
4860 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4861 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004862
Steve Naroff54055232008-10-27 17:20:55 +00004863 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Steve Naroff54055232008-10-27 17:20:55 +00004865 while (*argPtr++ && parenCount) {
4866 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004867 case '^':
4868 // Replace the '^' with '*'.
4869 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004870 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004871 break;
4872 case '(':
4873 parenCount++;
4874 break;
4875 case ')':
4876 parenCount--;
4877 break;
Steve Naroff54055232008-10-27 17:20:55 +00004878 }
4879 }
4880 return;
4881}
4882
4883bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004884 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004885 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004886 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004887 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004888 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004889 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004890 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004891 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004892 }
4893 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004894 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004895 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004896 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004897 return true;
4898 }
4899 return false;
4900}
4901
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004902bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4903 const FunctionProtoType *FTP;
4904 const PointerType *PT = QT->getAs<PointerType>();
4905 if (PT) {
4906 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4907 } else {
4908 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4909 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4910 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4911 }
4912 if (FTP) {
4913 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004914 E = FTP->arg_type_end(); I != E; ++I) {
4915 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004916 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004917 if ((*I)->isObjCObjectPointerType() &&
4918 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4919 return true;
4920 }
4921
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004922 }
4923 return false;
4924}
4925
Ted Kremenek8189cde2009-02-07 01:47:29 +00004926void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4927 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004928 const char *argPtr = strchr(Name, '(');
4929 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004930
Steve Naroff54055232008-10-27 17:20:55 +00004931 LParen = argPtr; // output the start.
4932 argPtr++; // skip past the left paren.
4933 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004934
Steve Naroff54055232008-10-27 17:20:55 +00004935 while (*argPtr && parenCount) {
4936 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004937 case '(': parenCount++; break;
4938 case ')': parenCount--; break;
4939 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004940 }
4941 if (parenCount) argPtr++;
4942 }
4943 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4944 RParen = argPtr; // output the end
4945}
4946
4947void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4948 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4949 RewriteBlockPointerFunctionArgs(FD);
4950 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004951 }
Steve Naroff54055232008-10-27 17:20:55 +00004952 // Handle Variables and Typedefs.
4953 SourceLocation DeclLoc = ND->getLocation();
4954 QualType DeclT;
4955 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4956 DeclT = VD->getType();
4957 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4958 DeclT = TDD->getUnderlyingType();
4959 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4960 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004961 else
Steve Naroff54055232008-10-27 17:20:55 +00004962 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004963
Steve Naroff54055232008-10-27 17:20:55 +00004964 const char *startBuf = SM->getCharacterData(DeclLoc);
4965 const char *endBuf = startBuf;
4966 // scan backward (from the decl location) for the end of the previous decl.
4967 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4968 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004969 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4970 std::string buf;
4971 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004972 // *startBuf != '^' if we are dealing with a pointer to function that
4973 // may take block argument types (which will be handled below).
4974 if (*startBuf == '^') {
4975 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004976 buf = '*';
4977 startBuf++;
4978 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004979 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004980 while (*startBuf != ')') {
4981 buf += *startBuf;
4982 startBuf++;
4983 OrigLength++;
4984 }
4985 buf += ')';
4986 OrigLength++;
4987
4988 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4989 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004990 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004991 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004992 DeclLoc = ND->getLocation();
4993 startBuf = SM->getCharacterData(DeclLoc);
4994 const char *argListBegin, *argListEnd;
4995 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4996 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004997 if (*argListBegin == '^')
4998 buf += '*';
4999 else if (*argListBegin == '<') {
5000 buf += "/*";
5001 buf += *argListBegin++;
5002 OrigLength++;;
5003 while (*argListBegin != '>') {
5004 buf += *argListBegin++;
5005 OrigLength++;
5006 }
5007 buf += *argListBegin;
5008 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005009 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005010 else
5011 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005012 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005013 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005014 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005015 buf += ')';
5016 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005017 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005018 ReplaceText(Start, OrigLength, buf);
5019
Steve Naroff54055232008-10-27 17:20:55 +00005020 return;
5021}
5022
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005023
5024/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5025/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5026/// struct Block_byref_id_object *src) {
5027/// _Block_object_assign (&_dest->object, _src->object,
5028/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5029/// [|BLOCK_FIELD_IS_WEAK]) // object
5030/// _Block_object_assign(&_dest->object, _src->object,
5031/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5032/// [|BLOCK_FIELD_IS_WEAK]) // block
5033/// }
5034/// And:
5035/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5036/// _Block_object_dispose(_src->object,
5037/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5038/// [|BLOCK_FIELD_IS_WEAK]) // object
5039/// _Block_object_dispose(_src->object,
5040/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5041/// [|BLOCK_FIELD_IS_WEAK]) // block
5042/// }
5043
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005044std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5045 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005046 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005047 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005048 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005049 CopyDestroyCache.insert(flag);
5050 S = "static void __Block_byref_id_object_copy_";
5051 S += utostr(flag);
5052 S += "(void *dst, void *src) {\n";
5053
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005054 // offset into the object pointer is computed as:
5055 // void * + void* + int + int + void* + void *
5056 unsigned IntSize =
5057 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5058 unsigned VoidPtrSize =
5059 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5060
5061 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5062 S += " _Block_object_assign((char*)dst + ";
5063 S += utostr(offset);
5064 S += ", *(void * *) ((char*)src + ";
5065 S += utostr(offset);
5066 S += "), ";
5067 S += utostr(flag);
5068 S += ");\n}\n";
5069
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005070 S += "static void __Block_byref_id_object_dispose_";
5071 S += utostr(flag);
5072 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005073 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5074 S += utostr(offset);
5075 S += "), ";
5076 S += utostr(flag);
5077 S += ");\n}\n";
5078 return S;
5079}
5080
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005081/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5082/// the declaration into:
5083/// struct __Block_byref_ND {
5084/// void *__isa; // NULL for everything except __weak pointers
5085/// struct __Block_byref_ND *__forwarding;
5086/// int32_t __flags;
5087/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005088/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5089/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005090/// typex ND;
5091/// };
5092///
5093/// It then replaces declaration of ND variable with:
5094/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5095/// __size=sizeof(struct __Block_byref_ND),
5096/// ND=initializer-if-any};
5097///
5098///
5099void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005100 // Insert declaration for the function in which block literal is
5101 // used.
5102 if (CurFunctionDeclToDeclareForBlock)
5103 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005104 int flag = 0;
5105 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005106 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005107 if (DeclLoc.isInvalid())
5108 // If type location is missing, it is because of missing type (a warning).
5109 // Use variable's location which is good for this case.
5110 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005111 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005112 SourceLocation X = ND->getLocEnd();
5113 X = SM->getInstantiationLoc(X);
5114 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005115 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005116 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005117 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005118 ByrefType += " {\n";
5119 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005120 RewriteByRefString(ByrefType, Name, ND);
5121 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005122 ByrefType += " int __flags;\n";
5123 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005124 // Add void *__Block_byref_id_object_copy;
5125 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005126 QualType Ty = ND->getType();
5127 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5128 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005129 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5130 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005131 }
5132
5133 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005134 ByrefType += " " + Name + ";\n";
5135 ByrefType += "};\n";
5136 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005137 SourceLocation FunLocStart;
5138 if (CurFunctionDef)
5139 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5140 else {
5141 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5142 FunLocStart = CurMethodDef->getLocStart();
5143 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005144 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005145 if (Ty.isObjCGCWeak()) {
5146 flag |= BLOCK_FIELD_IS_WEAK;
5147 isa = 1;
5148 }
5149
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005150 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005151 flag = BLOCK_BYREF_CALLER;
5152 QualType Ty = ND->getType();
5153 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5154 if (Ty->isBlockPointerType())
5155 flag |= BLOCK_FIELD_IS_BLOCK;
5156 else
5157 flag |= BLOCK_FIELD_IS_OBJECT;
5158 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005159 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005160 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005161 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005162
5163 // struct __Block_byref_ND ND =
5164 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5165 // initializer-if-any};
5166 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005167 unsigned flags = 0;
5168 if (HasCopyAndDispose)
5169 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005170 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005171 ByrefType.clear();
5172 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005173 std::string ForwardingCastType("(");
5174 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005175 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005176 ByrefType += " " + Name + " = {(void*)";
5177 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005178 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005179 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005180 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005181 ByrefType += "sizeof(";
5182 RewriteByRefString(ByrefType, Name, ND);
5183 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005184 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005185 ByrefType += ", __Block_byref_id_object_copy_";
5186 ByrefType += utostr(flag);
5187 ByrefType += ", __Block_byref_id_object_dispose_";
5188 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005189 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005190 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005191 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005192 }
5193 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005194 SourceLocation startLoc;
5195 Expr *E = ND->getInit();
5196 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5197 startLoc = ECE->getLParenLoc();
5198 else
5199 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005200 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005201 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005202 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005203 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005204 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005205 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005206 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005207 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005208 ByrefType += "sizeof(";
5209 RewriteByRefString(ByrefType, Name, ND);
5210 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005211 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005212 ByrefType += "__Block_byref_id_object_copy_";
5213 ByrefType += utostr(flag);
5214 ByrefType += ", __Block_byref_id_object_dispose_";
5215 ByrefType += utostr(flag);
5216 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005217 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005218 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005219
5220 // Complete the newly synthesized compound expression by inserting a right
5221 // curly brace before the end of the declaration.
5222 // FIXME: This approach avoids rewriting the initializer expression. It
5223 // also assumes there is only one declarator. For example, the following
5224 // isn't currently supported by this routine (in general):
5225 //
5226 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5227 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005228 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5229 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005230 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5231 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005232 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005233
Benjamin Kramerd999b372010-02-14 14:14:16 +00005234 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005235 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005236 return;
5237}
5238
Mike Stump1eb44332009-09-09 15:08:12 +00005239void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005240 // Add initializers for any closure decl refs.
5241 GetBlockDeclRefExprs(Exp->getBody());
5242 if (BlockDeclRefs.size()) {
5243 // Unique all "by copy" declarations.
5244 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005245 if (!BlockDeclRefs[i]->isByRef()) {
5246 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5247 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5248 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5249 }
5250 }
Steve Naroff54055232008-10-27 17:20:55 +00005251 // Unique all "by ref" declarations.
5252 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5253 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005254 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5255 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5256 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5257 }
Steve Naroff54055232008-10-27 17:20:55 +00005258 }
5259 // Find any imported blocks...they will need special attention.
5260 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005261 if (BlockDeclRefs[i]->isByRef() ||
5262 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005263 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005264 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005265 }
5266}
5267
Daniel Dunbar4087f272010-08-17 22:39:59 +00005268FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005269 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005270 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005271 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005272 ID, FType, 0, SC_Extern,
5273 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005274}
5275
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005276Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5277 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005278 Blocks.push_back(Exp);
5279
5280 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005281
5282 // Add inner imported variables now used in current block.
5283 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005284 if (!InnerBlockDeclRefs.empty()) {
5285 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5286 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5287 ValueDecl *VD = Exp->getDecl();
5288 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005289 // We need to save the copied-in variables in nested
5290 // blocks because it is needed at the end for some of the API generations.
5291 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005292 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5293 BlockDeclRefs.push_back(Exp);
5294 BlockByCopyDeclsPtrSet.insert(VD);
5295 BlockByCopyDecls.push_back(VD);
5296 }
5297 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5298 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5299 BlockDeclRefs.push_back(Exp);
5300 BlockByRefDeclsPtrSet.insert(VD);
5301 BlockByRefDecls.push_back(VD);
5302 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005303 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005304 // Find any imported blocks...they will need special attention.
5305 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5306 if (InnerBlockDeclRefs[i]->isByRef() ||
5307 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5308 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5309 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005310 }
5311 InnerDeclRefsCount.push_back(countOfInnerDecls);
5312
Steve Narofffa15fd92008-10-28 20:29:00 +00005313 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005314
Steve Narofffa15fd92008-10-28 20:29:00 +00005315 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005316 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005317 else if (CurMethodDef)
5318 BuildUniqueMethodName(FuncName, CurMethodDef);
5319 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005320 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005321
Steve Narofffa15fd92008-10-28 20:29:00 +00005322 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Steve Narofffa15fd92008-10-28 20:29:00 +00005324 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5325 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005326
Steve Narofffa15fd92008-10-28 20:29:00 +00005327 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005328 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5329 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005330
5331 FunctionDecl *FD;
5332 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005333
Steve Narofffa15fd92008-10-28 20:29:00 +00005334 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005335 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005336 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5337 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005338
Steve Narofffa15fd92008-10-28 20:29:00 +00005339 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005340
Steve Narofffdc03722008-10-29 21:23:59 +00005341 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005342 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005343 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005344 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005345 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005346 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005347 InitExprs.push_back(castExpr);
5348
Steve Naroff01aec112009-12-06 21:14:13 +00005349 // Initialize the block descriptor.
5350 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005351
Steve Naroff01aec112009-12-06 21:14:13 +00005352 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5353 &Context->Idents.get(DescData.c_str()),
5354 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005355 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005356 UnaryOperator *DescRefExpr =
5357 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5358 Context->VoidPtrTy,
5359 VK_LValue,
5360 SourceLocation()),
5361 UO_AddrOf,
5362 Context->getPointerType(Context->VoidPtrTy),
5363 VK_RValue, OK_Ordinary,
5364 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005365 InitExprs.push_back(DescRefExpr);
5366
Steve Narofffa15fd92008-10-28 20:29:00 +00005367 // Add initializers for any closure decl refs.
5368 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005369 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005371 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005373 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005374 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005375 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005376 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5377 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005378 if (HasLocalVariableExternalStorage(*I)) {
5379 QualType QT = (*I)->getType();
5380 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005381 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5382 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005383 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005384 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005385 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005386 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5387 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005388 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005389 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005390 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005391 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005392 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5393 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005394 if (HasLocalVariableExternalStorage(*I)) {
5395 QualType QT = (*I)->getType();
5396 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005397 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5398 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005399 }
5400
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 }
Mike Stump1eb44332009-09-09 15:08:12 +00005402 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005403 }
5404 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005405 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005406 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005407 ValueDecl *ND = (*I);
5408 std::string Name(ND->getNameAsString());
5409 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005410 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005411 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5412 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005413 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005414 SourceLocation(), II);
5415 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5416 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5417
Daniel Dunbar4087f272010-08-17 22:39:59 +00005418 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005419 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5420 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005421 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005422 Context->getPointerType(Exp->getType()),
5423 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005424 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005425 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 }
5427 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005428 if (ImportedBlockDecls.size()) {
5429 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5430 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005431 unsigned IntSize =
5432 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005433 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5434 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005435 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005436 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005437 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005438 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005439 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005440 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005441 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005442 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005443 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 BlockDeclRefs.clear();
5445 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005446 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005447 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005448 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005449 ImportedBlockDecls.clear();
5450 return NewRep;
5451}
5452
5453//===----------------------------------------------------------------------===//
5454// Function Body / Expression rewriting
5455//===----------------------------------------------------------------------===//
5456
Steve Naroffc77a6362008-12-04 16:24:46 +00005457// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5458// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5459// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5460// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5461// Since the rewriter isn't capable of rewriting rewritten code, it's important
5462// we get this right.
5463void RewriteObjC::CollectPropertySetters(Stmt *S) {
5464 // Perform a bottom up traversal of all children.
5465 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5466 CI != E; ++CI)
5467 if (*CI)
5468 CollectPropertySetters(*CI);
5469
5470 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5471 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005472 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5473 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005474 }
5475 }
5476}
5477
Steve Narofffa15fd92008-10-28 20:29:00 +00005478Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005479 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005480 isa<DoStmt>(S) || isa<ForStmt>(S))
5481 Stmts.push_back(S);
5482 else if (isa<ObjCForCollectionStmt>(S)) {
5483 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005484 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005485 }
Mike Stump1eb44332009-09-09 15:08:12 +00005486
Steve Narofffa15fd92008-10-28 20:29:00 +00005487 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005488
Steve Narofffa15fd92008-10-28 20:29:00 +00005489 // Perform a bottom up rewrite of all children.
5490 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5491 CI != E; ++CI)
5492 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005493 Stmt *newStmt;
5494 Stmt *S = (*CI);
5495 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5496 Expr *OldBase = IvarRefExpr->getBase();
5497 bool replaced = false;
5498 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5499 if (replaced) {
5500 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5501 ReplaceStmt(OldBase, IRE->getBase());
5502 else
5503 ReplaceStmt(S, newStmt);
5504 }
5505 }
5506 else
5507 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005508 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005509 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005510 // If dealing with an assignment with LHS being a property reference
5511 // expression, the entire assignment tree is rewritten into a property
5512 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5513 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005514 if (Expr *Exp = dyn_cast<Expr>(S))
John McCall12f78a62010-12-02 01:19:52 +00005515 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005516 if (PropSetters[Exp]) {
5517 ++CI;
5518 continue;
5519 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005520 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005521 }
Mike Stump1eb44332009-09-09 15:08:12 +00005522
Steve Narofffa15fd92008-10-28 20:29:00 +00005523 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005524 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005525 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5526 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005527 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005528 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005529 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005531 Stmt *SaveCurrentBody = CurrentBody;
5532 CurrentBody = BE->getBody();
5533 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005534 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005535 CurrentBody = SaveCurrentBody;
5536 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005537 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005538 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005539 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005540 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005541
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005542 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5543
Steve Narofffa15fd92008-10-28 20:29:00 +00005544 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005545 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005546 return blockTranscribed;
5547 }
5548 // Handle specific things.
5549 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5550 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005551
John McCall12f78a62010-12-02 01:19:52 +00005552 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005553 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5554 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5555
5556 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005557 if (BinOp) {
5558 // Because the rewriter doesn't allow us to rewrite rewritten code,
5559 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005560 DisableReplaceStmt = true;
5561 // Save the source range. Even if we disable the replacement, the
5562 // rewritten node will have been inserted into the tree. If the synthesized
5563 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005564 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005565 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5566 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005567 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005568 // Need to rewrite the ivar access expression if need be.
5569 if (isa<ObjCIvarRefExpr>(newStmt)) {
5570 bool replaced = false;
5571 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5572 }
5573
Steve Naroffb619d952008-12-09 12:56:34 +00005574 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005575 //
5576 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5577 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5578 // to see the original expression). Consider this example:
5579 //
5580 // Foo *obj1, *obj2;
5581 //
5582 // obj1.i = [obj2 rrrr];
5583 //
5584 // 'BinOp' for the previous expression looks like:
5585 //
5586 // (BinaryOperator 0x231ccf0 'int' '='
5587 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5588 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5589 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5590 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5591 //
5592 // 'newStmt' represents the rewritten message expression. For example:
5593 //
5594 // (CallExpr 0x231d300 'id':'struct objc_object *'
5595 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5596 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5597 // (CStyleCastExpr 0x231d220 'void *'
5598 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5599 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005600 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005601 // can be used as the setter argument. ReplaceStmt() will still 'see'
5602 // the original RHS (since we haven't altered BinOp).
5603 //
Mike Stump1eb44332009-09-09 15:08:12 +00005604 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005605 // node. As a result, we now leak the original AST nodes.
5606 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005607 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005608 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005609 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005610 }
5611 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005612
Steve Narofffa15fd92008-10-28 20:29:00 +00005613 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5614 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005615
Steve Narofffa15fd92008-10-28 20:29:00 +00005616 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5617 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005618
Steve Narofffa15fd92008-10-28 20:29:00 +00005619 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005620#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005621 // Before we rewrite it, put the original message expression in a comment.
5622 SourceLocation startLoc = MessExpr->getLocStart();
5623 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005624
Steve Narofffa15fd92008-10-28 20:29:00 +00005625 const char *startBuf = SM->getCharacterData(startLoc);
5626 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005627
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 std::string messString;
5629 messString += "// ";
5630 messString.append(startBuf, endBuf-startBuf+1);
5631 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005632
5633 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005634 // InsertText(clang::SourceLocation, char const*, unsigned int).
5635 // InsertText(startLoc, messString.c_str(), messString.size());
5636 // Tried this, but it didn't work either...
5637 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005638#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005639 return RewriteMessageExpr(MessExpr);
5640 }
Mike Stump1eb44332009-09-09 15:08:12 +00005641
Steve Narofffa15fd92008-10-28 20:29:00 +00005642 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5643 return RewriteObjCTryStmt(StmtTry);
5644
5645 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5646 return RewriteObjCSynchronizedStmt(StmtTry);
5647
5648 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5649 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005650
Steve Narofffa15fd92008-10-28 20:29:00 +00005651 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5652 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005653
5654 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005655 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005656 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005657 OrigStmtRange.getEnd());
5658 if (BreakStmt *StmtBreakStmt =
5659 dyn_cast<BreakStmt>(S))
5660 return RewriteBreakStmt(StmtBreakStmt);
5661 if (ContinueStmt *StmtContinueStmt =
5662 dyn_cast<ContinueStmt>(S))
5663 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005664
5665 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005666 // and cast exprs.
5667 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5668 // FIXME: What we're doing here is modifying the type-specifier that
5669 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005670 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005671 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5672 // the context of an ObjCForCollectionStmt. For example:
5673 // NSArray *someArray;
5674 // for (id <FooProtocol> index in someArray) ;
5675 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5676 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005677 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005678 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005679
Steve Narofffa15fd92008-10-28 20:29:00 +00005680 // Blocks rewrite rules.
5681 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5682 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005683 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005684 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005685 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005686 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005687 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005688 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005689 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005690 if (VD->hasAttr<BlocksAttr>()) {
5691 static unsigned uniqueByrefDeclCount = 0;
5692 assert(!BlockByRefDeclNo.count(ND) &&
5693 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5694 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005695 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005696 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005697 else
5698 RewriteTypeOfDecl(VD);
5699 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005700 }
5701 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005702 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005703 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005704 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005705 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5706 }
5707 }
5708 }
Mike Stump1eb44332009-09-09 15:08:12 +00005709
Steve Narofffa15fd92008-10-28 20:29:00 +00005710 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5711 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005712
5713 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005714 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5715 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005716 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5717 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005718 && "Statement stack mismatch");
5719 Stmts.pop_back();
5720 }
5721 // Handle blocks rewriting.
5722 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5723 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005724 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005726 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5727 ValueDecl *VD = DRE->getDecl();
5728 if (VD->hasAttr<BlocksAttr>())
5729 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005730 if (HasLocalVariableExternalStorage(VD))
5731 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005732 }
5733
Steve Narofffa15fd92008-10-28 20:29:00 +00005734 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005735 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005736 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005737 ReplaceStmt(S, BlockCall);
5738 return BlockCall;
5739 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005740 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005741 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005742 RewriteCastExpr(CE);
5743 }
5744#if 0
5745 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005746 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5747 ICE->getSubExpr(),
5748 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 // Get the new text.
5750 std::string SStr;
5751 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005752 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 const std::string &Str = Buf.str();
5754
5755 printf("CAST = %s\n", &Str[0]);
5756 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5757 delete S;
5758 return Replacement;
5759 }
5760#endif
5761 // Return this stmt unmodified.
5762 return S;
5763}
5764
Steve Naroff3d7e7862009-12-05 15:55:59 +00005765void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5766 for (RecordDecl::field_iterator i = RD->field_begin(),
5767 e = RD->field_end(); i != e; ++i) {
5768 FieldDecl *FD = *i;
5769 if (isTopLevelBlockPointerType(FD->getType()))
5770 RewriteBlockPointerDecl(FD);
5771 if (FD->getType()->isObjCQualifiedIdType() ||
5772 FD->getType()->isObjCQualifiedInterfaceType())
5773 RewriteObjCQualifiedInterfaceTypes(FD);
5774 }
5775}
5776
Steve Narofffa15fd92008-10-28 20:29:00 +00005777/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5778/// main file of the input.
5779void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005781 if (FD->isOverloadedOperator())
5782 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005783
Steve Narofffa15fd92008-10-28 20:29:00 +00005784 // Since function prototypes don't have ParmDecl's, we check the function
5785 // prototype. This enables us to rewrite function declarations and
5786 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005787 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005788
Sebastian Redld3a413d2009-04-26 20:35:05 +00005789 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005790 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005791 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005792 CurFunctionDeclToDeclareForBlock = FD;
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 FD->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 // This synthesizes and inserts the block "impl" struct, invoke function,
5804 // and any copy/dispose helper functions.
5805 InsertBlockLiteralsWithinFunction(FD);
5806 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005807 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005808 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005809 return;
5810 }
5811 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005812 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005813 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005814 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005815 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005816 Body =
5817 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5818 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005819 CurrentBody = 0;
5820 if (PropParentMap) {
5821 delete PropParentMap;
5822 PropParentMap = 0;
5823 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005824 InsertBlockLiteralsWithinMethod(MD);
5825 CurMethodDef = 0;
5826 }
5827 }
5828 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5829 ClassImplementation.push_back(CI);
5830 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5831 CategoryImplementation.push_back(CI);
5832 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5833 RewriteForwardClassDecl(CD);
5834 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5835 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005836 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005837 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005838 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005839 CheckFunctionPointerDecl(VD->getType(), VD);
5840 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005841 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005842 RewriteCastExpr(CE);
5843 }
5844 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005845 } else if (VD->getType()->isRecordType()) {
5846 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5847 if (RD->isDefinition())
5848 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005850 if (VD->getInit()) {
5851 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005852 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005853 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005854 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005855 CurrentBody = 0;
5856 if (PropParentMap) {
5857 delete PropParentMap;
5858 PropParentMap = 0;
5859 }
Mike Stump1eb44332009-09-09 15:08:12 +00005860 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005861 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005862 GlobalVarDecl = 0;
5863
5864 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005865 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005866 RewriteCastExpr(CE);
5867 }
5868 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005869 return;
5870 }
5871 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005872 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005873 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005874 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005875 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5876 return;
5877 }
5878 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005879 if (RD->isDefinition())
5880 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005881 return;
5882 }
5883 // Nothing yet.
5884}
5885
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005886void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005887 if (Diags.hasErrorOccurred())
5888 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005889
Steve Narofffa15fd92008-10-28 20:29:00 +00005890 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005891
Steve Naroff621edce2009-04-29 16:37:50 +00005892 // Here's a great place to add any extra declarations that may be needed.
5893 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005894 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005895 E = ProtocolExprDecls.end(); I != E; ++I)
5896 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5897
Benjamin Kramerd999b372010-02-14 14:14:16 +00005898 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005899 if (ClassImplementation.size() || CategoryImplementation.size())
5900 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005901
Steve Narofffa15fd92008-10-28 20:29:00 +00005902 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5903 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005904 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005905 Rewrite.getRewriteBufferFor(MainFileID)) {
5906 //printf("Changed:\n");
5907 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5908 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005909 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005910 }
Steve Narofface66252008-11-13 20:07:04 +00005911
Steve Naroff621edce2009-04-29 16:37:50 +00005912 if (ClassImplementation.size() || CategoryImplementation.size() ||
5913 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005914 // Rewrite Objective-c meta data*
5915 std::string ResultStr;
5916 SynthesizeMetaDataIntoBuffer(ResultStr);
5917 // Emit metadata.
5918 *OutFile << ResultStr;
5919 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005920 OutFile->flush();
5921}