blob: 875a0c7a84c531aa967886d6a88c5f8092472455 [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) {
John McCall7502c1d2011-02-13 04:07:26 +00001494 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001495 if (*CI) {
1496 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1497 if (newStmt)
1498 *CI = newStmt;
1499 }
1500 }
1501 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1502 SourceRange OrigStmtRange = S->getSourceRange();
1503 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1504 replaced);
1505 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001506 }
1507 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1508 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1509 return newStmt;
1510 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001511 return S;
1512}
1513
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514/// SynthCountByEnumWithState - To print:
1515/// ((unsigned int (*)
1516/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001517/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001519/// "countByEnumeratingWithState:objects:count:"),
1520/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521/// (id *)items, (unsigned int)16)
1522///
Steve Naroffb29b4272008-04-14 22:03:09 +00001523void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1525 "id *, unsigned int))(void *)objc_msgSend)";
1526 buf += "\n\t\t";
1527 buf += "((id)l_collection,\n\t\t";
1528 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1529 buf += "\n\t\t";
1530 buf += "&enumState, "
1531 "(id *)items, (unsigned int)16)";
1532}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001533
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001534/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1535/// statement to exit to its outer synthesized loop.
1536///
Steve Naroffb29b4272008-04-14 22:03:09 +00001537Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001538 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1539 return S;
1540 // replace break with goto __break_label
1541 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001543 SourceLocation startLoc = S->getLocStart();
1544 buf = "goto __break_label_";
1545 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001546 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001547
1548 return 0;
1549}
1550
1551/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1552/// statement to continue with its inner synthesized loop.
1553///
Steve Naroffb29b4272008-04-14 22:03:09 +00001554Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001555 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1556 return S;
1557 // replace continue with goto __continue_label
1558 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001560 SourceLocation startLoc = S->getLocStart();
1561 buf = "goto __continue_label_";
1562 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001563 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001565 return 0;
1566}
1567
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001568/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001569/// It rewrites:
1570/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001572/// Into:
1573/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001574/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001576/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001578/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001580/// if (limit) {
1581/// unsigned long startMutations = *enumState.mutationsPtr;
1582/// do {
1583/// unsigned long counter = 0;
1584/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001585/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001587/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001588/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001590/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001591/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592/// objects:items count:16]);
1593/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001594/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001595/// }
1596/// else
1597/// elem = nil;
1598/// }
1599///
Steve Naroffb29b4272008-04-14 22:03:09 +00001600Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001601 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001602 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001603 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001604 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001605 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001610 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001611 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 std::string buf;
1613 buf = "\n{\n\t";
1614 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1615 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001616 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001617 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001618 if (ElementType->isObjCQualifiedIdType() ||
1619 ElementType->isObjCQualifiedInterfaceType())
1620 // Simply use 'id' for all qualified types.
1621 elementTypeAsString = "id";
1622 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001623 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001624 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001626 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001627 buf += elementName;
1628 buf += ";\n\t";
1629 }
Chris Lattner06767512008-04-08 05:52:18 +00001630 else {
1631 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001632 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001633 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1634 if (VD->getType()->isObjCQualifiedIdType() ||
1635 VD->getType()->isObjCQualifiedInterfaceType())
1636 // Simply use 'id' for all qualified types.
1637 elementTypeAsString = "id";
1638 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001639 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001642 // struct __objcFastEnumerationState enumState = { 0 };
1643 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1644 // id items[16];
1645 buf += "id items[16];\n\t";
1646 // id l_collection = (id)
1647 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001648 // Find start location of 'collection' the hard way!
1649 const char *startCollectionBuf = startBuf;
1650 startCollectionBuf += 3; // skip 'for'
1651 startCollectionBuf = strchr(startCollectionBuf, '(');
1652 startCollectionBuf++; // skip '('
1653 // find 'in' and skip it.
1654 while (*startCollectionBuf != ' ' ||
1655 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1656 (*(startCollectionBuf+3) != ' ' &&
1657 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1658 startCollectionBuf++;
1659 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
1661 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001662 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001664 SourceLocation rightParenLoc = S->getRParenLoc();
1665 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1666 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001668
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001669 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1670 // objects:items count:16];
1671 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001672 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 // ((unsigned int (*)
1674 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001675 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001676 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001677 // "countByEnumeratingWithState:objects:count:"),
1678 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001679 // (id *)items, (unsigned int)16);
1680 buf += "unsigned long limit =\n\t\t";
1681 SynthCountByEnumWithState(buf);
1682 buf += ";\n\t";
1683 /// if (limit) {
1684 /// unsigned long startMutations = *enumState.mutationsPtr;
1685 /// do {
1686 /// unsigned long counter = 0;
1687 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001688 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001689 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001690 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001691 buf += "if (limit) {\n\t";
1692 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1693 buf += "do {\n\t\t";
1694 buf += "unsigned long counter = 0;\n\t\t";
1695 buf += "do {\n\t\t\t";
1696 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1697 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1698 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001699 buf += " = (";
1700 buf += elementTypeAsString;
1701 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001702 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001703 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001704
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001705 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001706 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001707 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001708 /// objects:items count:16]);
1709 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001710 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001711 /// }
1712 /// else
1713 /// elem = nil;
1714 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001715 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001716 buf = ";\n\t";
1717 buf += "__continue_label_";
1718 buf += utostr(ObjCBcLabelNo.back());
1719 buf += ": ;";
1720 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001721 buf += "} while (counter < limit);\n\t";
1722 buf += "} while (limit = ";
1723 SynthCountByEnumWithState(buf);
1724 buf += ");\n\t";
1725 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001726 buf += " = ((";
1727 buf += elementTypeAsString;
1728 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001729 buf += "__break_label_";
1730 buf += utostr(ObjCBcLabelNo.back());
1731 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001732 buf += "}\n\t";
1733 buf += "else\n\t\t";
1734 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001735 buf += " = ((";
1736 buf += elementTypeAsString;
1737 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001738 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001740 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001741 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001742 if (isa<CompoundStmt>(S->getBody())) {
1743 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001744 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001745 } else {
1746 /* Need to treat single statements specially. For example:
1747 *
1748 * for (A *a in b) if (stuff()) break;
1749 * for (A *a in b) xxxyy;
1750 *
1751 * The following code simply scans ahead to the semi to find the actual end.
1752 */
1753 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1754 const char *semiBuf = strchr(stmtBuf, ';');
1755 assert(semiBuf && "Can't find ';'");
1756 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001757 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001758 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001759 Stmts.pop_back();
1760 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001762}
1763
Mike Stump1eb44332009-09-09 15:08:12 +00001764/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001765/// This routine rewrites @synchronized(expr) stmt;
1766/// into:
1767/// objc_sync_enter(expr);
1768/// @try stmt @finally { objc_sync_exit(expr); }
1769///
Steve Naroffb29b4272008-04-14 22:03:09 +00001770Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001771 // Get the start location and compute the semi location.
1772 SourceLocation startLoc = S->getLocStart();
1773 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001775 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001776
1777 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001778 buf = "objc_sync_enter((id)";
1779 const char *lparenBuf = startBuf;
1780 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001781 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001782 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1783 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001784 // been rewritten! (which implies the SourceLocation's are invalid).
1785 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001786 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001787 while (*endBuf != ')') endBuf--;
1788 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001789 buf = ");\n";
1790 // declare a new scope with two variables, _stack and _rethrow.
1791 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1792 buf += "int buf[18/*32-bit i386*/];\n";
1793 buf += "char *pointers[4];} _stack;\n";
1794 buf += "id volatile _rethrow = 0;\n";
1795 buf += "objc_exception_try_enter(&_stack);\n";
1796 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001797 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001798 startLoc = S->getSynchBody()->getLocEnd();
1799 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Steve Naroffc7089f12008-08-19 13:04:19 +00001801 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001802 SourceLocation lastCurlyLoc = startLoc;
1803 buf = "}\nelse {\n";
1804 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001805 buf += "}\n";
1806 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001807 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001808
1809 std::string syncBuf;
1810 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001811 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001812 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001813 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001814 std::string syncExprBufS;
1815 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001816 syncExpr->printPretty(syncExprBuf, *Context, 0,
1817 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001818 syncBuf += syncExprBuf.str();
1819 syncBuf += ");";
1820
1821 buf += syncBuf;
1822 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001823 buf += "}\n";
1824 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Benjamin Kramerd999b372010-02-14 14:14:16 +00001826 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001827
1828 bool hasReturns = false;
1829 HasReturnStmts(S->getSynchBody(), hasReturns);
1830 if (hasReturns)
1831 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1832
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001833 return 0;
1834}
1835
Steve Naroffb85e77a2009-12-05 21:43:12 +00001836void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1837{
Steve Naroff8c565152008-12-05 17:03:39 +00001838 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001839 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001840 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001841 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001842
Steve Naroffb85e77a2009-12-05 21:43:12 +00001843 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001844 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001845 TryFinallyContainsReturnDiag);
1846 }
1847 return;
1848}
1849
Steve Naroffb85e77a2009-12-05 21:43:12 +00001850void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1851{
1852 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001853 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001854 if (*CI)
1855 HasReturnStmts(*CI, hasReturns);
1856
1857 if (isa<ReturnStmt>(S))
1858 hasReturns = true;
1859 return;
1860}
1861
1862void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1863 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001864 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001865 if (*CI) {
1866 RewriteTryReturnStmts(*CI);
1867 }
1868 if (isa<ReturnStmt>(S)) {
1869 SourceLocation startLoc = S->getLocStart();
1870 const char *startBuf = SM->getCharacterData(startLoc);
1871
1872 const char *semiBuf = strchr(startBuf, ';');
1873 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1874 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1875
1876 std::string buf;
1877 buf = "{ objc_exception_try_exit(&_stack); return";
1878
Benjamin Kramerd999b372010-02-14 14:14:16 +00001879 ReplaceText(startLoc, 6, buf);
1880 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001881 }
1882 return;
1883}
1884
1885void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1886 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001887 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888 if (*CI) {
1889 RewriteSyncReturnStmts(*CI, syncExitBuf);
1890 }
1891 if (isa<ReturnStmt>(S)) {
1892 SourceLocation startLoc = S->getLocStart();
1893 const char *startBuf = SM->getCharacterData(startLoc);
1894
1895 const char *semiBuf = strchr(startBuf, ';');
1896 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1897 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1898
1899 std::string buf;
1900 buf = "{ objc_exception_try_exit(&_stack);";
1901 buf += syncExitBuf;
1902 buf += " return";
1903
Benjamin Kramerd999b372010-02-14 14:14:16 +00001904 ReplaceText(startLoc, 6, buf);
1905 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001906 }
1907 return;
1908}
1909
Steve Naroffb29b4272008-04-14 22:03:09 +00001910Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001911 // Get the start location and compute the semi location.
1912 SourceLocation startLoc = S->getLocStart();
1913 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Steve Naroff75730982007-11-07 04:08:17 +00001915 assert((*startBuf == '@') && "bogus @try location");
1916
1917 std::string buf;
1918 // declare a new scope with two variables, _stack and _rethrow.
1919 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1920 buf += "int buf[18/*32-bit i386*/];\n";
1921 buf += "char *pointers[4];} _stack;\n";
1922 buf += "id volatile _rethrow = 0;\n";
1923 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001924 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001925
Benjamin Kramerd999b372010-02-14 14:14:16 +00001926 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Steve Naroff75730982007-11-07 04:08:17 +00001928 startLoc = S->getTryBody()->getLocEnd();
1929 startBuf = SM->getCharacterData(startLoc);
1930
1931 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Steve Naroff75730982007-11-07 04:08:17 +00001933 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001934 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001935 startLoc = startLoc.getFileLocWithOffset(1);
1936 buf = " /* @catch begin */ else {\n";
1937 buf += " id _caught = objc_exception_extract(&_stack);\n";
1938 buf += " objc_exception_try_enter (&_stack);\n";
1939 buf += " if (_setjmp(_stack.buf))\n";
1940 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1941 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Benjamin Kramerd999b372010-02-14 14:14:16 +00001943 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001944 } else { /* no catch list */
1945 buf = "}\nelse {\n";
1946 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1947 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001948 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001949 }
Steve Naroff75730982007-11-07 04:08:17 +00001950 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001951 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1952 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001953 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001954
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001955 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001956 buf = "if ("; // we are generating code for the first catch clause
1957 else
1958 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001959 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001960 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Steve Naroff75730982007-11-07 04:08:17 +00001962 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Steve Naroff75730982007-11-07 04:08:17 +00001964 const char *lParenLoc = strchr(startBuf, '(');
1965
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001966 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001967 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001968 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001969 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1970 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001971 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001972 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001973 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Steve Naroffe12e6922008-02-01 20:02:07 +00001975 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001976 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001977 } else if (catchDecl) {
1978 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001979 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001980 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001981 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001982 } else if (const ObjCObjectPointerType *Ptr =
1983 t->getAs<ObjCObjectPointerType>()) {
1984 // Should be a pointer to a class.
1985 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1986 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001987 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001988 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001989 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001990 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001991 }
1992 }
1993 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001994 lastCatchBody = Catch->getCatchBody();
1995 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001996 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1997 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1998 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1999 assert((*rParenBuf == ')') && "bogus @catch paren location");
2000 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Mike Stump1eb44332009-09-09 15:08:12 +00002002 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002003 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002005 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002006 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002007 }
Steve Naroff75730982007-11-07 04:08:17 +00002008 }
2009 // Complete the catch list...
2010 if (lastCatchBody) {
2011 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002012 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2013 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Steve Naroff378f47a2008-09-11 15:29:03 +00002015 // Insert the last (implicit) else clause *before* the right curly brace.
2016 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2017 buf = "} /* last catch end */\n";
2018 buf += "else {\n";
2019 buf += " _rethrow = _caught;\n";
2020 buf += " objc_exception_try_exit(&_stack);\n";
2021 buf += "} } /* @catch end */\n";
2022 if (!S->getFinallyStmt())
2023 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002024 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Steve Naroff75730982007-11-07 04:08:17 +00002026 // Set lastCurlyLoc
2027 lastCurlyLoc = lastCatchBody->getLocEnd();
2028 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002029 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002030 startLoc = finalStmt->getLocStart();
2031 startBuf = SM->getCharacterData(startLoc);
2032 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Benjamin Kramerd999b372010-02-14 14:14:16 +00002034 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroff75730982007-11-07 04:08:17 +00002036 Stmt *body = finalStmt->getFinallyBody();
2037 SourceLocation startLoc = body->getLocStart();
2038 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002039 assert(*SM->getCharacterData(startLoc) == '{' &&
2040 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002041 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002042 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Steve Naroff75730982007-11-07 04:08:17 +00002044 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002045 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002046 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002047 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroff75730982007-11-07 04:08:17 +00002049 // Set lastCurlyLoc
2050 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Steve Naroff8c565152008-12-05 17:03:39 +00002052 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002053 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002054 } else { /* no finally clause - make sure we synthesize an implicit one */
2055 buf = "{ /* implicit finally clause */\n";
2056 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2057 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2058 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002059 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002060
2061 // Now check for any return/continue/go statements within the @try.
2062 // The implicit finally clause won't called if the @try contains any
2063 // jump statements.
2064 bool hasReturns = false;
2065 HasReturnStmts(S->getTryBody(), hasReturns);
2066 if (hasReturns)
2067 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002068 }
2069 // Now emit the final closing curly brace...
2070 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002071 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002072 return 0;
2073}
2074
Mike Stump1eb44332009-09-09 15:08:12 +00002075// This can't be done with ReplaceStmt(S, ThrowExpr), since
2076// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002077// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002078Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002079 // Get the start location and compute the semi location.
2080 SourceLocation startLoc = S->getLocStart();
2081 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Steve Naroff2bd03922007-11-07 15:32:26 +00002083 assert((*startBuf == '@') && "bogus @throw location");
2084
2085 std::string buf;
2086 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002087 if (S->getThrowExpr())
2088 buf = "objc_exception_throw(";
2089 else // add an implicit argument
2090 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002092 // handle "@ throw" correctly.
2093 const char *wBuf = strchr(startBuf, 'w');
2094 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002095 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Steve Naroff2bd03922007-11-07 15:32:26 +00002097 const char *semiBuf = strchr(startBuf, ';');
2098 assert((*semiBuf == ';') && "@throw: can't find ';'");
2099 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002100 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002101 return 0;
2102}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002103
Steve Naroffb29b4272008-04-14 22:03:09 +00002104Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002105 // Create a new string expression.
2106 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002107 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002108 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002109 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2110 StrEncoding.length(), false,StrType,
2111 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002112 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Chris Lattner07506182007-11-30 22:53:43 +00002114 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002115 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002116 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002117}
2118
Steve Naroffb29b4272008-04-14 22:03:09 +00002119Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002120 if (!SelGetUidFunctionDecl)
2121 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002122 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2123 // Create a call to sel_registerName("selName").
2124 llvm::SmallVector<Expr*, 8> SelExprs;
2125 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002126 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002127 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002128 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002129 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002130 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2131 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002132 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002133 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002134 return SelExp;
2135}
2136
Steve Naroffb29b4272008-04-14 22:03:09 +00002137CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002138 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2139 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002140 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002141 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Steve Naroffebf2b562007-10-23 23:50:29 +00002143 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002144 DeclRefExpr *DRE =
2145 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Steve Naroffebf2b562007-10-23 23:50:29 +00002147 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002148 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002149 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002150 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002151 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002152
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002155 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002156 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002157 FT->getCallResultType(*Context),
2158 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002159 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002160}
2161
Steve Naroffd5255f52007-11-01 13:24:47 +00002162static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2163 const char *&startRef, const char *&endRef) {
2164 while (startBuf < endBuf) {
2165 if (*startBuf == '<')
2166 startRef = startBuf; // mark the start.
2167 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002168 if (startRef && *startRef == '<') {
2169 endRef = startBuf; // mark the end.
2170 return true;
2171 }
2172 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 }
2174 startBuf++;
2175 }
2176 return false;
2177}
2178
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002179static void scanToNextArgument(const char *&argRef) {
2180 int angle = 0;
2181 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2182 if (*argRef == '<')
2183 angle++;
2184 else if (*argRef == '>')
2185 angle--;
2186 argRef++;
2187 }
2188 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2189}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002190
Steve Naroffb29b4272008-04-14 22:03:09 +00002191bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002192 if (T->isObjCQualifiedIdType())
2193 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002194 if (const PointerType *PT = T->getAs<PointerType>()) {
2195 if (PT->getPointeeType()->isObjCQualifiedIdType())
2196 return true;
2197 }
2198 if (T->isObjCObjectPointerType()) {
2199 T = T->getPointeeType();
2200 return T->isObjCQualifiedInterfaceType();
2201 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002202 if (T->isArrayType()) {
2203 QualType ElemTy = Context->getBaseElementType(T);
2204 return needToScanForQualifiers(ElemTy);
2205 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002206 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002207}
2208
Steve Naroff4f95b752008-07-29 18:15:38 +00002209void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2210 QualType Type = E->getType();
2211 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002212 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Steve Naroffcda658e2008-11-19 21:15:47 +00002214 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2215 Loc = ECE->getLParenLoc();
2216 EndLoc = ECE->getRParenLoc();
2217 } else {
2218 Loc = E->getLocStart();
2219 EndLoc = E->getLocEnd();
2220 }
2221 // This will defend against trying to rewrite synthesized expressions.
2222 if (Loc.isInvalid() || EndLoc.isInvalid())
2223 return;
2224
Steve Naroff4f95b752008-07-29 18:15:38 +00002225 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002226 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002227 const char *startRef = 0, *endRef = 0;
2228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229 // Get the locations of the startRef, endRef.
2230 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2231 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2232 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002233 InsertText(LessLoc, "/*");
2234 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002235 }
2236 }
2237}
2238
Steve Naroffb29b4272008-04-14 22:03:09 +00002239void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002240 SourceLocation Loc;
2241 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002242 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002243 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2244 Loc = VD->getLocation();
2245 Type = VD->getType();
2246 }
2247 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2248 Loc = FD->getLocation();
2249 // Check for ObjC 'id' and class types that have been adorned with protocol
2250 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002251 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002252 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002253 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002254 if (!proto)
2255 return;
2256 Type = proto->getResultType();
2257 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002258 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2259 Loc = FD->getLocation();
2260 Type = FD->getType();
2261 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002262 else
2263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002265 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002266 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Steve Naroffd5255f52007-11-01 13:24:47 +00002268 const char *endBuf = SM->getCharacterData(Loc);
2269 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002270 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002271 startBuf--; // scan backward (from the decl location) for return type.
2272 const char *startRef = 0, *endRef = 0;
2273 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2274 // Get the locations of the startRef, endRef.
2275 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2276 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2277 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002278 InsertText(LessLoc, "/*");
2279 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002280 }
2281 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002282 if (!proto)
2283 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002284 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002285 const char *startBuf = SM->getCharacterData(Loc);
2286 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002287 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2288 if (needToScanForQualifiers(proto->getArgType(i))) {
2289 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Steve Naroffd5255f52007-11-01 13:24:47 +00002291 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002292 // scan forward (from the decl location) for argument types.
2293 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002294 const char *startRef = 0, *endRef = 0;
2295 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2296 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002297 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002298 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002299 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002300 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002301 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002302 InsertText(LessLoc, "/*");
2303 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002304 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002305 startBuf = ++endBuf;
2306 }
2307 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002308 // If the function name is derived from a macro expansion, then the
2309 // argument buffer will not follow the name. Need to speak with Chris.
2310 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002311 startBuf++; // scan forward (from the decl location) for argument types.
2312 startBuf++;
2313 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002314 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002315}
2316
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002317void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2318 QualType QT = ND->getType();
2319 const Type* TypePtr = QT->getAs<Type>();
2320 if (!isa<TypeOfExprType>(TypePtr))
2321 return;
2322 while (isa<TypeOfExprType>(TypePtr)) {
2323 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2324 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2325 TypePtr = QT->getAs<Type>();
2326 }
2327 // FIXME. This will not work for multiple declarators; as in:
2328 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002329 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002330 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2331 const char *startBuf = SM->getCharacterData(DeclLoc);
2332 if (ND->getInit()) {
2333 std::string Name(ND->getNameAsString());
2334 TypeAsString += " " + Name + " = ";
2335 Expr *E = ND->getInit();
2336 SourceLocation startLoc;
2337 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2338 startLoc = ECE->getLParenLoc();
2339 else
2340 startLoc = E->getLocStart();
2341 startLoc = SM->getInstantiationLoc(startLoc);
2342 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002343 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002344 }
2345 else {
2346 SourceLocation X = ND->getLocEnd();
2347 X = SM->getInstantiationLoc(X);
2348 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002349 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002350 }
2351}
2352
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002353// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002354void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002355 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2356 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002357 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002358 QualType getFuncType =
2359 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002360 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002361 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002362 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002363 SC_Extern,
2364 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002365}
2366
Steve Naroffb29b4272008-04-14 22:03:09 +00002367void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002368 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002369 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002370 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002371 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002372 return;
2373 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002375}
2376
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002377void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2378 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002379 const char *argPtr = TypeString.c_str();
2380 if (!strchr(argPtr, '^')) {
2381 Str += TypeString;
2382 return;
2383 }
2384 while (*argPtr) {
2385 Str += (*argPtr == '^' ? '*' : *argPtr);
2386 argPtr++;
2387 }
2388}
2389
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002390// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002391void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2392 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002393 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002394 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002395 const char *argPtr = TypeString.c_str();
2396 int paren = 0;
2397 while (*argPtr) {
2398 switch (*argPtr) {
2399 case '(':
2400 Str += *argPtr;
2401 paren++;
2402 break;
2403 case ')':
2404 Str += *argPtr;
2405 paren--;
2406 break;
2407 case '^':
2408 Str += '*';
2409 if (paren == 1)
2410 Str += VD->getNameAsString();
2411 break;
2412 default:
2413 Str += *argPtr;
2414 break;
2415 }
2416 argPtr++;
2417 }
2418}
2419
2420
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002421void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2422 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2423 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2424 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2425 if (!proto)
2426 return;
2427 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002428 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002429 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002430 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002431 FdStr += "(";
2432 unsigned numArgs = proto->getNumArgs();
2433 for (unsigned i = 0; i < numArgs; i++) {
2434 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002435 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002436 if (i+1 < numArgs)
2437 FdStr += ", ";
2438 }
2439 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002440 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002441 CurFunctionDeclToDeclareForBlock = 0;
2442}
2443
Steve Naroffc0a123c2008-03-11 17:37:02 +00002444// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002445void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002446 if (SuperContructorFunctionDecl)
2447 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002448 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002449 llvm::SmallVector<QualType, 16> ArgTys;
2450 QualType argT = Context->getObjCIdType();
2451 assert(!argT.isNull() && "Can't find 'id' type");
2452 ArgTys.push_back(argT);
2453 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002454 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2455 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002456 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002457 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002458 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002459 SC_Extern,
2460 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002461}
2462
Steve Naroff09b266e2007-10-30 23:14:51 +00002463// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002464void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002465 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2466 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002467 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002468 assert(!argT.isNull() && "Can't find 'id' type");
2469 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002470 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002471 assert(!argT.isNull() && "Can't find 'SEL' type");
2472 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002473 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2474 &ArgTys[0], ArgTys.size(),
2475 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002476 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002477 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002478 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002479 SC_Extern,
2480 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002481}
2482
Steve Naroff874e2322007-11-15 10:28:18 +00002483// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002484void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002485 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2486 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002487 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002488 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002489 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002490 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2491 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2492 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002493 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002494 assert(!argT.isNull() && "Can't find 'SEL' type");
2495 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002496 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2497 &ArgTys[0], ArgTys.size(),
2498 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002499 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002500 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002501 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002502 SC_Extern,
2503 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002504}
2505
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002506// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002507void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002508 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2509 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002510 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002511 assert(!argT.isNull() && "Can't find 'id' type");
2512 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002513 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002514 assert(!argT.isNull() && "Can't find 'SEL' type");
2515 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002516 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2517 &ArgTys[0], ArgTys.size(),
2518 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002519 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002520 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002521 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002522 SC_Extern,
2523 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002524}
2525
Mike Stump1eb44332009-09-09 15:08:12 +00002526// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002527// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002528void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002529 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002530 &Context->Idents.get("objc_msgSendSuper_stret");
2531 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002532 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002533 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002534 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002535 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2536 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2537 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002538 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 assert(!argT.isNull() && "Can't find 'SEL' type");
2540 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002541 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2542 &ArgTys[0], ArgTys.size(),
2543 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002544 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002545 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002546 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002547 SC_Extern,
2548 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002549}
2550
Steve Naroff1284db82008-05-08 22:02:18 +00002551// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002552void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002553 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2554 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002556 assert(!argT.isNull() && "Can't find 'id' type");
2557 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002558 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002559 assert(!argT.isNull() && "Can't find 'SEL' type");
2560 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002561 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2562 &ArgTys[0], ArgTys.size(),
2563 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002564 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002565 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002566 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002567 SC_Extern,
2568 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002569}
2570
Steve Naroff09b266e2007-10-30 23:14:51 +00002571// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002572void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002573 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2574 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002575 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002576 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2577 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002578 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002579 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002580 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002581 SC_Extern,
2582 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002583}
2584
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002585// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2586void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2587 IdentifierInfo *getSuperClassIdent =
2588 &Context->Idents.get("class_getSuperclass");
2589 llvm::SmallVector<QualType, 16> ArgTys;
2590 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002591 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2592 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002593 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002594 SourceLocation(),
2595 getSuperClassIdent,
2596 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002597 SC_Extern,
2598 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002599 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002600}
2601
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002602// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002603void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002604 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2605 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002606 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002607 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2608 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002609 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002610 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002611 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002614}
2615
Steve Naroffb29b4272008-04-14 22:03:09 +00002616Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002617 QualType strType = getConstantStringStructType();
2618
2619 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002620
2621 std::string tmpName = InFileName;
2622 unsigned i;
2623 for (i=0; i < tmpName.length(); i++) {
2624 char c = tmpName.at(i);
2625 // replace any non alphanumeric characters with '_'.
2626 if (!isalpha(c) && (c < '0' || c > '9'))
2627 tmpName[i] = '_';
2628 }
2629 S += tmpName;
2630 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002631 S += utostr(NumObjCStringLiterals++);
2632
Steve Naroffba92b2e2008-03-27 22:29:16 +00002633 Preamble += "static __NSConstantStringImpl " + S;
2634 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2635 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002636 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002637 std::string prettyBufS;
2638 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002639 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2640 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002641 Preamble += prettyBuf.str();
2642 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002643 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002644
2645 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002646 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002647 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002648 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2649 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002650 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002651 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002652 VK_RValue, OK_Ordinary,
2653 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002654 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002655 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002656 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002657 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002658 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002659 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002660}
2661
Steve Naroff874e2322007-11-15 10:28:18 +00002662// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002663QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002664 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002665 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002666 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002667 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002668 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Steve Naroff874e2322007-11-15 10:28:18 +00002670 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002671 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002672 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002673 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002674
Steve Naroff874e2322007-11-15 10:28:18 +00002675 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002676 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002677 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2678 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002679 FieldTypes[i], 0,
2680 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002681 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002682 }
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor838db382010-02-11 01:19:42 +00002684 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002685 }
2686 return Context->getTagDeclType(SuperStructDecl);
2687}
2688
Steve Naroffb29b4272008-04-14 22:03:09 +00002689QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002690 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002691 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002692 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002693 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002694 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002696 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002697 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002698 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002699 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002701 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002702 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002704
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002705 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002706 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002707 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2708 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002709 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002710 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002711 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002712 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002713 }
2714
Douglas Gregor838db382010-02-11 01:19:42 +00002715 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002716 }
2717 return Context->getTagDeclType(ConstantStringDecl);
2718}
2719
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002720Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2721 SourceLocation StartLoc,
2722 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002723 if (!SelGetUidFunctionDecl)
2724 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002725 if (!MsgSendFunctionDecl)
2726 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002727 if (!MsgSendSuperFunctionDecl)
2728 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002729 if (!MsgSendStretFunctionDecl)
2730 SynthMsgSendStretFunctionDecl();
2731 if (!MsgSendSuperStretFunctionDecl)
2732 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002733 if (!MsgSendFpretFunctionDecl)
2734 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002735 if (!GetClassFunctionDecl)
2736 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002737 if (!GetSuperClassFunctionDecl)
2738 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002739 if (!GetMetaClassFunctionDecl)
2740 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Steve Naroff874e2322007-11-15 10:28:18 +00002742 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002743 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2744 // May need to use objc_msgSend_stret() as well.
2745 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002746 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2747 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002748 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002749 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002750 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002751 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002752 }
Mike Stump1eb44332009-09-09 15:08:12 +00002753
Steve Naroff934f2762007-10-24 22:48:43 +00002754 // Synthesize a call to objc_msgSend().
2755 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002756 switch (Exp->getReceiverKind()) {
2757 case ObjCMessageExpr::SuperClass: {
2758 MsgSendFlavor = MsgSendSuperFunctionDecl;
2759 if (MsgSendStretFlavor)
2760 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2761 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Douglas Gregor04badcf2010-04-21 00:45:42 +00002763 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregor04badcf2010-04-21 00:45:42 +00002765 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002766
Douglas Gregor04badcf2010-04-21 00:45:42 +00002767 // set the receiver to self, the first argument to all methods.
2768 InitExprs.push_back(
2769 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002770 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002772 Context->getObjCIdType(),
2773 VK_RValue,
2774 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2778 llvm::SmallVector<Expr*, 8> ClsExprs;
2779 QualType argType = Context->getPointerType(Context->CharTy);
2780 ClsExprs.push_back(StringLiteral::Create(*Context,
2781 ClassDecl->getIdentifier()->getNameStart(),
2782 ClassDecl->getIdentifier()->getLength(),
2783 false, argType, SourceLocation()));
2784 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2785 &ClsExprs[0],
2786 ClsExprs.size(),
2787 StartLoc,
2788 EndLoc);
2789 // (Class)objc_getClass("CurrentClass")
2790 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2791 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002792 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793 ClsExprs.clear();
2794 ClsExprs.push_back(ArgExpr);
2795 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2796 &ClsExprs[0], ClsExprs.size(),
2797 StartLoc, EndLoc);
2798
2799 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2800 // To turn off a warning, type-cast to 'id'
2801 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2802 NoTypeInfoCStyleCastExpr(Context,
2803 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002804 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 // struct objc_super
2806 QualType superType = getSuperStructType();
2807 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002808
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809 if (LangOpts.Microsoft) {
2810 SynthSuperContructorFunctionDecl();
2811 // Simulate a contructor call...
2812 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002813 superType, VK_LValue,
2814 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002815 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2816 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002817 superType, VK_LValue,
2818 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819 // The code for super is a little tricky to prevent collision with
2820 // the structure definition in the header. The rewriter has it's own
2821 // internal definition (__rw_objc_super) that is uses. This is why
2822 // we need the cast below. For example:
2823 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2824 //
John McCall2de56d12010-08-25 11:45:40 +00002825 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002826 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002827 VK_RValue, OK_Ordinary,
2828 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002829 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2830 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002831 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002832 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 // (struct objc_super) { <exprs from above> }
2834 InitListExpr *ILE =
2835 new (Context) InitListExpr(*Context, SourceLocation(),
2836 &InitExprs[0], InitExprs.size(),
2837 SourceLocation());
2838 TypeSourceInfo *superTInfo
2839 = Context->getTrivialTypeSourceInfo(superType);
2840 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002841 superType, VK_LValue,
2842 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002843 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002844 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002846 VK_RValue, OK_Ordinary,
2847 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002848 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002849 MsgExprs.push_back(SuperRep);
2850 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002851 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852
2853 case ObjCMessageExpr::Class: {
2854 llvm::SmallVector<Expr*, 8> ClsExprs;
2855 QualType argType = Context->getPointerType(Context->CharTy);
2856 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002857 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 IdentifierInfo *clsName = Class->getIdentifier();
2859 ClsExprs.push_back(StringLiteral::Create(*Context,
2860 clsName->getNameStart(),
2861 clsName->getLength(),
2862 false, argType,
2863 SourceLocation()));
2864 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2865 &ClsExprs[0],
2866 ClsExprs.size(),
2867 StartLoc, EndLoc);
2868 MsgExprs.push_back(Cls);
2869 break;
2870 }
2871
2872 case ObjCMessageExpr::SuperInstance:{
2873 MsgSendFlavor = MsgSendSuperFunctionDecl;
2874 if (MsgSendStretFlavor)
2875 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2876 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2877 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2878 llvm::SmallVector<Expr*, 4> InitExprs;
2879
2880 InitExprs.push_back(
2881 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002882 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002883 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002884 Context->getObjCIdType(),
2885 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 ); // set the 'receiver'.
2887
2888 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2889 llvm::SmallVector<Expr*, 8> ClsExprs;
2890 QualType argType = Context->getPointerType(Context->CharTy);
2891 ClsExprs.push_back(StringLiteral::Create(*Context,
2892 ClassDecl->getIdentifier()->getNameStart(),
2893 ClassDecl->getIdentifier()->getLength(),
2894 false, argType, SourceLocation()));
2895 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2896 &ClsExprs[0],
2897 ClsExprs.size(),
2898 StartLoc, EndLoc);
2899 // (Class)objc_getClass("CurrentClass")
2900 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2901 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002902 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 ClsExprs.clear();
2904 ClsExprs.push_back(ArgExpr);
2905 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2906 &ClsExprs[0], ClsExprs.size(),
2907 StartLoc, EndLoc);
2908
2909 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2910 // To turn off a warning, type-cast to 'id'
2911 InitExprs.push_back(
2912 // set 'super class', using class_getSuperclass().
2913 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002914 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002915 // struct objc_super
2916 QualType superType = getSuperStructType();
2917 Expr *SuperRep;
2918
2919 if (LangOpts.Microsoft) {
2920 SynthSuperContructorFunctionDecl();
2921 // Simulate a contructor call...
2922 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002923 superType, VK_LValue,
2924 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002925 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2926 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002927 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002928 // The code for super is a little tricky to prevent collision with
2929 // the structure definition in the header. The rewriter has it's own
2930 // internal definition (__rw_objc_super) that is uses. This is why
2931 // we need the cast below. For example:
2932 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2933 //
John McCall2de56d12010-08-25 11:45:40 +00002934 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002935 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002936 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002937 SourceLocation());
2938 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2939 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002940 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002941 } else {
2942 // (struct objc_super) { <exprs from above> }
2943 InitListExpr *ILE =
2944 new (Context) InitListExpr(*Context, SourceLocation(),
2945 &InitExprs[0], InitExprs.size(),
2946 SourceLocation());
2947 TypeSourceInfo *superTInfo
2948 = Context->getTrivialTypeSourceInfo(superType);
2949 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002950 superType, VK_RValue, ILE,
2951 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002952 }
2953 MsgExprs.push_back(SuperRep);
2954 break;
2955 }
2956
2957 case ObjCMessageExpr::Instance: {
2958 // Remove all type-casts because it may contain objc-style types; e.g.
2959 // Foo<Proto> *.
2960 Expr *recExpr = Exp->getInstanceReceiver();
2961 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2962 recExpr = CE->getSubExpr();
2963 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002964 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002965 MsgExprs.push_back(recExpr);
2966 break;
2967 }
2968 }
2969
Steve Naroffbeaf2992007-11-03 11:27:19 +00002970 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002971 llvm::SmallVector<Expr*, 8> SelExprs;
2972 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002973 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002974 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002975 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002976 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002977 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002978 &SelExprs[0], SelExprs.size(),
2979 StartLoc,
2980 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002981 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002982
Steve Naroff934f2762007-10-24 22:48:43 +00002983 // Now push any user supplied arguments.
2984 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002985 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002986 // Make all implicit casts explicit...ICE comes in handy:-)
2987 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2988 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002989 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002990 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002991 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002992 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002993 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00002994 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002995 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002996 }
2997 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002998 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003000 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003001 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003002 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003003 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003004 }
Mike Stump1eb44332009-09-09 15:08:12 +00003005 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003006 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003007 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3008 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003009 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003010 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003011 }
Steve Naroffab972d32007-11-04 22:37:50 +00003012 // Generate the funky cast.
3013 CastExpr *cast;
3014 llvm::SmallVector<QualType, 8> ArgTypes;
3015 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Steve Naroffab972d32007-11-04 22:37:50 +00003017 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003018 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3019 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3020 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003021 ArgTypes.push_back(Context->getObjCIdType());
3022 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003023 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003024 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003025 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3026 E = OMD->param_end(); PI != E; ++PI) {
3027 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003028 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003029 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003030 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003031 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003032 ArgTypes.push_back(t);
3033 }
Chris Lattner89951a82009-02-20 18:43:26 +00003034 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3035 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003036 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003037 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003038 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003039 }
3040 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003041 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Steve Naroffab972d32007-11-04 22:37:50 +00003043 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003044 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003045 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003046
Mike Stump1eb44332009-09-09 15:08:12 +00003047 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003048 // If we don't do this cast, we get the following bizarre warning/note:
3049 // xx.m:13: warning: function called through a non-compatible type
3050 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003051 cast = NoTypeInfoCStyleCastExpr(Context,
3052 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003053 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Steve Naroffab972d32007-11-04 22:37:50 +00003055 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003056 QualType castType =
3057 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3058 // If we don't have a method decl, force a variadic cast.
3059 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003060 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003061 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003062 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003063
3064 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003065 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003066
John McCall183700f2009-09-21 23:43:11 +00003067 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003068 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003069 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003070 FT->getResultType(), VK_RValue,
3071 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003072 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003073 if (MsgSendStretFlavor) {
3074 // We have the method which returns a struct/union. Must also generate
3075 // call to objc_msgSend_stret and hang both varieties on a conditional
3076 // expression which dictate which one to envoke depending on size of
3077 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003079 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003080 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003081 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003082 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003083 cast = NoTypeInfoCStyleCastExpr(Context,
3084 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003085 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003086 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003087 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3088 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003089 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003090 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003091 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003093 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003094 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003095
John McCall183700f2009-09-21 23:43:11 +00003096 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003097 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003098 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003099 FT->getResultType(), VK_RValue,
3100 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003102 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003103 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003104 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003105 Context->getSizeType(),
3106 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003107 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3108 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3109 // For X86 it is more complicated and some kind of target specific routine
3110 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003111 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003112 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003113 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3114 llvm::APInt(IntSize, 8),
3115 Context->IntTy,
3116 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003117 BinaryOperator *lessThanExpr =
3118 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3119 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003120 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003121 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003122 new (Context) ConditionalOperator(lessThanExpr,
3123 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003124 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003125 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003126 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3127 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003128 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003129 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003130 return ReplacingStmt;
3131}
3132
Steve Naroffb29b4272008-04-14 22:03:09 +00003133Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003134 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3135 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Steve Naroff934f2762007-10-24 22:48:43 +00003137 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003138 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003140 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003141 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003142}
3143
Steve Naroff621edce2009-04-29 16:37:50 +00003144// typedef struct objc_object Protocol;
3145QualType RewriteObjC::getProtocolType() {
3146 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003147 TypeSourceInfo *TInfo
3148 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003149 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003150 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003151 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003152 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003153 }
3154 return Context->getTypeDeclType(ProtocolTypeDecl);
3155}
3156
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003157/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003158/// a synthesized/forward data reference (to the protocol's metadata).
3159/// The forward references (and metadata) are generated in
3160/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003161Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003162 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3163 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003164 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003165 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003166 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003167 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3168 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003169 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003170 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003171 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003172 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003173 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003174 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003175 ReplaceStmt(Exp, castExpr);
3176 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003177 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003178 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003179
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003180}
3181
Mike Stump1eb44332009-09-09 15:08:12 +00003182bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003183 const char *endBuf) {
3184 while (startBuf < endBuf) {
3185 if (*startBuf == '#') {
3186 // Skip whitespace.
3187 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3188 ;
3189 if (!strncmp(startBuf, "if", strlen("if")) ||
3190 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3191 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3192 !strncmp(startBuf, "define", strlen("define")) ||
3193 !strncmp(startBuf, "undef", strlen("undef")) ||
3194 !strncmp(startBuf, "else", strlen("else")) ||
3195 !strncmp(startBuf, "elif", strlen("elif")) ||
3196 !strncmp(startBuf, "endif", strlen("endif")) ||
3197 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3198 !strncmp(startBuf, "include", strlen("include")) ||
3199 !strncmp(startBuf, "import", strlen("import")) ||
3200 !strncmp(startBuf, "include_next", strlen("include_next")))
3201 return true;
3202 }
3203 startBuf++;
3204 }
3205 return false;
3206}
3207
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003208/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003209/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003210void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003211 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003212 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003213 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003214 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003215 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003216 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003217 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003218 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003219 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003220 SourceLocation LocStart = CDecl->getLocStart();
3221 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Steve Narofffea763e82007-11-14 19:25:57 +00003223 const char *startBuf = SM->getCharacterData(LocStart);
3224 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003225
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003226 // If no ivars and no root or if its root, directly or indirectly,
3227 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003228 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3229 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003231 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003232 return;
3233 }
Mike Stump1eb44332009-09-09 15:08:12 +00003234
3235 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003236 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003237 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003239 if (LangOpts.Microsoft)
3240 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003241
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003242 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003243 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003244 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003245 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003246 // If the buffer contains preprocessor directives, we do more fine-grained
3247 // rewrites. This is intended to fix code that looks like (which occurs in
3248 // NSURL.h, for example):
3249 //
3250 // #ifdef XYZ
3251 // @interface Foo : NSObject
3252 // #else
3253 // @interface FooBar : NSObject
3254 // #endif
3255 // {
3256 // int i;
3257 // }
3258 // @end
3259 //
3260 // This clause is segregated to avoid breaking the common case.
3261 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003262 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003263 CDecl->getClassLoc();
3264 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003265 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003266
Chris Lattnercafeb352009-02-20 18:18:36 +00003267 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003268 // advance to the end of the referenced protocols.
3269 while (endHeader < cursor && *endHeader != '>') endHeader++;
3270 endHeader++;
3271 }
3272 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003273 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003274 } else {
3275 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003276 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003277 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003278 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003279 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003280 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003281 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003283 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003284
Steve Narofffea763e82007-11-14 19:25:57 +00003285 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003286 SourceLocation OnePastCurly =
3287 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003288 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003289 }
3290 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003291
Steve Narofffea763e82007-11-14 19:25:57 +00003292 // Now comment out any visibility specifiers.
3293 while (cursor < endBuf) {
3294 if (*cursor == '@') {
3295 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003296 // Skip whitespace.
3297 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3298 /*scan*/;
3299
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003300 // FIXME: presence of @public, etc. inside comment results in
3301 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003302 if (!strncmp(cursor, "public", strlen("public")) ||
3303 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003304 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003305 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003306 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003307 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003308 // FIXME: If there are cases where '<' is used in ivar declaration part
3309 // of user code, then scan the ivar list and use needToScanForQualifiers
3310 // for type checking.
3311 else if (*cursor == '<') {
3312 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003313 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003314 cursor = strchr(cursor, '>');
3315 cursor++;
3316 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003317 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003318 } else if (*cursor == '^') { // rewrite block specifier.
3319 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003320 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003321 }
Steve Narofffea763e82007-11-14 19:25:57 +00003322 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003323 }
Steve Narofffea763e82007-11-14 19:25:57 +00003324 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003325 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003326 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003327 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003328 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003330 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003332 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003333 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003334 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003335 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003336 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003337 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003338}
3339
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003340// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003341/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003342template<typename MethodIterator>
3343void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3344 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003345 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003346 llvm::StringRef prefix,
3347 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003348 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003349 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003350
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003351 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003352 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003353 SEL _cmd;
3354 char *method_types;
3355 void *_imp;
3356 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003357 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003358 Result += "\nstruct _objc_method {\n";
3359 Result += "\tSEL _cmd;\n";
3360 Result += "\tchar *method_types;\n";
3361 Result += "\tvoid *_imp;\n";
3362 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003364 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003365 }
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003367 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Steve Naroff946a6932008-03-11 00:12:29 +00003369 /* struct {
3370 struct _objc_method_list *next_method;
3371 int method_count;
3372 struct _objc_method method_list[];
3373 }
3374 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003375 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003376 Result += "\nstatic struct {\n";
3377 Result += "\tstruct _objc_method_list *next_method;\n";
3378 Result += "\tint method_count;\n";
3379 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003380 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003381 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003382 Result += prefix;
3383 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3384 Result += "_METHODS_";
3385 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003386 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003387 Result += IsInstanceMethod ? "inst" : "cls";
3388 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003389 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003390
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003391 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003392 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003393 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003394 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003395 Result += "\", \"";
3396 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003397 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003398 Result += MethodInternalNames[*MethodBegin];
3399 Result += "}\n";
3400 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3401 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003402 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003403 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003404 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003405 Result += "\", \"";
3406 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003407 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003408 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003409 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003410 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003411 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003412}
3413
Steve Naroff621edce2009-04-29 16:37:50 +00003414/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003415void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003416RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3417 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003418 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003419
3420 // Output struct protocol_methods holder of method selector and type.
3421 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3422 /* struct protocol_methods {
3423 SEL _cmd;
3424 char *method_types;
3425 }
3426 */
3427 Result += "\nstruct _protocol_methods {\n";
3428 Result += "\tstruct objc_selector *_cmd;\n";
3429 Result += "\tchar *method_types;\n";
3430 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Steve Naroff621edce2009-04-29 16:37:50 +00003432 objc_protocol_methods = true;
3433 }
3434 // Do not synthesize the protocol more than once.
3435 if (ObjCSynthesizedProtocols.count(PDecl))
3436 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003437
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003438 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3439 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3440 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003441 /* struct _objc_protocol_method_list {
3442 int protocol_method_count;
3443 struct protocol_methods protocols[];
3444 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003445 */
Steve Naroff621edce2009-04-29 16:37:50 +00003446 Result += "\nstatic struct {\n";
3447 Result += "\tint protocol_method_count;\n";
3448 Result += "\tstruct _protocol_methods protocol_methods[";
3449 Result += utostr(NumMethods);
3450 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3451 Result += PDecl->getNameAsString();
3452 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3453 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Steve Naroff621edce2009-04-29 16:37:50 +00003455 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003456 for (ObjCProtocolDecl::instmeth_iterator
3457 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003458 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003459 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003460 Result += "\t ,{{(struct objc_selector *)\"";
3461 else
3462 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003463 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003464 std::string MethodTypeString;
3465 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3466 Result += "\", \"";
3467 Result += MethodTypeString;
3468 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003469 }
Steve Naroff621edce2009-04-29 16:37:50 +00003470 Result += "\t }\n};\n";
3471 }
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Steve Naroff621edce2009-04-29 16:37:50 +00003473 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003474 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3475 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003476 if (NumMethods > 0) {
3477 /* struct _objc_protocol_method_list {
3478 int protocol_method_count;
3479 struct protocol_methods protocols[];
3480 }
3481 */
3482 Result += "\nstatic struct {\n";
3483 Result += "\tint protocol_method_count;\n";
3484 Result += "\tstruct _protocol_methods protocol_methods[";
3485 Result += utostr(NumMethods);
3486 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3487 Result += PDecl->getNameAsString();
3488 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3489 "{\n\t";
3490 Result += utostr(NumMethods);
3491 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003492
Steve Naroff621edce2009-04-29 16:37:50 +00003493 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003494 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003495 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003496 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003497 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003498 Result += "\t ,{{(struct objc_selector *)\"";
3499 else
3500 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003501 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003502 std::string MethodTypeString;
3503 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3504 Result += "\", \"";
3505 Result += MethodTypeString;
3506 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003507 }
Steve Naroff621edce2009-04-29 16:37:50 +00003508 Result += "\t }\n};\n";
3509 }
3510
3511 // Output:
3512 /* struct _objc_protocol {
3513 // Objective-C 1.0 extensions
3514 struct _objc_protocol_extension *isa;
3515 char *protocol_name;
3516 struct _objc_protocol **protocol_list;
3517 struct _objc_protocol_method_list *instance_methods;
3518 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003519 };
Steve Naroff621edce2009-04-29 16:37:50 +00003520 */
3521 static bool objc_protocol = false;
3522 if (!objc_protocol) {
3523 Result += "\nstruct _objc_protocol {\n";
3524 Result += "\tstruct _objc_protocol_extension *isa;\n";
3525 Result += "\tchar *protocol_name;\n";
3526 Result += "\tstruct _objc_protocol **protocol_list;\n";
3527 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3528 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003529 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Steve Naroff621edce2009-04-29 16:37:50 +00003531 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003532 }
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Steve Naroff621edce2009-04-29 16:37:50 +00003534 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3535 Result += PDecl->getNameAsString();
3536 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3537 "{\n\t0, \"";
3538 Result += PDecl->getNameAsString();
3539 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003540 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003541 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3542 Result += PDecl->getNameAsString();
3543 Result += ", ";
3544 }
3545 else
3546 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003547 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003548 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3549 Result += PDecl->getNameAsString();
3550 Result += "\n";
3551 }
3552 else
3553 Result += "0\n";
3554 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Steve Naroff621edce2009-04-29 16:37:50 +00003556 // Mark this protocol as having been generated.
3557 if (!ObjCSynthesizedProtocols.insert(PDecl))
3558 assert(false && "protocol already synthesized");
3559
3560}
3561
3562void RewriteObjC::
3563RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003564 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003565 std::string &Result) {
3566 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Steve Naroff621edce2009-04-29 16:37:50 +00003568 for (unsigned i = 0; i != Protocols.size(); i++)
3569 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3570
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003571 // Output the top lovel protocol meta-data for the class.
3572 /* struct _objc_protocol_list {
3573 struct _objc_protocol_list *next;
3574 int protocol_count;
3575 struct _objc_protocol *class_protocols[];
3576 }
3577 */
3578 Result += "\nstatic struct {\n";
3579 Result += "\tstruct _objc_protocol_list *next;\n";
3580 Result += "\tint protocol_count;\n";
3581 Result += "\tstruct _objc_protocol *class_protocols[";
3582 Result += utostr(Protocols.size());
3583 Result += "];\n} _OBJC_";
3584 Result += prefix;
3585 Result += "_PROTOCOLS_";
3586 Result += ClassName;
3587 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3588 "{\n\t0, ";
3589 Result += utostr(Protocols.size());
3590 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003592 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003593 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003594 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003596 for (unsigned i = 1; i != Protocols.size(); i++) {
3597 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003598 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003599 Result += "\n";
3600 }
3601 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003602}
3603
Steve Naroff621edce2009-04-29 16:37:50 +00003604
Mike Stump1eb44332009-09-09 15:08:12 +00003605/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003606/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003607void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003608 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003609 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003610 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003611 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003612 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003613 CDecl = CDecl->getNextClassCategory())
3614 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3615 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003617 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003618 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003619 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003621 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003622 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003623 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003624
3625 // If any of our property implementations have associated getters or
3626 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003627 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3628 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003629 Prop != PropEnd; ++Prop) {
3630 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3631 continue;
3632 if (!(*Prop)->getPropertyIvarDecl())
3633 continue;
3634 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3635 if (!PD)
3636 continue;
3637 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3638 InstanceMethods.push_back(Getter);
3639 if (PD->isReadOnly())
3640 continue;
3641 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3642 InstanceMethods.push_back(Setter);
3643 }
3644 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003645 true, "CATEGORY_", FullCategoryName.c_str(),
3646 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003648 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003649 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003650 false, "CATEGORY_", FullCategoryName.c_str(),
3651 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003653 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003654 // Null CDecl is case of a category implementation with no category interface
3655 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003656 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003657 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003658 /* struct _objc_category {
3659 char *category_name;
3660 char *class_name;
3661 struct _objc_method_list *instance_methods;
3662 struct _objc_method_list *class_methods;
3663 struct _objc_protocol_list *protocols;
3664 // Objective-C 1.0 extensions
3665 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003666 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003667 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003668 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003669 */
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003671 static bool objc_category = false;
3672 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003673 Result += "\nstruct _objc_category {\n";
3674 Result += "\tchar *category_name;\n";
3675 Result += "\tchar *class_name;\n";
3676 Result += "\tstruct _objc_method_list *instance_methods;\n";
3677 Result += "\tstruct _objc_method_list *class_methods;\n";
3678 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003679 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003680 Result += "\tstruct _objc_property_list *instance_properties;\n";
3681 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003682 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003683 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003684 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3685 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003686 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003687 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003688 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003689 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003692 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003693 Result += "\t, (struct _objc_method_list *)"
3694 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3695 Result += FullCategoryName;
3696 Result += "\n";
3697 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003698 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003699 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003700 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003701 Result += "\t, (struct _objc_method_list *)"
3702 "&_OBJC_CATEGORY_CLASS_METHODS_";
3703 Result += FullCategoryName;
3704 Result += "\n";
3705 }
3706 else
3707 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Chris Lattnercafeb352009-02-20 18:18:36 +00003709 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003710 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003711 Result += FullCategoryName;
3712 Result += "\n";
3713 }
3714 else
3715 Result += "\t, 0\n";
3716 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003717}
3718
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003719/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3720/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003721void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003722 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003723 if (ivar->isBitField()) {
3724 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3725 // place all bitfields at offset 0.
3726 Result += "0";
3727 } else {
3728 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003729 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003730 if (LangOpts.Microsoft)
3731 Result += "_IMPL";
3732 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003733 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003734 Result += ")";
3735 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003736}
3737
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003738//===----------------------------------------------------------------------===//
3739// Meta Data Emission
3740//===----------------------------------------------------------------------===//
3741
Steve Naroffb29b4272008-04-14 22:03:09 +00003742void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003743 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003744 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003745
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003746 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003747 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003748 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003749 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003750 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003751 }
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Chris Lattnerbe6df082007-12-12 07:56:42 +00003753 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003754 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003755 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003756 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003757 if (NumIvars > 0) {
3758 static bool objc_ivar = false;
3759 if (!objc_ivar) {
3760 /* struct _objc_ivar {
3761 char *ivar_name;
3762 char *ivar_type;
3763 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003764 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003765 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003766 Result += "\nstruct _objc_ivar {\n";
3767 Result += "\tchar *ivar_name;\n";
3768 Result += "\tchar *ivar_type;\n";
3769 Result += "\tint ivar_offset;\n";
3770 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003771
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003772 objc_ivar = true;
3773 }
3774
Steve Naroff946a6932008-03-11 00:12:29 +00003775 /* struct {
3776 int ivar_count;
3777 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003778 };
Steve Naroff946a6932008-03-11 00:12:29 +00003779 */
Mike Stump1eb44332009-09-09 15:08:12 +00003780 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003781 Result += "\tint ivar_count;\n";
3782 Result += "\tstruct _objc_ivar ivar_list[";
3783 Result += utostr(NumIvars);
3784 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003785 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003786 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003787 "{\n\t";
3788 Result += utostr(NumIvars);
3789 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003791 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003792 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003793 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003794 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003795 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003796 IV != IVEnd; ++IV)
3797 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003798 IVI = IDecl->ivar_begin();
3799 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003800 } else {
3801 IVI = CDecl->ivar_begin();
3802 IVE = CDecl->ivar_end();
3803 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003804 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003805 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003806 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003807 std::string TmpString, StrEncoding;
3808 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3809 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003810 Result += StrEncoding;
3811 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003812 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003813 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003814 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003815 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003816 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003817 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003818 std::string TmpString, StrEncoding;
3819 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3820 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003821 Result += StrEncoding;
3822 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003823 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003824 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003825 }
Mike Stump1eb44332009-09-09 15:08:12 +00003826
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003827 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003828 }
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003830 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003831 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003832 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003833
3834 // If any of our property implementations have associated getters or
3835 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003836 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3837 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003838 Prop != PropEnd; ++Prop) {
3839 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3840 continue;
3841 if (!(*Prop)->getPropertyIvarDecl())
3842 continue;
3843 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3844 if (!PD)
3845 continue;
3846 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003847 if (!Getter->isDefined())
3848 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003849 if (PD->isReadOnly())
3850 continue;
3851 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003852 if (!Setter->isDefined())
3853 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003854 }
3855 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003856 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003858 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003859 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003860 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003861
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003862 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003863 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003864 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003866 // Declaration of class/meta-class metadata
3867 /* struct _objc_class {
3868 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003869 const char *super_class_name;
3870 char *name;
3871 long version;
3872 long info;
3873 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003874 struct _objc_ivar_list *ivars;
3875 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003876 struct objc_cache *cache;
3877 struct objc_protocol_list *protocols;
3878 const char *ivar_layout;
3879 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003880 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003881 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003882 static bool objc_class = false;
3883 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003884 Result += "\nstruct _objc_class {\n";
3885 Result += "\tstruct _objc_class *isa;\n";
3886 Result += "\tconst char *super_class_name;\n";
3887 Result += "\tchar *name;\n";
3888 Result += "\tlong version;\n";
3889 Result += "\tlong info;\n";
3890 Result += "\tlong instance_size;\n";
3891 Result += "\tstruct _objc_ivar_list *ivars;\n";
3892 Result += "\tstruct _objc_method_list *methods;\n";
3893 Result += "\tstruct objc_cache *cache;\n";
3894 Result += "\tstruct _objc_protocol_list *protocols;\n";
3895 Result += "\tconst char *ivar_layout;\n";
3896 Result += "\tstruct _objc_class_ext *ext;\n";
3897 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003898 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003899 }
Mike Stump1eb44332009-09-09 15:08:12 +00003900
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003901 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003902 ObjCInterfaceDecl *RootClass = 0;
3903 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003904 while (SuperClass) {
3905 RootClass = SuperClass;
3906 SuperClass = SuperClass->getSuperClass();
3907 }
3908 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003910 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003911 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003912 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003913 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003914 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 Result += "\"";
3916
3917 if (SuperClass) {
3918 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003919 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003920 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003921 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003922 Result += "\"";
3923 }
3924 else {
3925 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003926 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003927 Result += "\"";
3928 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003929 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003930 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003932 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003933 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003934 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003935 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003936 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003937 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003939 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003940 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003941 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003942 Result += ",0,0\n";
3943 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003944 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 Result += "\t,0,0,0,0\n";
3946 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003947
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003948 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003949 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003950 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003951 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003953 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 if (SuperClass) {
3955 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003956 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003958 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003959 Result += "\"";
3960 }
3961 else {
3962 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003963 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003964 Result += "\"";
3965 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003966 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003967 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003968 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003969 Result += ",0";
3970 else {
3971 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003972 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003973 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003974 if (LangOpts.Microsoft)
3975 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003976 Result += ")";
3977 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003978 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003979 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003980 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003981 Result += "\n\t";
3982 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003983 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003985 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003986 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003987 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003988 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003990 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003991 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003992 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003993 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003994 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 Result += ", 0,0\n";
3996 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003997 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003998 Result += ",0,0,0\n";
3999 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004000}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004001
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004002/// RewriteImplementations - This routine rewrites all method implementations
4003/// and emits meta-data.
4004
Steve Narofface66252008-11-13 20:07:04 +00004005void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004006 int ClsDefCount = ClassImplementation.size();
4007 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004009 // Rewrite implemented methods
4010 for (int i = 0; i < ClsDefCount; i++)
4011 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004013 for (int i = 0; i < CatDefCount; i++)
4014 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004015}
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Steve Narofface66252008-11-13 20:07:04 +00004017void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4018 int ClsDefCount = ClassImplementation.size();
4019 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004020
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004021 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004022 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004023 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004025 // For each implemented category, write out all its meta data.
4026 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004027 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004028
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004029 // Write objc_symtab metadata
4030 /*
4031 struct _objc_symtab
4032 {
4033 long sel_ref_cnt;
4034 SEL *refs;
4035 short cls_def_cnt;
4036 short cat_def_cnt;
4037 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004038 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004039 */
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004041 Result += "\nstruct _objc_symtab {\n";
4042 Result += "\tlong sel_ref_cnt;\n";
4043 Result += "\tSEL *refs;\n";
4044 Result += "\tshort cls_def_cnt;\n";
4045 Result += "\tshort cat_def_cnt;\n";
4046 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4047 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004050 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004051 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004052 + ", " + utostr(CatDefCount) + "\n";
4053 for (int i = 0; i < ClsDefCount; i++) {
4054 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004055 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004056 Result += "\n";
4057 }
Mike Stump1eb44332009-09-09 15:08:12 +00004058
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004059 for (int i = 0; i < CatDefCount; i++) {
4060 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004061 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004062 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004063 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += "\n";
4065 }
Mike Stump1eb44332009-09-09 15:08:12 +00004066
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004067 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004069 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004070
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004071 /*
4072 struct _objc_module {
4073 long version;
4074 long size;
4075 const char *name;
4076 struct _objc_symtab *symtab;
4077 }
4078 */
Mike Stump1eb44332009-09-09 15:08:12 +00004079
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004080 Result += "\nstruct _objc_module {\n";
4081 Result += "\tlong version;\n";
4082 Result += "\tlong size;\n";
4083 Result += "\tconst char *name;\n";
4084 Result += "\tstruct _objc_symtab *symtab;\n";
4085 Result += "};\n\n";
4086 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004087 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004088 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004089 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004090 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004091
4092 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004093 if (ProtocolExprDecls.size()) {
4094 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4095 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004096 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004097 E = ProtocolExprDecls.end(); I != E; ++I) {
4098 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4099 Result += (*I)->getNameAsString();
4100 Result += " = &_OBJC_PROTOCOL_";
4101 Result += (*I)->getNameAsString();
4102 Result += ";\n";
4103 }
4104 Result += "#pragma data_seg(pop)\n\n";
4105 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004106 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004107 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004108 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4109 Result += "&_OBJC_MODULES;\n";
4110 Result += "#pragma data_seg(pop)\n\n";
4111 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004112}
Chris Lattner311ff022007-10-16 22:36:42 +00004113
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004114void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4115 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004116 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004117 assert(BlockByRefDeclNo.count(VD) &&
4118 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004119 if (def)
4120 ResultStr += "struct ";
4121 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004122 "_" + utostr(BlockByRefDeclNo[VD]) ;
4123}
4124
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004125static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4126 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4127 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4128 return false;
4129}
4130
Steve Naroff54055232008-10-27 17:20:55 +00004131std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004132 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004133 std::string Tag) {
4134 const FunctionType *AFT = CE->getFunctionType();
4135 QualType RT = AFT->getResultType();
4136 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004137 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004138 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004139
Steve Naroff54055232008-10-27 17:20:55 +00004140 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Douglas Gregor72564e72009-02-26 23:50:07 +00004142 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004143 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004144 // block (to reference imported block decl refs).
4145 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004146 } else if (BD->param_empty()) {
4147 S += "(" + StructRef + " *__cself)";
4148 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004149 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004150 assert(FT && "SynthesizeBlockFunc: No function proto");
4151 S += '(';
4152 // first add the implicit argument.
4153 S += StructRef + " *__cself, ";
4154 std::string ParamStr;
4155 for (BlockDecl::param_iterator AI = BD->param_begin(),
4156 E = BD->param_end(); AI != E; ++AI) {
4157 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004158 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004159 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004160 if (convertBlockPointerToFunctionPointer(QT))
4161 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004162 else
4163 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004164 S += ParamStr;
4165 }
4166 if (FT->isVariadic()) {
4167 if (!BD->param_empty()) S += ", ";
4168 S += "...";
4169 }
4170 S += ')';
4171 }
4172 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004173
Steve Naroff54055232008-10-27 17:20:55 +00004174 // Create local declarations to avoid rewriting all closure decl ref exprs.
4175 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004176 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004177 E = BlockByRefDecls.end(); I != E; ++I) {
4178 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004179 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004180 std::string TypeString;
4181 RewriteByRefString(TypeString, Name, (*I));
4182 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004183 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004184 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004185 }
Steve Naroff54055232008-10-27 17:20:55 +00004186 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004187 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004188 E = BlockByCopyDecls.end(); I != E; ++I) {
4189 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004190 // Handle nested closure invocation. For example:
4191 //
4192 // void (^myImportedClosure)(void);
4193 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004194 //
Steve Naroff54055232008-10-27 17:20:55 +00004195 // void (^anotherClosure)(void);
4196 // anotherClosure = ^(void) {
4197 // myImportedClosure(); // import and invoke the closure
4198 // };
4199 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004200 if (isTopLevelBlockPointerType((*I)->getType())) {
4201 RewriteBlockPointerTypeVariable(S, (*I));
4202 S += " = (";
4203 RewriteBlockPointerType(S, (*I)->getType());
4204 S += ")";
4205 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4206 }
4207 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004208 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004209 QualType QT = (*I)->getType();
4210 if (HasLocalVariableExternalStorage(*I))
4211 QT = Context->getPointerType(QT);
4212 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004213 S += Name + " = __cself->" +
4214 (*I)->getNameAsString() + "; // bound by copy\n";
4215 }
Steve Naroff54055232008-10-27 17:20:55 +00004216 }
4217 std::string RewrittenStr = RewrittenBlockExprs[CE];
4218 const char *cstr = RewrittenStr.c_str();
4219 while (*cstr++ != '{') ;
4220 S += cstr;
4221 S += "\n";
4222 return S;
4223}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004224
Steve Naroff54055232008-10-27 17:20:55 +00004225std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004226 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004227 std::string Tag) {
4228 std::string StructRef = "struct " + Tag;
4229 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Steve Naroff54055232008-10-27 17:20:55 +00004231 S += funcName;
4232 S += "_block_copy_" + utostr(i);
4233 S += "(" + StructRef;
4234 S += "*dst, " + StructRef;
4235 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004236 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004237 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004238 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004239 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004240 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004241 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004242 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004243 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004244 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004245 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004246 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004247 S += "}\n";
4248
Steve Naroff54055232008-10-27 17:20:55 +00004249 S += "\nstatic void __";
4250 S += funcName;
4251 S += "_block_dispose_" + utostr(i);
4252 S += "(" + StructRef;
4253 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004254 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004255 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004256 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004257 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004258 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004259 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004260 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004261 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004262 }
Mike Stump1eb44332009-09-09 15:08:12 +00004263 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004264 return S;
4265}
4266
Steve Naroff01aec112009-12-06 21:14:13 +00004267std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4268 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004269 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004270 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004271
Steve Naroff54055232008-10-27 17:20:55 +00004272 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004273 S += " struct " + Desc;
4274 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004275
Steve Naroff01aec112009-12-06 21:14:13 +00004276 Constructor += "(void *fp, "; // Invoke function pointer.
4277 Constructor += "struct " + Desc; // Descriptor pointer.
4278 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Steve Naroff54055232008-10-27 17:20:55 +00004280 if (BlockDeclRefs.size()) {
4281 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004282 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004283 E = BlockByCopyDecls.end(); I != E; ++I) {
4284 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004285 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004286 std::string ArgName = "_" + FieldName;
4287 // Handle nested closure invocation. For example:
4288 //
4289 // void (^myImportedBlock)(void);
4290 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004291 //
Steve Naroff54055232008-10-27 17:20:55 +00004292 // void (^anotherBlock)(void);
4293 // anotherBlock = ^(void) {
4294 // myImportedBlock(); // import and invoke the closure
4295 // };
4296 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004297 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004298 S += "struct __block_impl *";
4299 Constructor += ", void *" + ArgName;
4300 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004301 QualType QT = (*I)->getType();
4302 if (HasLocalVariableExternalStorage(*I))
4303 QT = Context->getPointerType(QT);
4304 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4305 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004306 Constructor += ", " + ArgName;
4307 }
4308 S += FieldName + ";\n";
4309 }
4310 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004311 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004312 E = BlockByRefDecls.end(); I != E; ++I) {
4313 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004314 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004315 std::string ArgName = "_" + FieldName;
4316 // Handle nested closure invocation. For example:
4317 //
4318 // void (^myImportedBlock)(void);
4319 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004320 //
Steve Naroff54055232008-10-27 17:20:55 +00004321 // void (^anotherBlock)(void);
4322 // anotherBlock = ^(void) {
4323 // myImportedBlock(); // import and invoke the closure
4324 // };
4325 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004326 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004327 S += "struct __block_impl *";
4328 Constructor += ", void *" + ArgName;
4329 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004330 std::string TypeString;
4331 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004332 TypeString += " *";
4333 FieldName = TypeString + FieldName;
4334 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004335 Constructor += ", " + ArgName;
4336 }
4337 S += FieldName + "; // by ref\n";
4338 }
4339 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004340 Constructor += ", int flags=0)";
4341 // Initialize all "by copy" arguments.
4342 bool firsTime = true;
4343 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4344 E = BlockByCopyDecls.end(); I != E; ++I) {
4345 std::string Name = (*I)->getNameAsString();
4346 if (firsTime) {
4347 Constructor += " : ";
4348 firsTime = false;
4349 }
4350 else
4351 Constructor += ", ";
4352 if (isTopLevelBlockPointerType((*I)->getType()))
4353 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4354 else
4355 Constructor += Name + "(_" + Name + ")";
4356 }
4357 // Initialize all "by ref" arguments.
4358 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4359 E = BlockByRefDecls.end(); I != E; ++I) {
4360 std::string Name = (*I)->getNameAsString();
4361 if (firsTime) {
4362 Constructor += " : ";
4363 firsTime = false;
4364 }
4365 else
4366 Constructor += ", ";
4367 if (isTopLevelBlockPointerType((*I)->getType()))
4368 Constructor += Name + "((struct __block_impl *)_"
4369 + Name + "->__forwarding)";
4370 else
4371 Constructor += Name + "(_" + Name + "->__forwarding)";
4372 }
4373
4374 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004375 if (GlobalVarDecl)
4376 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4377 else
4378 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004379 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004380
Steve Naroff01aec112009-12-06 21:14:13 +00004381 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004382 } else {
4383 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004384 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004385 if (GlobalVarDecl)
4386 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4387 else
4388 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004389 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4390 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004391 }
4392 Constructor += " ";
4393 Constructor += "}\n";
4394 S += Constructor;
4395 S += "};\n";
4396 return S;
4397}
4398
Steve Naroff01aec112009-12-06 21:14:13 +00004399std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4400 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004401 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004402 unsigned hasCopy) {
4403 std::string S = "\nstatic struct " + DescTag;
4404
4405 S += " {\n unsigned long reserved;\n";
4406 S += " unsigned long Block_size;\n";
4407 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004408 S += " void (*copy)(struct ";
4409 S += ImplTag; S += "*, struct ";
4410 S += ImplTag; S += "*);\n";
4411
4412 S += " void (*dispose)(struct ";
4413 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004414 }
4415 S += "} ";
4416
4417 S += DescTag + "_DATA = { 0, sizeof(struct ";
4418 S += ImplTag + ")";
4419 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004420 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4421 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004422 }
4423 S += "};\n";
4424 return S;
4425}
4426
Steve Naroff54055232008-10-27 17:20:55 +00004427void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004428 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004429 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004430 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004431 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004432 bool RewriteSC = (GlobalVarDecl &&
4433 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004434 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004435 GlobalVarDecl->getType().getCVRQualifiers());
4436 if (RewriteSC) {
4437 std::string SC(" void __");
4438 SC += GlobalVarDecl->getNameAsString();
4439 SC += "() {}";
4440 InsertText(FunLocStart, SC);
4441 }
4442
Steve Naroff54055232008-10-27 17:20:55 +00004443 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004444 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4445 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004446 // Need to copy-in the inner copied-in variables not actually used in this
4447 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004448 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4449 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4450 ValueDecl *VD = Exp->getDecl();
4451 BlockDeclRefs.push_back(Exp);
4452 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4453 BlockByCopyDeclsPtrSet.insert(VD);
4454 BlockByCopyDecls.push_back(VD);
4455 }
4456 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4457 BlockByRefDeclsPtrSet.insert(VD);
4458 BlockByRefDecls.push_back(VD);
4459 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004460 // imported objects in the inner blocks not used in the outer
4461 // blocks must be copied/disposed in the outer block as well.
4462 if (Exp->isByRef() ||
4463 VD->getType()->isObjCObjectPointerType() ||
4464 VD->getType()->isBlockPointerType())
4465 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004466 }
Steve Naroff54055232008-10-27 17:20:55 +00004467
Daniel Dunbar4087f272010-08-17 22:39:59 +00004468 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4469 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Steve Naroff01aec112009-12-06 21:14:13 +00004471 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004472
Benjamin Kramerd999b372010-02-14 14:14:16 +00004473 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004474
Steve Naroff01aec112009-12-06 21:14:13 +00004475 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004476
Benjamin Kramerd999b372010-02-14 14:14:16 +00004477 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004478
4479 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004480 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004481 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004482 }
Steve Naroff01aec112009-12-06 21:14:13 +00004483 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4484 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004485 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Steve Naroff54055232008-10-27 17:20:55 +00004487 BlockDeclRefs.clear();
4488 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004489 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004490 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004491 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004492 ImportedBlockDecls.clear();
4493 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004494 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004495 // Must insert any 'const/volatile/static here. Since it has been
4496 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004497 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004498 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004499 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004500 if (GlobalVarDecl->getType().isConstQualified())
4501 SC += "const ";
4502 if (GlobalVarDecl->getType().isVolatileQualified())
4503 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004504 if (GlobalVarDecl->getType().isRestrictQualified())
4505 SC += "restrict ";
4506 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004507 }
4508
Steve Naroff54055232008-10-27 17:20:55 +00004509 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004510 InnerDeclRefsCount.clear();
4511 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004512 RewrittenBlockExprs.clear();
4513}
4514
4515void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4516 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004517 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Steve Naroff54055232008-10-27 17:20:55 +00004519 SynthesizeBlockLiterals(FunLocStart, FuncName);
4520}
4521
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004522static void BuildUniqueMethodName(std::string &Name,
4523 ObjCMethodDecl *MD) {
4524 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004525 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004526 Name += "__" + MD->getSelector().getAsString();
4527 // Convert colons to underscores.
4528 std::string::size_type loc = 0;
4529 while ((loc = Name.find(":", loc)) != std::string::npos)
4530 Name.replace(loc, 1, "_");
4531}
4532
Steve Naroff54055232008-10-27 17:20:55 +00004533void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004534 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4535 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004536 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004537 std::string FuncName;
4538 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004539 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004540}
4541
4542void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004543 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004544 if (*CI) {
4545 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4546 GetBlockDeclRefExprs(CBE->getBody());
4547 else
4548 GetBlockDeclRefExprs(*CI);
4549 }
4550 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004551 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004552 // FIXME: Handle enums.
4553 if (!isa<FunctionDecl>(CDRE->getDecl()))
4554 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004555 }
4556 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4557 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4558 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004559 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4560 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004561 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004562 BlockDeclRefs.push_back(BDRE);
4563 }
4564
Steve Naroff54055232008-10-27 17:20:55 +00004565 return;
4566}
4567
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004568void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4569 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004570 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004571 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004572 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004573 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4574 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004575 GetInnerBlockDeclRefExprs(CBE->getBody(),
4576 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004577 InnerContexts);
4578 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004579 else
4580 GetInnerBlockDeclRefExprs(*CI,
4581 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004582 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004583
4584 }
4585 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004586 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004587 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004588 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004590 }
4591 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4592 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4593 if (Var->isFunctionOrMethodVarDecl())
4594 ImportedLocalExternalDecls.insert(Var);
4595 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004596
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004597 return;
4598}
4599
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004600/// convertFunctionTypeOfBlocks - This routine converts a function type
4601/// whose result type may be a block pointer or whose argument type(s)
4602/// might be block pointers to an equivalent funtion type replacing
4603/// all block pointers to function pointers.
4604QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4605 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4606 // FTP will be null for closures that don't take arguments.
4607 // Generate a funky cast.
4608 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004609 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004610 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004611
4612 if (FTP) {
4613 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4614 E = FTP->arg_type_end(); I && (I != E); ++I) {
4615 QualType t = *I;
4616 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004617 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004618 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004619 ArgTypes.push_back(t);
4620 }
4621 }
4622 QualType FuncType;
4623 // FIXME. Does this work if block takes no argument but has a return type
4624 // which is of block type?
4625 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004626 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004627 else FuncType = QualType(FT, 0);
4628 return FuncType;
4629}
4630
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004631Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004632 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004633 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004634
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004636 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004637 } else if (const BlockDeclRefExpr *CDRE =
4638 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004639 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004640 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004641 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004642 }
4643 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4644 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4645 }
4646 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4647 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4648 else if (const ConditionalOperator *CEXPR =
4649 dyn_cast<ConditionalOperator>(BlockExp)) {
4650 Expr *LHSExp = CEXPR->getLHS();
4651 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4652 Expr *RHSExp = CEXPR->getRHS();
4653 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4654 Expr *CONDExp = CEXPR->getCond();
4655 ConditionalOperator *CondExpr =
4656 new (Context) ConditionalOperator(CONDExp,
4657 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004658 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004659 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004660 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004661 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4662 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004663 } else {
4664 assert(1 && "RewriteBlockClass: Bad type");
4665 }
4666 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004667 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004668 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004669 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004670 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004671
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004672 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004673 SourceLocation(),
4674 &Context->Idents.get("__block_impl"));
4675 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004676
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004677 // Generate a funky cast.
4678 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004679
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004680 // Push the block argument type.
4681 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004682 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004683 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004684 E = FTP->arg_type_end(); I && (I != E); ++I) {
4685 QualType t = *I;
4686 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004687 if (!convertBlockPointerToFunctionPointer(t))
4688 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004689 ArgTypes.push_back(t);
4690 }
Steve Naroff54055232008-10-27 17:20:55 +00004691 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004692 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004693 QualType PtrToFuncCastType
4694 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004696 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004697
John McCall9d125032010-01-15 18:39:57 +00004698 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004699 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004700 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004701 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004702 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4703 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004704 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Douglas Gregor44b43212008-12-11 16:49:14 +00004706 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004707 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004708 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004709 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004710 FD->getType(), VK_LValue,
4711 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004713
John McCall9d125032010-01-15 18:39:57 +00004714 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004715 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004716 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004718 llvm::SmallVector<Expr*, 8> BlkExprs;
4719 // Add the implicit argument.
4720 BlkExprs.push_back(BlkCast);
4721 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004722 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004723 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004724 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004725 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004726 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4727 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004728 Exp->getType(), VK_RValue,
4729 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004730 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004731}
4732
Steve Naroff621edce2009-04-29 16:37:50 +00004733// We need to return the rewritten expression to handle cases where the
4734// BlockDeclRefExpr is embedded in another expression being rewritten.
4735// For example:
4736//
4737// int main() {
4738// __block Foo *f;
4739// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004740//
Steve Naroff621edce2009-04-29 16:37:50 +00004741// void (^myblock)() = ^() {
4742// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4743// i = 77;
4744// };
4745//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004746Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004747 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004748 // for each DeclRefExp where BYREFVAR is name of the variable.
4749 ValueDecl *VD;
4750 bool isArrow = true;
4751 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4752 VD = BDRE->getDecl();
4753 else {
4754 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4755 isArrow = false;
4756 }
4757
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004758 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4759 &Context->Idents.get("__forwarding"),
4760 Context->VoidPtrTy, 0,
4761 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004762 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4763 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004764 FD->getType(), VK_LValue,
4765 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004766
Daniel Dunbar4087f272010-08-17 22:39:59 +00004767 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004768 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4769 &Context->Idents.get(Name),
4770 Context->VoidPtrTy, 0,
4771 /*BitWidth=*/0, /*Mutable=*/true);
4772 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004773 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004774
4775
4776
Steve Naroffdf8570d2009-02-02 17:19:26 +00004777 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004778 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4779 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004780 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004781 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004782}
4783
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004784// Rewrites the imported local variable V with external storage
4785// (static, extern, etc.) as *V
4786//
4787Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4788 ValueDecl *VD = DRE->getDecl();
4789 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4790 if (!ImportedLocalExternalDecls.count(Var))
4791 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004792 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4793 VK_LValue, OK_Ordinary,
4794 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004795 // Need parens to enforce precedence.
4796 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4797 Exp);
4798 ReplaceStmt(DRE, PE);
4799 return PE;
4800}
4801
Steve Naroffb2f9e512008-11-03 23:29:32 +00004802void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4803 SourceLocation LocStart = CE->getLParenLoc();
4804 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004805
4806 // Need to avoid trying to rewrite synthesized casts.
4807 if (LocStart.isInvalid())
4808 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004809 // Need to avoid trying to rewrite casts contained in macros.
4810 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4811 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004812
Steve Naroff54055232008-10-27 17:20:55 +00004813 const char *startBuf = SM->getCharacterData(LocStart);
4814 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004815 QualType QT = CE->getType();
4816 const Type* TypePtr = QT->getAs<Type>();
4817 if (isa<TypeOfExprType>(TypePtr)) {
4818 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4819 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4820 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004821 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004822 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004823 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004824 return;
4825 }
Steve Naroff54055232008-10-27 17:20:55 +00004826 // advance the location to startArgList.
4827 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004828
Steve Naroff54055232008-10-27 17:20:55 +00004829 while (*argPtr++ && (argPtr < endBuf)) {
4830 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004831 case '^':
4832 // Replace the '^' with '*'.
4833 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004834 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004835 break;
Steve Naroff54055232008-10-27 17:20:55 +00004836 }
4837 }
4838 return;
4839}
4840
4841void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4842 SourceLocation DeclLoc = FD->getLocation();
4843 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004844
Steve Naroff54055232008-10-27 17:20:55 +00004845 // We have 1 or more arguments that have closure pointers.
4846 const char *startBuf = SM->getCharacterData(DeclLoc);
4847 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004848
Steve Naroff54055232008-10-27 17:20:55 +00004849 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Steve Naroff54055232008-10-27 17:20:55 +00004851 parenCount++;
4852 // advance the location to startArgList.
4853 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4854 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Steve Naroff54055232008-10-27 17:20:55 +00004856 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Steve Naroff54055232008-10-27 17:20:55 +00004858 while (*argPtr++ && parenCount) {
4859 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004860 case '^':
4861 // Replace the '^' with '*'.
4862 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004863 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004864 break;
4865 case '(':
4866 parenCount++;
4867 break;
4868 case ')':
4869 parenCount--;
4870 break;
Steve Naroff54055232008-10-27 17:20:55 +00004871 }
4872 }
4873 return;
4874}
4875
4876bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004877 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004878 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004879 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004880 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004881 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004882 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004883 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004884 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004885 }
4886 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004887 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004888 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004889 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004890 return true;
4891 }
4892 return false;
4893}
4894
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004895bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4896 const FunctionProtoType *FTP;
4897 const PointerType *PT = QT->getAs<PointerType>();
4898 if (PT) {
4899 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4900 } else {
4901 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4902 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4903 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4904 }
4905 if (FTP) {
4906 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004907 E = FTP->arg_type_end(); I != E; ++I) {
4908 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004909 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004910 if ((*I)->isObjCObjectPointerType() &&
4911 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4912 return true;
4913 }
4914
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004915 }
4916 return false;
4917}
4918
Ted Kremenek8189cde2009-02-07 01:47:29 +00004919void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4920 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004921 const char *argPtr = strchr(Name, '(');
4922 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004923
Steve Naroff54055232008-10-27 17:20:55 +00004924 LParen = argPtr; // output the start.
4925 argPtr++; // skip past the left paren.
4926 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Steve Naroff54055232008-10-27 17:20:55 +00004928 while (*argPtr && parenCount) {
4929 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004930 case '(': parenCount++; break;
4931 case ')': parenCount--; break;
4932 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004933 }
4934 if (parenCount) argPtr++;
4935 }
4936 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4937 RParen = argPtr; // output the end
4938}
4939
4940void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4941 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4942 RewriteBlockPointerFunctionArgs(FD);
4943 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004944 }
Steve Naroff54055232008-10-27 17:20:55 +00004945 // Handle Variables and Typedefs.
4946 SourceLocation DeclLoc = ND->getLocation();
4947 QualType DeclT;
4948 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4949 DeclT = VD->getType();
4950 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4951 DeclT = TDD->getUnderlyingType();
4952 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4953 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004954 else
Steve Naroff54055232008-10-27 17:20:55 +00004955 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Steve Naroff54055232008-10-27 17:20:55 +00004957 const char *startBuf = SM->getCharacterData(DeclLoc);
4958 const char *endBuf = startBuf;
4959 // scan backward (from the decl location) for the end of the previous decl.
4960 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4961 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004962 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4963 std::string buf;
4964 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004965 // *startBuf != '^' if we are dealing with a pointer to function that
4966 // may take block argument types (which will be handled below).
4967 if (*startBuf == '^') {
4968 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004969 buf = '*';
4970 startBuf++;
4971 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004972 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004973 while (*startBuf != ')') {
4974 buf += *startBuf;
4975 startBuf++;
4976 OrigLength++;
4977 }
4978 buf += ')';
4979 OrigLength++;
4980
4981 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4982 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004983 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004984 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004985 DeclLoc = ND->getLocation();
4986 startBuf = SM->getCharacterData(DeclLoc);
4987 const char *argListBegin, *argListEnd;
4988 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4989 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004990 if (*argListBegin == '^')
4991 buf += '*';
4992 else if (*argListBegin == '<') {
4993 buf += "/*";
4994 buf += *argListBegin++;
4995 OrigLength++;;
4996 while (*argListBegin != '>') {
4997 buf += *argListBegin++;
4998 OrigLength++;
4999 }
5000 buf += *argListBegin;
5001 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005002 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005003 else
5004 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005005 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005006 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005007 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005008 buf += ')';
5009 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005010 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005011 ReplaceText(Start, OrigLength, buf);
5012
Steve Naroff54055232008-10-27 17:20:55 +00005013 return;
5014}
5015
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005016
5017/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5018/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5019/// struct Block_byref_id_object *src) {
5020/// _Block_object_assign (&_dest->object, _src->object,
5021/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5022/// [|BLOCK_FIELD_IS_WEAK]) // object
5023/// _Block_object_assign(&_dest->object, _src->object,
5024/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5025/// [|BLOCK_FIELD_IS_WEAK]) // block
5026/// }
5027/// And:
5028/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5029/// _Block_object_dispose(_src->object,
5030/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5031/// [|BLOCK_FIELD_IS_WEAK]) // object
5032/// _Block_object_dispose(_src->object,
5033/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5034/// [|BLOCK_FIELD_IS_WEAK]) // block
5035/// }
5036
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005037std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5038 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005039 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005040 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005041 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005042 CopyDestroyCache.insert(flag);
5043 S = "static void __Block_byref_id_object_copy_";
5044 S += utostr(flag);
5045 S += "(void *dst, void *src) {\n";
5046
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005047 // offset into the object pointer is computed as:
5048 // void * + void* + int + int + void* + void *
5049 unsigned IntSize =
5050 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5051 unsigned VoidPtrSize =
5052 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5053
5054 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5055 S += " _Block_object_assign((char*)dst + ";
5056 S += utostr(offset);
5057 S += ", *(void * *) ((char*)src + ";
5058 S += utostr(offset);
5059 S += "), ";
5060 S += utostr(flag);
5061 S += ");\n}\n";
5062
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005063 S += "static void __Block_byref_id_object_dispose_";
5064 S += utostr(flag);
5065 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005066 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5067 S += utostr(offset);
5068 S += "), ";
5069 S += utostr(flag);
5070 S += ");\n}\n";
5071 return S;
5072}
5073
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005074/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5075/// the declaration into:
5076/// struct __Block_byref_ND {
5077/// void *__isa; // NULL for everything except __weak pointers
5078/// struct __Block_byref_ND *__forwarding;
5079/// int32_t __flags;
5080/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005081/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5082/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005083/// typex ND;
5084/// };
5085///
5086/// It then replaces declaration of ND variable with:
5087/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5088/// __size=sizeof(struct __Block_byref_ND),
5089/// ND=initializer-if-any};
5090///
5091///
5092void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005093 // Insert declaration for the function in which block literal is
5094 // used.
5095 if (CurFunctionDeclToDeclareForBlock)
5096 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005097 int flag = 0;
5098 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005099 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005100 if (DeclLoc.isInvalid())
5101 // If type location is missing, it is because of missing type (a warning).
5102 // Use variable's location which is good for this case.
5103 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005104 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005105 SourceLocation X = ND->getLocEnd();
5106 X = SM->getInstantiationLoc(X);
5107 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005108 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005109 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005110 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005111 ByrefType += " {\n";
5112 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005113 RewriteByRefString(ByrefType, Name, ND);
5114 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005115 ByrefType += " int __flags;\n";
5116 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005117 // Add void *__Block_byref_id_object_copy;
5118 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005119 QualType Ty = ND->getType();
5120 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5121 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005122 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5123 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005124 }
5125
5126 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005127 ByrefType += " " + Name + ";\n";
5128 ByrefType += "};\n";
5129 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005130 SourceLocation FunLocStart;
5131 if (CurFunctionDef)
5132 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5133 else {
5134 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5135 FunLocStart = CurMethodDef->getLocStart();
5136 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005137 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005138 if (Ty.isObjCGCWeak()) {
5139 flag |= BLOCK_FIELD_IS_WEAK;
5140 isa = 1;
5141 }
5142
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005143 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005144 flag = BLOCK_BYREF_CALLER;
5145 QualType Ty = ND->getType();
5146 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5147 if (Ty->isBlockPointerType())
5148 flag |= BLOCK_FIELD_IS_BLOCK;
5149 else
5150 flag |= BLOCK_FIELD_IS_OBJECT;
5151 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005152 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005153 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005154 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005155
5156 // struct __Block_byref_ND ND =
5157 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5158 // initializer-if-any};
5159 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005160 unsigned flags = 0;
5161 if (HasCopyAndDispose)
5162 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005163 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005164 ByrefType.clear();
5165 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005166 std::string ForwardingCastType("(");
5167 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005168 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005169 ByrefType += " " + Name + " = {(void*)";
5170 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005171 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005172 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005173 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005174 ByrefType += "sizeof(";
5175 RewriteByRefString(ByrefType, Name, ND);
5176 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005177 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005178 ByrefType += ", __Block_byref_id_object_copy_";
5179 ByrefType += utostr(flag);
5180 ByrefType += ", __Block_byref_id_object_dispose_";
5181 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005182 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005183 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005184 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005185 }
5186 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005187 SourceLocation startLoc;
5188 Expr *E = ND->getInit();
5189 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5190 startLoc = ECE->getLParenLoc();
5191 else
5192 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005193 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005194 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005195 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005196 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005197 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005198 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005199 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005200 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005201 ByrefType += "sizeof(";
5202 RewriteByRefString(ByrefType, Name, ND);
5203 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005204 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005205 ByrefType += "__Block_byref_id_object_copy_";
5206 ByrefType += utostr(flag);
5207 ByrefType += ", __Block_byref_id_object_dispose_";
5208 ByrefType += utostr(flag);
5209 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005210 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005211 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005212
5213 // Complete the newly synthesized compound expression by inserting a right
5214 // curly brace before the end of the declaration.
5215 // FIXME: This approach avoids rewriting the initializer expression. It
5216 // also assumes there is only one declarator. For example, the following
5217 // isn't currently supported by this routine (in general):
5218 //
5219 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5220 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005221 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5222 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005223 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5224 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005225 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005226
Benjamin Kramerd999b372010-02-14 14:14:16 +00005227 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005228 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005229 return;
5230}
5231
Mike Stump1eb44332009-09-09 15:08:12 +00005232void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005233 // Add initializers for any closure decl refs.
5234 GetBlockDeclRefExprs(Exp->getBody());
5235 if (BlockDeclRefs.size()) {
5236 // Unique all "by copy" declarations.
5237 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005238 if (!BlockDeclRefs[i]->isByRef()) {
5239 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5240 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5241 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5242 }
5243 }
Steve Naroff54055232008-10-27 17:20:55 +00005244 // Unique all "by ref" declarations.
5245 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5246 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005247 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5248 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5249 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5250 }
Steve Naroff54055232008-10-27 17:20:55 +00005251 }
5252 // Find any imported blocks...they will need special attention.
5253 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005254 if (BlockDeclRefs[i]->isByRef() ||
5255 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005256 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005257 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005258 }
5259}
5260
Daniel Dunbar4087f272010-08-17 22:39:59 +00005261FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005262 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005263 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005264 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005265 ID, FType, 0, SC_Extern,
5266 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005267}
5268
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005269Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5270 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005271 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005272 Blocks.push_back(Exp);
5273
5274 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005275
5276 // Add inner imported variables now used in current block.
5277 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005278 if (!InnerBlockDeclRefs.empty()) {
5279 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5280 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5281 ValueDecl *VD = Exp->getDecl();
5282 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005283 // We need to save the copied-in variables in nested
5284 // blocks because it is needed at the end for some of the API generations.
5285 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005286 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5287 BlockDeclRefs.push_back(Exp);
5288 BlockByCopyDeclsPtrSet.insert(VD);
5289 BlockByCopyDecls.push_back(VD);
5290 }
5291 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5292 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5293 BlockDeclRefs.push_back(Exp);
5294 BlockByRefDeclsPtrSet.insert(VD);
5295 BlockByRefDecls.push_back(VD);
5296 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005297 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005298 // Find any imported blocks...they will need special attention.
5299 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5300 if (InnerBlockDeclRefs[i]->isByRef() ||
5301 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5302 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5303 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005304 }
5305 InnerDeclRefsCount.push_back(countOfInnerDecls);
5306
Steve Narofffa15fd92008-10-28 20:29:00 +00005307 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005308
Steve Narofffa15fd92008-10-28 20:29:00 +00005309 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005310 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005311 else if (CurMethodDef)
5312 BuildUniqueMethodName(FuncName, CurMethodDef);
5313 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005314 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005315
Steve Narofffa15fd92008-10-28 20:29:00 +00005316 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005317
Steve Narofffa15fd92008-10-28 20:29:00 +00005318 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5319 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005320
Steve Narofffa15fd92008-10-28 20:29:00 +00005321 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005322 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5323 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005324
5325 FunctionDecl *FD;
5326 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005327
Steve Narofffa15fd92008-10-28 20:29:00 +00005328 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005329 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005330 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5331 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005332
Steve Narofffa15fd92008-10-28 20:29:00 +00005333 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Steve Narofffdc03722008-10-29 21:23:59 +00005335 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005336 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005337 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005338 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005339 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005340 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005341 InitExprs.push_back(castExpr);
5342
Steve Naroff01aec112009-12-06 21:14:13 +00005343 // Initialize the block descriptor.
5344 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005345
Steve Naroff01aec112009-12-06 21:14:13 +00005346 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5347 &Context->Idents.get(DescData.c_str()),
5348 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005349 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005350 UnaryOperator *DescRefExpr =
5351 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5352 Context->VoidPtrTy,
5353 VK_LValue,
5354 SourceLocation()),
5355 UO_AddrOf,
5356 Context->getPointerType(Context->VoidPtrTy),
5357 VK_RValue, OK_Ordinary,
5358 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005359 InitExprs.push_back(DescRefExpr);
5360
Steve Narofffa15fd92008-10-28 20:29:00 +00005361 // Add initializers for any closure decl refs.
5362 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005363 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005365 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005367 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005368 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005369 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005370 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5371 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005372 if (HasLocalVariableExternalStorage(*I)) {
5373 QualType QT = (*I)->getType();
5374 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005375 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5376 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005377 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005378 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005379 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005380 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5381 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005382 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005383 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005385 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005386 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5387 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005388 if (HasLocalVariableExternalStorage(*I)) {
5389 QualType QT = (*I)->getType();
5390 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005391 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5392 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005393 }
5394
Steve Narofffa15fd92008-10-28 20:29:00 +00005395 }
Mike Stump1eb44332009-09-09 15:08:12 +00005396 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005397 }
5398 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005399 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005400 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005401 ValueDecl *ND = (*I);
5402 std::string Name(ND->getNameAsString());
5403 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005404 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005405 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5406 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005407 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005408 SourceLocation(), II);
5409 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5410 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5411
Daniel Dunbar4087f272010-08-17 22:39:59 +00005412 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005413 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5414 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005415 bool isNestedCapturedVar = false;
5416 if (block)
5417 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5418 ce = block->capture_end(); ci != ce; ++ci) {
5419 const VarDecl *variable = ci->getVariable();
5420 if (variable == ND && ci->isNested()) {
5421 assert (ci->isByRef() &&
5422 "SynthBlockInitExpr - captured block variable is not byref");
5423 isNestedCapturedVar = true;
5424 break;
5425 }
5426 }
5427 // captured nested byref variable has its address passed. Do not take
5428 // its address again.
5429 if (!isNestedCapturedVar)
5430 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005431 Context->getPointerType(Exp->getType()),
5432 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005433 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005434 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005435 }
5436 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005437 if (ImportedBlockDecls.size()) {
5438 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5439 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005440 unsigned IntSize =
5441 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005442 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5443 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005444 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005445 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005446 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005447 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005448 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005449 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005450 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005451 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005452 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005453 BlockDeclRefs.clear();
5454 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005455 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005456 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005457 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005458 ImportedBlockDecls.clear();
5459 return NewRep;
5460}
5461
5462//===----------------------------------------------------------------------===//
5463// Function Body / Expression rewriting
5464//===----------------------------------------------------------------------===//
5465
Steve Naroffc77a6362008-12-04 16:24:46 +00005466// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5467// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5468// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5469// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5470// Since the rewriter isn't capable of rewriting rewritten code, it's important
5471// we get this right.
5472void RewriteObjC::CollectPropertySetters(Stmt *S) {
5473 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005474 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005475 if (*CI)
5476 CollectPropertySetters(*CI);
5477
5478 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5479 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005480 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5481 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005482 }
5483 }
5484}
5485
Steve Narofffa15fd92008-10-28 20:29:00 +00005486Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005487 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005488 isa<DoStmt>(S) || isa<ForStmt>(S))
5489 Stmts.push_back(S);
5490 else if (isa<ObjCForCollectionStmt>(S)) {
5491 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005492 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005493 }
Mike Stump1eb44332009-09-09 15:08:12 +00005494
Steve Narofffa15fd92008-10-28 20:29:00 +00005495 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005496
Steve Narofffa15fd92008-10-28 20:29:00 +00005497 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005498 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005499 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005500 Stmt *newStmt;
5501 Stmt *S = (*CI);
5502 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5503 Expr *OldBase = IvarRefExpr->getBase();
5504 bool replaced = false;
5505 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5506 if (replaced) {
5507 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5508 ReplaceStmt(OldBase, IRE->getBase());
5509 else
5510 ReplaceStmt(S, newStmt);
5511 }
5512 }
5513 else
5514 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005515 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005516 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005517 // If dealing with an assignment with LHS being a property reference
5518 // expression, the entire assignment tree is rewritten into a property
5519 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5520 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005521 if (Expr *Exp = dyn_cast<Expr>(S))
John McCall12f78a62010-12-02 01:19:52 +00005522 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005523 if (PropSetters[Exp]) {
5524 ++CI;
5525 continue;
5526 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005527 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005528 }
Mike Stump1eb44332009-09-09 15:08:12 +00005529
Steve Narofffa15fd92008-10-28 20:29:00 +00005530 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005531 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005532 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5533 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005534 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005535 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005536 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005537 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005538 Stmt *SaveCurrentBody = CurrentBody;
5539 CurrentBody = BE->getBody();
5540 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005542 CurrentBody = SaveCurrentBody;
5543 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005544 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005545 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005546 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005547 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005548
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005549 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5550
Steve Narofffa15fd92008-10-28 20:29:00 +00005551 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005552 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005553 return blockTranscribed;
5554 }
5555 // Handle specific things.
5556 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5557 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005558
John McCall12f78a62010-12-02 01:19:52 +00005559 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005560 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5561 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5562
5563 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005564 if (BinOp) {
5565 // Because the rewriter doesn't allow us to rewrite rewritten code,
5566 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005567 DisableReplaceStmt = true;
5568 // Save the source range. Even if we disable the replacement, the
5569 // rewritten node will have been inserted into the tree. If the synthesized
5570 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005571 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005572 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5573 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005574 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005575 // Need to rewrite the ivar access expression if need be.
5576 if (isa<ObjCIvarRefExpr>(newStmt)) {
5577 bool replaced = false;
5578 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5579 }
5580
Steve Naroffb619d952008-12-09 12:56:34 +00005581 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005582 //
5583 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5584 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5585 // to see the original expression). Consider this example:
5586 //
5587 // Foo *obj1, *obj2;
5588 //
5589 // obj1.i = [obj2 rrrr];
5590 //
5591 // 'BinOp' for the previous expression looks like:
5592 //
5593 // (BinaryOperator 0x231ccf0 'int' '='
5594 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5595 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5596 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5597 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5598 //
5599 // 'newStmt' represents the rewritten message expression. For example:
5600 //
5601 // (CallExpr 0x231d300 'id':'struct objc_object *'
5602 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5603 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5604 // (CStyleCastExpr 0x231d220 'void *'
5605 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5606 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005607 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005608 // can be used as the setter argument. ReplaceStmt() will still 'see'
5609 // the original RHS (since we haven't altered BinOp).
5610 //
Mike Stump1eb44332009-09-09 15:08:12 +00005611 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005612 // node. As a result, we now leak the original AST nodes.
5613 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005614 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005615 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005616 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005617 }
5618 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005619
Steve Narofffa15fd92008-10-28 20:29:00 +00005620 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5621 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005622
Steve Narofffa15fd92008-10-28 20:29:00 +00005623 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5624 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005625
Steve Narofffa15fd92008-10-28 20:29:00 +00005626 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005627#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 // Before we rewrite it, put the original message expression in a comment.
5629 SourceLocation startLoc = MessExpr->getLocStart();
5630 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005631
Steve Narofffa15fd92008-10-28 20:29:00 +00005632 const char *startBuf = SM->getCharacterData(startLoc);
5633 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005634
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 std::string messString;
5636 messString += "// ";
5637 messString.append(startBuf, endBuf-startBuf+1);
5638 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005639
5640 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 // InsertText(clang::SourceLocation, char const*, unsigned int).
5642 // InsertText(startLoc, messString.c_str(), messString.size());
5643 // Tried this, but it didn't work either...
5644 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005645#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005646 return RewriteMessageExpr(MessExpr);
5647 }
Mike Stump1eb44332009-09-09 15:08:12 +00005648
Steve Narofffa15fd92008-10-28 20:29:00 +00005649 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5650 return RewriteObjCTryStmt(StmtTry);
5651
5652 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5653 return RewriteObjCSynchronizedStmt(StmtTry);
5654
5655 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5656 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005657
Steve Narofffa15fd92008-10-28 20:29:00 +00005658 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5659 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005660
5661 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005663 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005664 OrigStmtRange.getEnd());
5665 if (BreakStmt *StmtBreakStmt =
5666 dyn_cast<BreakStmt>(S))
5667 return RewriteBreakStmt(StmtBreakStmt);
5668 if (ContinueStmt *StmtContinueStmt =
5669 dyn_cast<ContinueStmt>(S))
5670 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005671
5672 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 // and cast exprs.
5674 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5675 // FIXME: What we're doing here is modifying the type-specifier that
5676 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005677 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005678 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5679 // the context of an ObjCForCollectionStmt. For example:
5680 // NSArray *someArray;
5681 // for (id <FooProtocol> index in someArray) ;
5682 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5683 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005684 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005685 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005686
Steve Narofffa15fd92008-10-28 20:29:00 +00005687 // Blocks rewrite rules.
5688 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5689 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005690 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005691 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005692 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005693 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005694 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005696 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005697 if (VD->hasAttr<BlocksAttr>()) {
5698 static unsigned uniqueByrefDeclCount = 0;
5699 assert(!BlockByRefDeclNo.count(ND) &&
5700 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5701 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005702 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005703 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005704 else
5705 RewriteTypeOfDecl(VD);
5706 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005707 }
5708 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005709 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005710 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005711 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005712 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5713 }
5714 }
5715 }
Mike Stump1eb44332009-09-09 15:08:12 +00005716
Steve Narofffa15fd92008-10-28 20:29:00 +00005717 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5718 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005719
5720 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5722 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005723 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5724 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 && "Statement stack mismatch");
5726 Stmts.pop_back();
5727 }
5728 // Handle blocks rewriting.
5729 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5730 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005731 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005732 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5734 ValueDecl *VD = DRE->getDecl();
5735 if (VD->hasAttr<BlocksAttr>())
5736 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005737 if (HasLocalVariableExternalStorage(VD))
5738 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005739 }
5740
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005742 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005743 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005744 ReplaceStmt(S, BlockCall);
5745 return BlockCall;
5746 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005747 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005748 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 RewriteCastExpr(CE);
5750 }
5751#if 0
5752 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005753 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5754 ICE->getSubExpr(),
5755 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 // Get the new text.
5757 std::string SStr;
5758 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005759 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005760 const std::string &Str = Buf.str();
5761
5762 printf("CAST = %s\n", &Str[0]);
5763 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5764 delete S;
5765 return Replacement;
5766 }
5767#endif
5768 // Return this stmt unmodified.
5769 return S;
5770}
5771
Steve Naroff3d7e7862009-12-05 15:55:59 +00005772void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5773 for (RecordDecl::field_iterator i = RD->field_begin(),
5774 e = RD->field_end(); i != e; ++i) {
5775 FieldDecl *FD = *i;
5776 if (isTopLevelBlockPointerType(FD->getType()))
5777 RewriteBlockPointerDecl(FD);
5778 if (FD->getType()->isObjCQualifiedIdType() ||
5779 FD->getType()->isObjCQualifiedInterfaceType())
5780 RewriteObjCQualifiedInterfaceTypes(FD);
5781 }
5782}
5783
Steve Narofffa15fd92008-10-28 20:29:00 +00005784/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5785/// main file of the input.
5786void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005788 if (FD->isOverloadedOperator())
5789 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Steve Narofffa15fd92008-10-28 20:29:00 +00005791 // Since function prototypes don't have ParmDecl's, we check the function
5792 // prototype. This enables us to rewrite function declarations and
5793 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005794 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005795
Sebastian Redld3a413d2009-04-26 20:35:05 +00005796 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005797 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005798 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005799 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005800 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005801 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005802 Body =
5803 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5804 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005805 CurrentBody = 0;
5806 if (PropParentMap) {
5807 delete PropParentMap;
5808 PropParentMap = 0;
5809 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005810 // This synthesizes and inserts the block "impl" struct, invoke function,
5811 // and any copy/dispose helper functions.
5812 InsertBlockLiteralsWithinFunction(FD);
5813 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005814 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005815 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005816 return;
5817 }
5818 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005819 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005820 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005821 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005822 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005823 Body =
5824 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5825 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005826 CurrentBody = 0;
5827 if (PropParentMap) {
5828 delete PropParentMap;
5829 PropParentMap = 0;
5830 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005831 InsertBlockLiteralsWithinMethod(MD);
5832 CurMethodDef = 0;
5833 }
5834 }
5835 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5836 ClassImplementation.push_back(CI);
5837 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5838 CategoryImplementation.push_back(CI);
5839 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5840 RewriteForwardClassDecl(CD);
5841 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5842 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005843 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005844 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005845 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005846 CheckFunctionPointerDecl(VD->getType(), VD);
5847 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005848 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 RewriteCastExpr(CE);
5850 }
5851 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005852 } else if (VD->getType()->isRecordType()) {
5853 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5854 if (RD->isDefinition())
5855 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005856 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005857 if (VD->getInit()) {
5858 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005859 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005860 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005861 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005862 CurrentBody = 0;
5863 if (PropParentMap) {
5864 delete PropParentMap;
5865 PropParentMap = 0;
5866 }
Mike Stump1eb44332009-09-09 15:08:12 +00005867 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005868 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005869 GlobalVarDecl = 0;
5870
5871 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005872 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005873 RewriteCastExpr(CE);
5874 }
5875 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005876 return;
5877 }
5878 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005879 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005880 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005881 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005882 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5883 return;
5884 }
5885 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005886 if (RD->isDefinition())
5887 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005888 return;
5889 }
5890 // Nothing yet.
5891}
5892
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005893void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005894 if (Diags.hasErrorOccurred())
5895 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005896
Steve Narofffa15fd92008-10-28 20:29:00 +00005897 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005898
Steve Naroff621edce2009-04-29 16:37:50 +00005899 // Here's a great place to add any extra declarations that may be needed.
5900 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005901 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005902 E = ProtocolExprDecls.end(); I != E; ++I)
5903 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5904
Benjamin Kramerd999b372010-02-14 14:14:16 +00005905 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005906 if (ClassImplementation.size() || CategoryImplementation.size())
5907 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005908
Steve Narofffa15fd92008-10-28 20:29:00 +00005909 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5910 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005911 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005912 Rewrite.getRewriteBufferFor(MainFileID)) {
5913 //printf("Changed:\n");
5914 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5915 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005916 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005917 }
Steve Narofface66252008-11-13 20:07:04 +00005918
Steve Naroff621edce2009-04-29 16:37:50 +00005919 if (ClassImplementation.size() || CategoryImplementation.size() ||
5920 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005921 // Rewrite Objective-c meta data*
5922 std::string ResultStr;
5923 SynthesizeMetaDataIntoBuffer(ResultStr);
5924 // Emit metadata.
5925 *OutFile << ResultStr;
5926 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005927 OutFile->flush();
5928}