blob: 464d4c4499298bab327052b9850c10781473b4f7 [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);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000301 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000303 Expr **args, unsigned nargs,
304 SourceLocation StartLoc=SourceLocation(),
305 SourceLocation EndLoc=SourceLocation());
306 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
307 SourceLocation StartLoc=SourceLocation(),
308 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000309 Stmt *RewriteBreakStmt(BreakStmt *S);
310 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000311 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Steve Naroff09b266e2007-10-30 23:14:51 +0000313 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000314 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000315 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000316 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000317 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000318 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000319 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000320 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000321 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000322 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Chris Lattnerf04da132007-10-24 17:06:59 +0000324 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000325 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000326 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000328 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Douglas Gregor653f1b12009-04-23 01:02:12 +0000331 template<typename MethodIterator>
332 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
333 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000334 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000335 llvm::StringRef prefix,
336 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Steve Naroff621edce2009-04-29 16:37:50 +0000339 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000340 llvm::StringRef prefix,
341 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000342 std::string &Result);
343 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000344 llvm::StringRef prefix,
345 llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000346 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000347 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000348 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000349 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000350 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000351 void RewriteImplementations();
352 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff54055232008-10-27 17:20:55 +0000354 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000355 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000356 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Steve Naroff54055232008-10-27 17:20:55 +0000358 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
359 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
361 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000362 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000363 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000365 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000366 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000367 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000368
369 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000370 llvm::StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000371 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000372 llvm::StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000373 std::string SynthesizeBlockImpl(BlockExpr *CE,
374 std::string Tag, std::string Desc);
375 std::string SynthesizeBlockDescriptor(std::string DescTag,
376 std::string ImplTag,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000377 int i, llvm::StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000378 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000379 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000380 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +0000381 llvm::StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000382 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Steve Naroff54055232008-10-27 17:20:55 +0000384 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000385 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000386 void GetInnerBlockDeclRefExprs(Stmt *S,
387 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000388 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff54055232008-10-27 17:20:55 +0000390 // We avoid calling Type::isBlockPointerType(), since it operates on the
391 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000392 bool isTopLevelBlockPointerType(QualType T) {
393 return isa<BlockPointerType>(T);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000396 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
397 /// to a function pointer type and upon success, returns true; false
398 /// otherwise.
399 bool convertBlockPointerToFunctionPointer(QualType &T) {
400 if (isTopLevelBlockPointerType(T)) {
401 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
402 T = Context->getPointerType(BPT->getPointeeType());
403 return true;
404 }
405 return false;
406 }
407
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000408 void convertToUnqualifiedObjCType(QualType &T) {
409 if (T->isObjCQualifiedIdType())
410 T = Context->getObjCIdType();
411 else if (T->isObjCQualifiedClassType())
412 T = Context->getObjCClassType();
413 else if (T->isObjCObjectPointerType() &&
414 T->getPointeeType()->isObjCQualifiedInterfaceType())
415 T = Context->getObjCIdType();
416 }
417
Steve Naroff54055232008-10-27 17:20:55 +0000418 // FIXME: This predicate seems like it would be useful to add to ASTContext.
419 bool isObjCType(QualType T) {
420 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
421 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Steve Naroff54055232008-10-27 17:20:55 +0000423 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Steve Naroff54055232008-10-27 17:20:55 +0000425 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
426 OCT == Context->getCanonicalType(Context->getObjCClassType()))
427 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek6217b802009-07-29 21:53:49 +0000429 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000430 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000431 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000432 return true;
433 }
434 return false;
435 }
436 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000437 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000438 void GetExtentOfArgList(const char *Name, const char *&LParen,
439 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000440 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Daniel Dunbar4087f272010-08-17 22:39:59 +0000442 FunctionDecl *SynthBlockInitFunctionDecl(llvm::StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
444 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Steve Naroff621edce2009-04-29 16:37:50 +0000446 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000447 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000448 if (From[i] == '"')
449 To += "\\\"";
450 else
451 To += From[i];
452 }
453 }
John McCalle23cf432010-12-14 08:05:40 +0000454
455 QualType getSimpleFunctionType(QualType result,
456 const QualType *args,
457 unsigned numArgs,
458 bool variadic = false) {
459 FunctionProtoType::ExtProtoInfo fpi;
460 fpi.Variadic = variadic;
461 return Context->getFunctionType(result, args, numArgs, fpi);
462 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000463 };
John McCall9d125032010-01-15 18:39:57 +0000464
465 // Helper function: create a CStyleCastExpr with trivial type source info.
466 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000467 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000468 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000469 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000470 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000471 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472}
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
475 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000476 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000477 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000478 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000479 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000480 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000481 // All the args are checked/rewritten. Don't call twice!
482 RewriteBlockPointerDecl(D);
483 break;
484 }
485 }
486}
487
488void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000489 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000490 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000491 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000492}
493
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000494static bool IsHeaderFile(const std::string &Filename) {
495 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000497 if (DotPos == std::string::npos) {
498 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000499 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000502 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
503 // C header: .h
504 // C++ header: .hh or .H;
505 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000506}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000507
Eli Friedman66d6f042009-05-18 22:20:00 +0000508RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000509 Diagnostic &D, const LangOptions &LOpts,
510 bool silenceMacroWarn)
511 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
512 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000513 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000514 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000515 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000516 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000517 "rewriter doesn't support user-specified control flow semantics "
518 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000519}
520
Eli Friedmanbce831b2009-05-18 22:29:17 +0000521ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
522 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000523 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000524 const LangOptions &LOpts,
525 bool SilenceRewriteMacroWarning) {
526 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000527}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000528
Steve Naroffb29b4272008-04-14 22:03:09 +0000529void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000530 Context = &context;
531 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000532 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000533 MsgSendFunctionDecl = 0;
534 MsgSendSuperFunctionDecl = 0;
535 MsgSendStretFunctionDecl = 0;
536 MsgSendSuperStretFunctionDecl = 0;
537 MsgSendFpretFunctionDecl = 0;
538 GetClassFunctionDecl = 0;
539 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000540 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 SelGetUidFunctionDecl = 0;
542 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000543 ConstantStringClassReference = 0;
544 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000545 CurMethodDef = 0;
546 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000547 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000548 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000549 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000550 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000551 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000553 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000554 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000555 PropParentMap = 0;
556 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000557 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000558 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000560 // Get the ID and start/end of the main file.
561 MainFileID = SM->getMainFileID();
562 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
563 MainFileStart = MainBuf->getBufferStart();
564 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner2c78b872009-04-14 23:22:57 +0000566 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000568 // declaring objc_selector outside the parameter list removes a silly
569 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000570 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000571 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000573 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000575 if (LangOpts.Microsoft) {
576 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000577 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
578 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000580 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000582 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
583 Preamble += "typedef struct objc_object Protocol;\n";
584 Preamble += "#define _REWRITER_typedef_Protocol\n";
585 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000586 if (LangOpts.Microsoft) {
587 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
588 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
589 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000590 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000601 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000602 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000603 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
604 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000607 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
609 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
611 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000612 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000613 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
616 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000617 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
618 Preamble += "struct __objcFastEnumerationState {\n\t";
619 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000620 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000621 Preamble += "unsigned long *mutationsPtr;\n\t";
622 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "#define __FASTENUMERATIONSTATE\n";
625 Preamble += "#endif\n";
626 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
627 Preamble += "struct __NSConstantStringImpl {\n";
628 Preamble += " int *isa;\n";
629 Preamble += " int flags;\n";
630 Preamble += " char *str;\n";
631 Preamble += " long length;\n";
632 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000633 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
634 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
635 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000636 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000637 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000638 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
639 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000640 // Blocks preamble.
641 Preamble += "#ifndef BLOCK_IMPL\n";
642 Preamble += "#define BLOCK_IMPL\n";
643 Preamble += "struct __block_impl {\n";
644 Preamble += " void *isa;\n";
645 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000646 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000647 Preamble += " void *FuncPtr;\n";
648 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000649 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000650 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000651 Preamble += "extern \"C\" __declspec(dllexport) "
652 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000653 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
654 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
655 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
656 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000657 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
658 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000659 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
660 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
661 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000662 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000663 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000664 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
665 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000666 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000667 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000668 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000669 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000670 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000671 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000672 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000673 Preamble += "#define __weak\n";
674 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000675 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
676 // as this avoids warning in any 64bit/32bit compilation model.
677 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000678}
679
680
Chris Lattnerf04da132007-10-24 17:06:59 +0000681//===----------------------------------------------------------------------===//
682// Top Level Driver Code
683//===----------------------------------------------------------------------===//
684
Chris Lattner682bf922009-03-29 16:50:03 +0000685void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000686 if (Diags.hasErrorOccurred())
687 return;
688
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000689 // Two cases: either the decl could be in the main file, or it could be in a
690 // #included file. If the former, rewrite it now. If the later, check to see
691 // if we rewrote the #include/#import.
692 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000693 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000695 // If this is for a builtin, ignore it.
696 if (Loc.isInvalid()) return;
697
Steve Naroffebf2b562007-10-23 23:50:29 +0000698 // Look for built-in declarations that we need to refer during the rewrite.
699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000700 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000701 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000702 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000703 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000704 ConstantStringClassReference = FVD;
705 return;
706 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000707 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000708 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000709 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000710 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000711 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000712 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000713 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000715 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000716 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
717 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000718 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
719 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000720 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000721 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000722 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000723 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000724 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000726}
727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728//===----------------------------------------------------------------------===//
729// Syntactic (non-AST) Rewriting Code
730//===----------------------------------------------------------------------===//
731
Steve Naroffb29b4272008-04-14 22:03:09 +0000732void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000733 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000734 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
735 const char *MainBufStart = MainBuf.begin();
736 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000737 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000739 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000740 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
741 if (*BufPtr == '#') {
742 if (++BufPtr == MainBufEnd)
743 return;
744 while (*BufPtr == ' ' || *BufPtr == '\t')
745 if (++BufPtr == MainBufEnd)
746 return;
747 if (!strncmp(BufPtr, "import", ImportLen)) {
748 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000749 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000750 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000751 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000752 BufPtr += ImportLen;
753 }
754 }
755 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000756}
757
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000758static std::string getIvarAccessString(ObjCIvarDecl *OID) {
759 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 std::string S;
761 S = "((struct ";
762 S += ClassDecl->getIdentifier()->getName();
763 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000764 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 return S;
766}
767
Steve Naroffa0876e82008-12-02 17:36:43 +0000768void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
769 ObjCImplementationDecl *IMD,
770 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000771 static bool objcGetPropertyDefined = false;
772 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000773 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000774 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775 const char *startBuf = SM->getCharacterData(startLoc);
776 assert((*startBuf == '@') && "bogus @synthesize location");
777 const char *semiBuf = strchr(startBuf, ';');
778 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000779 SourceLocation onePastSemiLoc =
780 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781
782 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
783 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 if (!OID)
790 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000791 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000792 if (!PD->getGetterMethodDecl()->isDefined()) {
793 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
794 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
795 ObjCPropertyDecl::OBJC_PR_copy));
796 std::string Getr;
797 if (GenGetProperty && !objcGetPropertyDefined) {
798 objcGetPropertyDefined = true;
799 // FIXME. Is this attribute correct in all cases?
800 Getr = "\nextern \"C\" __declspec(dllimport) "
801 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000803 RewriteObjCMethodDecl(OID->getContainingInterface(),
804 PD->getGetterMethodDecl(), Getr);
805 Getr += "{ ";
806 // Synthesize an explicit cast to gain access to the ivar.
807 // See objc-act.c:objc_synthesize_new_getter() for details.
808 if (GenGetProperty) {
809 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
810 Getr += "typedef ";
811 const FunctionType *FPRetType = 0;
812 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
813 FPRetType);
814 Getr += " _TYPE";
815 if (FPRetType) {
816 Getr += ")"; // close the precedence "scope" for "*".
817
818 // Now, emit the argument types (if any).
819 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
820 Getr += "(";
821 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
822 if (i) Getr += ", ";
823 std::string ParamStr = FT->getArgType(i).getAsString(
824 Context->PrintingPolicy);
825 Getr += ParamStr;
826 }
827 if (FT->isVariadic()) {
828 if (FT->getNumArgs()) Getr += ", ";
829 Getr += "...";
830 }
831 Getr += ")";
832 } else
833 Getr += "()";
834 }
835 Getr += ";\n";
836 Getr += "return (_TYPE)";
837 Getr += "objc_getProperty(self, _cmd, ";
838 SynthesizeIvarOffsetComputation(OID, Getr);
839 Getr += ", 1)";
840 }
841 else
842 Getr += "return " + getIvarAccessString(OID);
843 Getr += "; }";
844 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000845 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000846
847 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 // Generate the 'setter' function.
851 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000852 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
853 ObjCPropertyDecl::OBJC_PR_copy);
854 if (GenSetProperty && !objcSetPropertyDefined) {
855 objcSetPropertyDefined = true;
856 // FIXME. Is this attribute correct in all cases?
857 Setr = "\nextern \"C\" __declspec(dllimport) "
858 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
859 }
860
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000861 RewriteObjCMethodDecl(OID->getContainingInterface(),
862 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000863 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000865 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000866 if (GenSetProperty) {
867 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000868 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000870 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 Setr += ", ";
872 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
873 Setr += "0, ";
874 else
875 Setr += "1, ";
876 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
877 Setr += "1)";
878 else
879 Setr += "0)";
880 }
881 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000882 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000883 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000885 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000886 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000887}
Chris Lattner8a12c272007-10-11 18:38:32 +0000888
Steve Naroffb29b4272008-04-14 22:03:09 +0000889void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000890 // Get the start location and compute the semi location.
891 SourceLocation startLoc = ClassDecl->getLocation();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Chris Lattnerf04da132007-10-24 17:06:59 +0000895 // Translate to typedef's that forward reference structs with the same name
896 // as the class. As a convenience, we include the original declaration
897 // as a comment.
898 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000899 typedefString += "// @class ";
900 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
901 I != E; ++I) {
902 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
903 typedefString += ForwardDecl->getNameAsString();
904 if (I+1 != E)
905 typedefString += ", ";
906 else
907 typedefString += ";\n";
908 }
909
Chris Lattner67956052009-02-20 18:04:31 +0000910 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
911 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000912 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000913 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000914 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000915 typedefString += "\n";
916 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000917 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000918 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000919 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000921 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Steve Naroff934f2762007-10-24 22:48:43 +0000924 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000925 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000926}
927
Steve Naroffb29b4272008-04-14 22:03:09 +0000928void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000929 // When method is a synthesized one, such as a getter/setter there is
930 // nothing to rewrite.
931 if (Method->isSynthesized())
932 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000933 SourceLocation LocStart = Method->getLocStart();
934 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner30fc9332009-02-04 01:06:56 +0000936 if (SM->getInstantiationLineNumber(LocEnd) >
937 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000938 InsertText(LocStart, "#if 0\n");
939 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000940 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000941 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000942 }
943}
944
Mike Stump1eb44332009-09-09 15:08:12 +0000945void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000946 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000947
Benjamin Kramerd999b372010-02-14 14:14:16 +0000948 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000949 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000950}
951
Steve Naroffb29b4272008-04-14 22:03:09 +0000952void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000953 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Steve Naroff423cb562007-10-30 13:30:57 +0000955 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000958 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
959 E = CatDecl->prop_end(); I != E; ++I)
960 RewriteProperty(*I);
961
Mike Stump1eb44332009-09-09 15:08:12 +0000962 for (ObjCCategoryDecl::instmeth_iterator
963 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000964 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000965 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000966 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000967 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000968 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000969 RewriteMethodDeclaration(*I);
970
Steve Naroff423cb562007-10-30 13:30:57 +0000971 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000972 ReplaceText(CatDecl->getAtEndRange().getBegin(),
973 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000974}
975
Steve Naroffb29b4272008-04-14 22:03:09 +0000976void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000977 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Steve Naroff752d6ef2007-10-30 16:42:30 +0000979 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000980 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000981
982 for (ObjCProtocolDecl::instmeth_iterator
983 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000984 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000985 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000986 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000987 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000988 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000989 RewriteMethodDeclaration(*I);
990
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000991 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
992 E = PDecl->prop_end(); I != E; ++I)
993 RewriteProperty(*I);
994
Steve Naroff752d6ef2007-10-30 16:42:30 +0000995 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000996 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000997 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000998
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000999 // Must comment out @optional/@required
1000 const char *startBuf = SM->getCharacterData(LocStart);
1001 const char *endBuf = SM->getCharacterData(LocEnd);
1002 for (const char *p = startBuf; p < endBuf; p++) {
1003 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001004 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001005 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001007 }
1008 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001009 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001010 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001012 }
1013 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001014}
1015
Steve Naroffb29b4272008-04-14 22:03:09 +00001016void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001018 if (LocStart.isInvalid())
1019 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001020 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001022}
1023
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001024void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1025 const FunctionType *&FPRetType) {
1026 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001027 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001028 else if (T->isFunctionPointerType() ||
1029 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001030 // needs special handling, since pointer-to-functions have special
1031 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001032 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001033 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001034 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001035 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001036 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001037 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001038 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001039 ResultStr += FPRetType->getResultType().getAsString(
1040 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001041 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001042 }
1043 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001044 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001045}
1046
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001047void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1048 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001049 std::string &ResultStr) {
1050 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1051 const FunctionType *FPRetType = 0;
1052 ResultStr += "\nstatic ";
1053 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001054 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001056 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001057 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001059 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 NameStr += "_I_";
1061 else
1062 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001064 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001065 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001066
1067 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001068 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001069 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001071 }
Mike Stump1eb44332009-09-09 15:08:12 +00001072 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001073 {
1074 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 int len = selString.size();
1076 for (int i = 0; i < len; i++)
1077 if (selString[i] == ':')
1078 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001079 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001081 // Remember this name for metadata emission
1082 MethodInternalNames[OMD] = NameStr;
1083 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001085 // Rewrite arguments
1086 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001089 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001090 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001092 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001093 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001094 ResultStr += "struct ";
1095 }
1096 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001097 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001098 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001099 }
1100 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001101 ResultStr += Context->getObjCClassType().getAsString(
1102 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001105 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001109 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1110 E = OMD->param_end(); PI != E; ++PI) {
1111 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001112 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001113 if (PDecl->getType()->isObjCQualifiedIdType()) {
1114 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001115 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001116 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001117 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001118 QualType QT = PDecl->getType();
1119 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1120 if (convertBlockPointerToFunctionPointer(QT))
1121 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1122 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001123 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001124 ResultStr += Name;
1125 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001127 if (OMD->isVariadic())
1128 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001129 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Steve Naroff76e429d2008-07-16 14:40:40 +00001131 if (FPRetType) {
1132 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Steve Naroff76e429d2008-07-16 14:40:40 +00001134 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001135 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001136 ResultStr += "(";
1137 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1138 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001139 std::string ParamStr = FT->getArgType(i).getAsString(
1140 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001141 ResultStr += ParamStr;
1142 }
1143 if (FT->isVariadic()) {
1144 if (FT->getNumArgs()) ResultStr += ", ";
1145 ResultStr += "...";
1146 }
1147 ResultStr += ")";
1148 } else {
1149 ResultStr += "()";
1150 }
1151 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001153void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001154 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1155 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001157 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001159 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001160 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1161 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001162 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001164 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001165 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001167 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001168
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 const char *startBuf = SM->getCharacterData(LocStart);
1170 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001171 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001175 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1176 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001177 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001180 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001182 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001184 const char *startBuf = SM->getCharacterData(LocStart);
1185 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001186 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001188 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001189 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001190 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001191 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001192 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001193 }
1194
Benjamin Kramerd999b372010-02-14 14:14:16 +00001195 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196}
1197
Steve Naroffb29b4272008-04-14 22:03:09 +00001198void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001199 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001200 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001201 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001202 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += "\n";
1205 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001207 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001208 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001210 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001211 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001213 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001214 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001215
1216 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001218 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001219 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001220 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001221 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001222 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001223 for (ObjCInterfaceDecl::classmeth_iterator
1224 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001225 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001226 RewriteMethodDeclaration(*I);
1227
Steve Naroff2feac5e2007-10-30 03:43:13 +00001228 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001229 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001231}
1232
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001233Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001234 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001235 ObjCMethodDecl *OMD = 0;
1236 QualType Ty;
1237 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001238 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001239 bool Super = false;
1240 QualType SuperTy;
1241 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001242 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001243 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001244 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001245 if (ObjCPropertyRefExpr *PropRefExpr =
1246 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001247 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001248 if (PropRefExpr->isExplicitProperty()) {
1249 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1250 OMD = PDecl->getSetterMethodDecl();
1251 Ty = PDecl->getType();
1252 Sel = PDecl->getSetterName();
1253 } else {
1254 OMD = PropRefExpr->getImplicitPropertySetter();
1255 Sel = OMD->getSelector();
1256 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001257 }
John McCall12f78a62010-12-02 01:19:52 +00001258 Super = PropRefExpr->isSuperReceiver();
1259 if (!Super) {
1260 Receiver = PropRefExpr->getBase();
1261 } else {
1262 SuperTy = PropRefExpr->getSuperReceiverType();
1263 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001264 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001265 }
1266
1267 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Steve Naroffc77a6362008-12-04 16:24:46 +00001268 llvm::SmallVector<Expr *, 1> ExprVec;
1269 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001271 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001272 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001273 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001274 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001275 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001276 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001277 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001278 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001279 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001280 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001281 &ExprVec[0], 1,
1282 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001283 else {
1284 // FIXME. Refactor this into common code with that in
1285 // RewritePropertyOrImplicitGetter
1286 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1287 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1288 if (PropGetters[Exp])
1289 // This allows us to handle chain/nested property/implicit getters.
1290 Receiver = PropGetters[Exp];
1291
Douglas Gregor04badcf2010-04-21 00:45:42 +00001292 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001293 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001294 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001295 /*FIXME: */SourceLocation(),
1296 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001297 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001298 &ExprVec[0], 1,
1299 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001300 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001301 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001302
Steve Naroffc77a6362008-12-04 16:24:46 +00001303 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001304 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001305 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001306 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1307 // to things that stay around.
1308 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001309 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001310}
1311
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001312Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1313 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001314 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001315 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 ObjCMethodDecl *OMD = 0;
1317 QualType Ty;
1318 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001319 bool Super = false;
1320 QualType SuperTy;
1321 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001322 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001323 if (ObjCPropertyRefExpr *PropRefExpr =
1324 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001325 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001326 if (PropRefExpr->isExplicitProperty()) {
1327 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1328 OMD = PDecl->getGetterMethodDecl();
1329 Ty = PDecl->getType();
1330 Sel = PDecl->getGetterName();
1331 } else {
1332 OMD = PropRefExpr->getImplicitPropertyGetter();
1333 Sel = OMD->getSelector();
1334 Ty = PropRefExpr->getType();
1335 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001336 Super = PropRefExpr->isSuperReceiver();
1337 if (!Super)
1338 Receiver = PropRefExpr->getBase();
1339 else {
John McCall12f78a62010-12-02 01:19:52 +00001340 SuperTy = PropRefExpr->getSuperReceiverType();
1341 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001342 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001343 }
1344
1345 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1346
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001347 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001348 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001349 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001350 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001351 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001352 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001353 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001354 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001355 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001356 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001357 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001358 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001359 else {
1360 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1361 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1362 if (PropGetters[Exp])
1363 // This allows us to handle chain/nested property/implicit getters.
1364 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001365 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001366 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001367 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001368 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001369 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001370 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001371 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001372 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001373 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001374
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001375 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1376 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001377
1378 if (!PropParentMap)
1379 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001380 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001381 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001382 ImplicitCastExpr*ICE=0;
1383 if (Parent)
1384 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1385 assert((ICE->getCastKind() == CK_GetObjCProperty)
1386 && "RewritePropertyOrImplicitGetter");
1387 Parent = PropParentMap->getParent(Parent);
1388 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1389 }
1390 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001391 // We stash away the ReplacingStmt since actually doing the
1392 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001393 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001394 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1395 // to things that stay around.
1396 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001397 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001398 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001399 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001400 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001401 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1402 // to things that stay around.
1403 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001404 return ReplacingStmt;
1405 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001406}
1407
Mike Stump1eb44332009-09-09 15:08:12 +00001408Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001409 SourceLocation OrigStart,
1410 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001411 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001412 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001413 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001414 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001415 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001416 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001417 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001418 // lookup which class implements the instance variable.
1419 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001420 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001421 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001422 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Steve Narofff0757612008-05-08 17:52:16 +00001424 // Synthesize an explicit cast to gain access to the ivar.
1425 std::string RecName = clsDeclared->getIdentifier()->getName();
1426 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001427 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001428 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001429 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001430 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1431 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001432 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001433 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001434 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001435 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001436 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001437 IV->getBase()->getLocEnd(),
1438 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001439 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001440 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001441 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001442 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001443 IV->getLocation(),
1444 D->getType(),
1445 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001446 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001447 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001448 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001449 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001450 // Cannot delete IV->getBase(), since PE points to it.
1451 // Replace the old base with the cast. This is important when doing
1452 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001453 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001454 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001455 }
Steve Naroff84472a82008-04-18 21:55:08 +00001456 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001457 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Steve Naroff9f525972008-05-06 23:20:07 +00001459 // Explicit ivar refs need to have a cast inserted.
1460 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001461 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001462 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001463 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001464 // lookup which class implements the instance variable.
1465 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001466 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001467 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001468 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Steve Naroff9f525972008-05-06 23:20:07 +00001470 // Synthesize an explicit cast to gain access to the ivar.
1471 std::string RecName = clsDeclared->getIdentifier()->getName();
1472 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001473 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001474 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001475 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001476 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1477 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001478 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001479 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001480 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001481 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001482 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001483 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001484 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001485 // Cannot delete IV->getBase(), since PE points to it.
1486 // Replace the old base with the cast. This is important when doing
1487 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001488 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001489 return IV;
1490 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001491 }
Steve Naroff84472a82008-04-18 21:55:08 +00001492 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001493}
1494
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001495Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001496 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001497 if (*CI) {
1498 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1499 if (newStmt)
1500 *CI = newStmt;
1501 }
1502 }
1503 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1504 SourceRange OrigStmtRange = S->getSourceRange();
1505 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1506 replaced);
1507 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001508 }
1509 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1510 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1511 return newStmt;
1512 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001513 return S;
1514}
1515
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516/// SynthCountByEnumWithState - To print:
1517/// ((unsigned int (*)
1518/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001519/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001520/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001521/// "countByEnumeratingWithState:objects:count:"),
1522/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523/// (id *)items, (unsigned int)16)
1524///
Steve Naroffb29b4272008-04-14 22:03:09 +00001525void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001526 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1527 "id *, unsigned int))(void *)objc_msgSend)";
1528 buf += "\n\t\t";
1529 buf += "((id)l_collection,\n\t\t";
1530 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1531 buf += "\n\t\t";
1532 buf += "&enumState, "
1533 "(id *)items, (unsigned int)16)";
1534}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001535
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001536/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1537/// statement to exit to its outer synthesized loop.
1538///
Steve Naroffb29b4272008-04-14 22:03:09 +00001539Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001540 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1541 return S;
1542 // replace break with goto __break_label
1543 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001544
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001545 SourceLocation startLoc = S->getLocStart();
1546 buf = "goto __break_label_";
1547 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001548 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001549
1550 return 0;
1551}
1552
1553/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1554/// statement to continue with its inner synthesized loop.
1555///
Steve Naroffb29b4272008-04-14 22:03:09 +00001556Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001557 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1558 return S;
1559 // replace continue with goto __continue_label
1560 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001562 SourceLocation startLoc = S->getLocStart();
1563 buf = "goto __continue_label_";
1564 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001565 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001567 return 0;
1568}
1569
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001570/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001571/// It rewrites:
1572/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001573
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001574/// Into:
1575/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001576/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001578/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001580/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001582/// if (limit) {
1583/// unsigned long startMutations = *enumState.mutationsPtr;
1584/// do {
1585/// unsigned long counter = 0;
1586/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001587/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001588/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001589/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001590/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001591/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001592/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001593/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001594/// objects:items count:16]);
1595/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001596/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001597/// }
1598/// else
1599/// elem = nil;
1600/// }
1601///
Steve Naroffb29b4272008-04-14 22:03:09 +00001602Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001603 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001604 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001605 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001607 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001611 const char *startBuf = SM->getCharacterData(startLoc);
Daniel Dunbar4087f272010-08-17 22:39:59 +00001612 llvm::StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001613 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001614 std::string buf;
1615 buf = "\n{\n\t";
1616 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1617 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001618 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001619 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001620 if (ElementType->isObjCQualifiedIdType() ||
1621 ElementType->isObjCQualifiedInterfaceType())
1622 // Simply use 'id' for all qualified types.
1623 elementTypeAsString = "id";
1624 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001625 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001626 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001627 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001628 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 buf += elementName;
1630 buf += ";\n\t";
1631 }
Chris Lattner06767512008-04-08 05:52:18 +00001632 else {
1633 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001634 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001635 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1636 if (VD->getType()->isObjCQualifiedIdType() ||
1637 VD->getType()->isObjCQualifiedInterfaceType())
1638 // Simply use 'id' for all qualified types.
1639 elementTypeAsString = "id";
1640 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001641 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001644 // struct __objcFastEnumerationState enumState = { 0 };
1645 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1646 // id items[16];
1647 buf += "id items[16];\n\t";
1648 // id l_collection = (id)
1649 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001650 // Find start location of 'collection' the hard way!
1651 const char *startCollectionBuf = startBuf;
1652 startCollectionBuf += 3; // skip 'for'
1653 startCollectionBuf = strchr(startCollectionBuf, '(');
1654 startCollectionBuf++; // skip '('
1655 // find 'in' and skip it.
1656 while (*startCollectionBuf != ' ' ||
1657 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1658 (*(startCollectionBuf+3) != ' ' &&
1659 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1660 startCollectionBuf++;
1661 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001662
1663 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001664 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001665 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001666 SourceLocation rightParenLoc = S->getRParenLoc();
1667 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1668 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001669 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001671 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1672 // objects:items count:16];
1673 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001674 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001675 // ((unsigned int (*)
1676 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001677 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // "countByEnumeratingWithState:objects:count:"),
1680 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001681 // (id *)items, (unsigned int)16);
1682 buf += "unsigned long limit =\n\t\t";
1683 SynthCountByEnumWithState(buf);
1684 buf += ";\n\t";
1685 /// if (limit) {
1686 /// unsigned long startMutations = *enumState.mutationsPtr;
1687 /// do {
1688 /// unsigned long counter = 0;
1689 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001690 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001691 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001692 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 buf += "if (limit) {\n\t";
1694 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1695 buf += "do {\n\t\t";
1696 buf += "unsigned long counter = 0;\n\t\t";
1697 buf += "do {\n\t\t\t";
1698 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1699 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1700 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001701 buf += " = (";
1702 buf += elementTypeAsString;
1703 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001704 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001705 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001706
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001707 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001708 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001709 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001710 /// objects:items count:16]);
1711 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001712 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001713 /// }
1714 /// else
1715 /// elem = nil;
1716 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001717 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001718 buf = ";\n\t";
1719 buf += "__continue_label_";
1720 buf += utostr(ObjCBcLabelNo.back());
1721 buf += ": ;";
1722 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001723 buf += "} while (counter < limit);\n\t";
1724 buf += "} while (limit = ";
1725 SynthCountByEnumWithState(buf);
1726 buf += ");\n\t";
1727 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001728 buf += " = ((";
1729 buf += elementTypeAsString;
1730 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001731 buf += "__break_label_";
1732 buf += utostr(ObjCBcLabelNo.back());
1733 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001734 buf += "}\n\t";
1735 buf += "else\n\t\t";
1736 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001737 buf += " = ((";
1738 buf += elementTypeAsString;
1739 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001740 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001741
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001742 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001743 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001744 if (isa<CompoundStmt>(S->getBody())) {
1745 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001746 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001747 } else {
1748 /* Need to treat single statements specially. For example:
1749 *
1750 * for (A *a in b) if (stuff()) break;
1751 * for (A *a in b) xxxyy;
1752 *
1753 * The following code simply scans ahead to the semi to find the actual end.
1754 */
1755 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1756 const char *semiBuf = strchr(stmtBuf, ';');
1757 assert(semiBuf && "Can't find ';'");
1758 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001759 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001760 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001761 Stmts.pop_back();
1762 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001763 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001764}
1765
Mike Stump1eb44332009-09-09 15:08:12 +00001766/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001767/// This routine rewrites @synchronized(expr) stmt;
1768/// into:
1769/// objc_sync_enter(expr);
1770/// @try stmt @finally { objc_sync_exit(expr); }
1771///
Steve Naroffb29b4272008-04-14 22:03:09 +00001772Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001773 // Get the start location and compute the semi location.
1774 SourceLocation startLoc = S->getLocStart();
1775 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001777 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001778
1779 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001780 buf = "objc_sync_enter((id)";
1781 const char *lparenBuf = startBuf;
1782 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001783 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001784 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1785 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001786 // been rewritten! (which implies the SourceLocation's are invalid).
1787 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001788 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001789 while (*endBuf != ')') endBuf--;
1790 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001791 buf = ");\n";
1792 // declare a new scope with two variables, _stack and _rethrow.
1793 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1794 buf += "int buf[18/*32-bit i386*/];\n";
1795 buf += "char *pointers[4];} _stack;\n";
1796 buf += "id volatile _rethrow = 0;\n";
1797 buf += "objc_exception_try_enter(&_stack);\n";
1798 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001799 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001800 startLoc = S->getSynchBody()->getLocEnd();
1801 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Steve Naroffc7089f12008-08-19 13:04:19 +00001803 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001804 SourceLocation lastCurlyLoc = startLoc;
1805 buf = "}\nelse {\n";
1806 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001807 buf += "}\n";
1808 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001809 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001810
1811 std::string syncBuf;
1812 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001813 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001814 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001815 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001816 std::string syncExprBufS;
1817 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001818 syncExpr->printPretty(syncExprBuf, *Context, 0,
1819 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001820 syncBuf += syncExprBuf.str();
1821 syncBuf += ");";
1822
1823 buf += syncBuf;
1824 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001825 buf += "}\n";
1826 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Benjamin Kramerd999b372010-02-14 14:14:16 +00001828 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001829
1830 bool hasReturns = false;
1831 HasReturnStmts(S->getSynchBody(), hasReturns);
1832 if (hasReturns)
1833 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1834
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001835 return 0;
1836}
1837
Steve Naroffb85e77a2009-12-05 21:43:12 +00001838void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1839{
Steve Naroff8c565152008-12-05 17:03:39 +00001840 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001841 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001842 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001843 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001844
Steve Naroffb85e77a2009-12-05 21:43:12 +00001845 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001846 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001847 TryFinallyContainsReturnDiag);
1848 }
1849 return;
1850}
1851
Steve Naroffb85e77a2009-12-05 21:43:12 +00001852void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1853{
1854 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001855 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001856 if (*CI)
1857 HasReturnStmts(*CI, hasReturns);
1858
1859 if (isa<ReturnStmt>(S))
1860 hasReturns = true;
1861 return;
1862}
1863
1864void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1865 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001866 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001867 if (*CI) {
1868 RewriteTryReturnStmts(*CI);
1869 }
1870 if (isa<ReturnStmt>(S)) {
1871 SourceLocation startLoc = S->getLocStart();
1872 const char *startBuf = SM->getCharacterData(startLoc);
1873
1874 const char *semiBuf = strchr(startBuf, ';');
1875 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1876 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1877
1878 std::string buf;
1879 buf = "{ objc_exception_try_exit(&_stack); return";
1880
Benjamin Kramerd999b372010-02-14 14:14:16 +00001881 ReplaceText(startLoc, 6, buf);
1882 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001883 }
1884 return;
1885}
1886
1887void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1888 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001889 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001890 if (*CI) {
1891 RewriteSyncReturnStmts(*CI, syncExitBuf);
1892 }
1893 if (isa<ReturnStmt>(S)) {
1894 SourceLocation startLoc = S->getLocStart();
1895 const char *startBuf = SM->getCharacterData(startLoc);
1896
1897 const char *semiBuf = strchr(startBuf, ';');
1898 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1899 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1900
1901 std::string buf;
1902 buf = "{ objc_exception_try_exit(&_stack);";
1903 buf += syncExitBuf;
1904 buf += " return";
1905
Benjamin Kramerd999b372010-02-14 14:14:16 +00001906 ReplaceText(startLoc, 6, buf);
1907 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001908 }
1909 return;
1910}
1911
Steve Naroffb29b4272008-04-14 22:03:09 +00001912Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001913 // Get the start location and compute the semi location.
1914 SourceLocation startLoc = S->getLocStart();
1915 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroff75730982007-11-07 04:08:17 +00001917 assert((*startBuf == '@') && "bogus @try location");
1918
1919 std::string buf;
1920 // declare a new scope with two variables, _stack and _rethrow.
1921 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1922 buf += "int buf[18/*32-bit i386*/];\n";
1923 buf += "char *pointers[4];} _stack;\n";
1924 buf += "id volatile _rethrow = 0;\n";
1925 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001926 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001927
Benjamin Kramerd999b372010-02-14 14:14:16 +00001928 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Steve Naroff75730982007-11-07 04:08:17 +00001930 startLoc = S->getTryBody()->getLocEnd();
1931 startBuf = SM->getCharacterData(startLoc);
1932
1933 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Steve Naroff75730982007-11-07 04:08:17 +00001935 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001936 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001937 startLoc = startLoc.getFileLocWithOffset(1);
1938 buf = " /* @catch begin */ else {\n";
1939 buf += " id _caught = objc_exception_extract(&_stack);\n";
1940 buf += " objc_exception_try_enter (&_stack);\n";
1941 buf += " if (_setjmp(_stack.buf))\n";
1942 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1943 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Benjamin Kramerd999b372010-02-14 14:14:16 +00001945 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001946 } else { /* no catch list */
1947 buf = "}\nelse {\n";
1948 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1949 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001950 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001951 }
Steve Naroff75730982007-11-07 04:08:17 +00001952 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001953 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1954 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001955 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001956
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001957 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001958 buf = "if ("; // we are generating code for the first catch clause
1959 else
1960 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001961 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001962 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Steve Naroff75730982007-11-07 04:08:17 +00001964 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Steve Naroff75730982007-11-07 04:08:17 +00001966 const char *lParenLoc = strchr(startBuf, '(');
1967
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001968 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001969 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001970 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001971 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1972 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001973 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001974 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001975 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Steve Naroffe12e6922008-02-01 20:02:07 +00001977 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001978 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001979 } else if (catchDecl) {
1980 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001981 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001982 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001983 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001984 } else if (const ObjCObjectPointerType *Ptr =
1985 t->getAs<ObjCObjectPointerType>()) {
1986 // Should be a pointer to a class.
1987 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1988 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001989 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001990 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001991 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001992 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001993 }
1994 }
1995 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001996 lastCatchBody = Catch->getCatchBody();
1997 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001998 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1999 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2000 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2001 assert((*rParenBuf == ')') && "bogus @catch paren location");
2002 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Mike Stump1eb44332009-09-09 15:08:12 +00002004 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002005 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002006 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002007 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002008 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002009 }
Steve Naroff75730982007-11-07 04:08:17 +00002010 }
2011 // Complete the catch list...
2012 if (lastCatchBody) {
2013 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002014 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2015 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Steve Naroff378f47a2008-09-11 15:29:03 +00002017 // Insert the last (implicit) else clause *before* the right curly brace.
2018 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2019 buf = "} /* last catch end */\n";
2020 buf += "else {\n";
2021 buf += " _rethrow = _caught;\n";
2022 buf += " objc_exception_try_exit(&_stack);\n";
2023 buf += "} } /* @catch end */\n";
2024 if (!S->getFinallyStmt())
2025 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002026 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Steve Naroff75730982007-11-07 04:08:17 +00002028 // Set lastCurlyLoc
2029 lastCurlyLoc = lastCatchBody->getLocEnd();
2030 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002032 startLoc = finalStmt->getLocStart();
2033 startBuf = SM->getCharacterData(startLoc);
2034 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Benjamin Kramerd999b372010-02-14 14:14:16 +00002036 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Steve Naroff75730982007-11-07 04:08:17 +00002038 Stmt *body = finalStmt->getFinallyBody();
2039 SourceLocation startLoc = body->getLocStart();
2040 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002041 assert(*SM->getCharacterData(startLoc) == '{' &&
2042 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002043 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002044 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Steve Naroff75730982007-11-07 04:08:17 +00002046 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002047 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002048 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroff75730982007-11-07 04:08:17 +00002051 // Set lastCurlyLoc
2052 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroff8c565152008-12-05 17:03:39 +00002054 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002055 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002056 } else { /* no finally clause - make sure we synthesize an implicit one */
2057 buf = "{ /* implicit finally clause */\n";
2058 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2059 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2060 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002061 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002062
2063 // Now check for any return/continue/go statements within the @try.
2064 // The implicit finally clause won't called if the @try contains any
2065 // jump statements.
2066 bool hasReturns = false;
2067 HasReturnStmts(S->getTryBody(), hasReturns);
2068 if (hasReturns)
2069 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002070 }
2071 // Now emit the final closing curly brace...
2072 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002073 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002074 return 0;
2075}
2076
Mike Stump1eb44332009-09-09 15:08:12 +00002077// This can't be done with ReplaceStmt(S, ThrowExpr), since
2078// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002079// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002080Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002081 // Get the start location and compute the semi location.
2082 SourceLocation startLoc = S->getLocStart();
2083 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Steve Naroff2bd03922007-11-07 15:32:26 +00002085 assert((*startBuf == '@') && "bogus @throw location");
2086
2087 std::string buf;
2088 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002089 if (S->getThrowExpr())
2090 buf = "objc_exception_throw(";
2091 else // add an implicit argument
2092 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002094 // handle "@ throw" correctly.
2095 const char *wBuf = strchr(startBuf, 'w');
2096 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002097 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Steve Naroff2bd03922007-11-07 15:32:26 +00002099 const char *semiBuf = strchr(startBuf, ';');
2100 assert((*semiBuf == ';') && "@throw: can't find ';'");
2101 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002102 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002103 return 0;
2104}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002105
Steve Naroffb29b4272008-04-14 22:03:09 +00002106Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002107 // Create a new string expression.
2108 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002109 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002110 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002111 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2112 StrEncoding.length(), false,StrType,
2113 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002114 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Chris Lattner07506182007-11-30 22:53:43 +00002116 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002117 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002118 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002119}
2120
Steve Naroffb29b4272008-04-14 22:03:09 +00002121Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002122 if (!SelGetUidFunctionDecl)
2123 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002124 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2125 // Create a call to sel_registerName("selName").
2126 llvm::SmallVector<Expr*, 8> SelExprs;
2127 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002128 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002129 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002130 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002131 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002132 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2133 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002134 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002135 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002136 return SelExp;
2137}
2138
Steve Naroffb29b4272008-04-14 22:03:09 +00002139CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002140 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2141 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002142 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002143 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Steve Naroffebf2b562007-10-23 23:50:29 +00002145 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002146 DeclRefExpr *DRE =
2147 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Steve Naroffebf2b562007-10-23 23:50:29 +00002149 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002150 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002151 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002152 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002153 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002154
John McCall183700f2009-09-21 23:43:11 +00002155 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002157 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002158 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002159 FT->getCallResultType(*Context),
2160 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002161 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002162}
2163
Steve Naroffd5255f52007-11-01 13:24:47 +00002164static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2165 const char *&startRef, const char *&endRef) {
2166 while (startBuf < endBuf) {
2167 if (*startBuf == '<')
2168 startRef = startBuf; // mark the start.
2169 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002170 if (startRef && *startRef == '<') {
2171 endRef = startBuf; // mark the end.
2172 return true;
2173 }
2174 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 }
2176 startBuf++;
2177 }
2178 return false;
2179}
2180
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002181static void scanToNextArgument(const char *&argRef) {
2182 int angle = 0;
2183 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2184 if (*argRef == '<')
2185 angle++;
2186 else if (*argRef == '>')
2187 angle--;
2188 argRef++;
2189 }
2190 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2191}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002192
Steve Naroffb29b4272008-04-14 22:03:09 +00002193bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002194 if (T->isObjCQualifiedIdType())
2195 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002196 if (const PointerType *PT = T->getAs<PointerType>()) {
2197 if (PT->getPointeeType()->isObjCQualifiedIdType())
2198 return true;
2199 }
2200 if (T->isObjCObjectPointerType()) {
2201 T = T->getPointeeType();
2202 return T->isObjCQualifiedInterfaceType();
2203 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002204 if (T->isArrayType()) {
2205 QualType ElemTy = Context->getBaseElementType(T);
2206 return needToScanForQualifiers(ElemTy);
2207 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002208 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002209}
2210
Steve Naroff4f95b752008-07-29 18:15:38 +00002211void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2212 QualType Type = E->getType();
2213 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002214 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Steve Naroffcda658e2008-11-19 21:15:47 +00002216 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2217 Loc = ECE->getLParenLoc();
2218 EndLoc = ECE->getRParenLoc();
2219 } else {
2220 Loc = E->getLocStart();
2221 EndLoc = E->getLocEnd();
2222 }
2223 // This will defend against trying to rewrite synthesized expressions.
2224 if (Loc.isInvalid() || EndLoc.isInvalid())
2225 return;
2226
Steve Naroff4f95b752008-07-29 18:15:38 +00002227 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002228 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002229 const char *startRef = 0, *endRef = 0;
2230 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2231 // Get the locations of the startRef, endRef.
2232 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2233 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2234 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002235 InsertText(LessLoc, "/*");
2236 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002237 }
2238 }
2239}
2240
Steve Naroffb29b4272008-04-14 22:03:09 +00002241void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002242 SourceLocation Loc;
2243 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002244 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002245 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2246 Loc = VD->getLocation();
2247 Type = VD->getType();
2248 }
2249 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2250 Loc = FD->getLocation();
2251 // Check for ObjC 'id' and class types that have been adorned with protocol
2252 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002253 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002254 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002255 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002256 if (!proto)
2257 return;
2258 Type = proto->getResultType();
2259 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002260 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2261 Loc = FD->getLocation();
2262 Type = FD->getType();
2263 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002264 else
2265 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002267 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002268 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Steve Naroffd5255f52007-11-01 13:24:47 +00002270 const char *endBuf = SM->getCharacterData(Loc);
2271 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002272 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002273 startBuf--; // scan backward (from the decl location) for return type.
2274 const char *startRef = 0, *endRef = 0;
2275 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2276 // Get the locations of the startRef, endRef.
2277 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2278 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2279 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002280 InsertText(LessLoc, "/*");
2281 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002282 }
2283 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002284 if (!proto)
2285 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002286 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002287 const char *startBuf = SM->getCharacterData(Loc);
2288 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002289 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2290 if (needToScanForQualifiers(proto->getArgType(i))) {
2291 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Steve Naroffd5255f52007-11-01 13:24:47 +00002293 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002294 // scan forward (from the decl location) for argument types.
2295 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002296 const char *startRef = 0, *endRef = 0;
2297 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2298 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002299 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002300 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002301 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002302 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002303 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002304 InsertText(LessLoc, "/*");
2305 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002306 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002307 startBuf = ++endBuf;
2308 }
2309 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002310 // If the function name is derived from a macro expansion, then the
2311 // argument buffer will not follow the name. Need to speak with Chris.
2312 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 startBuf++; // scan forward (from the decl location) for argument types.
2314 startBuf++;
2315 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002316 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002317}
2318
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002319void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2320 QualType QT = ND->getType();
2321 const Type* TypePtr = QT->getAs<Type>();
2322 if (!isa<TypeOfExprType>(TypePtr))
2323 return;
2324 while (isa<TypeOfExprType>(TypePtr)) {
2325 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2326 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2327 TypePtr = QT->getAs<Type>();
2328 }
2329 // FIXME. This will not work for multiple declarators; as in:
2330 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002331 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002332 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2333 const char *startBuf = SM->getCharacterData(DeclLoc);
2334 if (ND->getInit()) {
2335 std::string Name(ND->getNameAsString());
2336 TypeAsString += " " + Name + " = ";
2337 Expr *E = ND->getInit();
2338 SourceLocation startLoc;
2339 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2340 startLoc = ECE->getLParenLoc();
2341 else
2342 startLoc = E->getLocStart();
2343 startLoc = SM->getInstantiationLoc(startLoc);
2344 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002345 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002346 }
2347 else {
2348 SourceLocation X = ND->getLocEnd();
2349 X = SM->getInstantiationLoc(X);
2350 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002351 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002352 }
2353}
2354
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002355// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002356void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002357 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2358 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002359 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002360 QualType getFuncType =
2361 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002362 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002363 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002364 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002365 SC_Extern,
2366 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002367}
2368
Steve Naroffb29b4272008-04-14 22:03:09 +00002369void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002370 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002371 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002372 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002374 return;
2375 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002377}
2378
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002379void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2380 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002381 const char *argPtr = TypeString.c_str();
2382 if (!strchr(argPtr, '^')) {
2383 Str += TypeString;
2384 return;
2385 }
2386 while (*argPtr) {
2387 Str += (*argPtr == '^' ? '*' : *argPtr);
2388 argPtr++;
2389 }
2390}
2391
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002392// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002393void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2394 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002395 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002396 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002397 const char *argPtr = TypeString.c_str();
2398 int paren = 0;
2399 while (*argPtr) {
2400 switch (*argPtr) {
2401 case '(':
2402 Str += *argPtr;
2403 paren++;
2404 break;
2405 case ')':
2406 Str += *argPtr;
2407 paren--;
2408 break;
2409 case '^':
2410 Str += '*';
2411 if (paren == 1)
2412 Str += VD->getNameAsString();
2413 break;
2414 default:
2415 Str += *argPtr;
2416 break;
2417 }
2418 argPtr++;
2419 }
2420}
2421
2422
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002423void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2424 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2425 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2426 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2427 if (!proto)
2428 return;
2429 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002430 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002431 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002432 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002433 FdStr += "(";
2434 unsigned numArgs = proto->getNumArgs();
2435 for (unsigned i = 0; i < numArgs; i++) {
2436 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002437 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002438 if (i+1 < numArgs)
2439 FdStr += ", ";
2440 }
2441 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002442 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002443 CurFunctionDeclToDeclareForBlock = 0;
2444}
2445
Steve Naroffc0a123c2008-03-11 17:37:02 +00002446// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002447void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002448 if (SuperContructorFunctionDecl)
2449 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002450 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002451 llvm::SmallVector<QualType, 16> ArgTys;
2452 QualType argT = Context->getObjCIdType();
2453 assert(!argT.isNull() && "Can't find 'id' type");
2454 ArgTys.push_back(argT);
2455 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002456 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2457 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002458 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002459 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002460 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002461 SC_Extern,
2462 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002463}
2464
Steve Naroff09b266e2007-10-30 23:14:51 +00002465// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002466void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002467 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2468 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002470 assert(!argT.isNull() && "Can't find 'id' type");
2471 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002472 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002473 assert(!argT.isNull() && "Can't find 'SEL' type");
2474 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002475 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2476 &ArgTys[0], ArgTys.size(),
2477 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002478 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002479 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002480 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002481 SC_Extern,
2482 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002483}
2484
Steve Naroff874e2322007-11-15 10:28:18 +00002485// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002486void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002487 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2488 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002489 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002490 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002491 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002492 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2493 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2494 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002495 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002496 assert(!argT.isNull() && "Can't find 'SEL' type");
2497 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002498 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2499 &ArgTys[0], ArgTys.size(),
2500 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002501 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002502 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002503 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002504 SC_Extern,
2505 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002506}
2507
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002508// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002509void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002510 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2511 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002512 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002513 assert(!argT.isNull() && "Can't find 'id' type");
2514 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002515 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002516 assert(!argT.isNull() && "Can't find 'SEL' type");
2517 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002518 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2519 &ArgTys[0], ArgTys.size(),
2520 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002521 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002522 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002523 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002524 SC_Extern,
2525 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002526}
2527
Mike Stump1eb44332009-09-09 15:08:12 +00002528// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002529// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002530void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002531 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002532 &Context->Idents.get("objc_msgSendSuper_stret");
2533 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002534 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002535 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002536 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002537 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2538 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2539 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002540 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002541 assert(!argT.isNull() && "Can't find 'SEL' type");
2542 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002543 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2544 &ArgTys[0], ArgTys.size(),
2545 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002546 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002547 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002548 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002549 SC_Extern,
2550 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002551}
2552
Steve Naroff1284db82008-05-08 22:02:18 +00002553// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002554void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002555 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2556 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002557 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002558 assert(!argT.isNull() && "Can't find 'id' type");
2559 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002560 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002561 assert(!argT.isNull() && "Can't find 'SEL' type");
2562 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002563 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2564 &ArgTys[0], ArgTys.size(),
2565 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002566 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002567 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002568 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002569 SC_Extern,
2570 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002571}
2572
Steve Naroff09b266e2007-10-30 23:14:51 +00002573// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002574void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002575 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2576 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002577 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002578 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2579 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002580 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002581 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002582 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002583 SC_Extern,
2584 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002585}
2586
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002587// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2588void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2589 IdentifierInfo *getSuperClassIdent =
2590 &Context->Idents.get("class_getSuperclass");
2591 llvm::SmallVector<QualType, 16> ArgTys;
2592 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002593 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2594 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002595 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002596 SourceLocation(),
2597 getSuperClassIdent,
2598 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002599 SC_Extern,
2600 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002601 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002602}
2603
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002604// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002605void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002606 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2607 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002608 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002609 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2610 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002611 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002612 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002613 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002614 SC_Extern,
2615 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002616}
2617
Steve Naroffb29b4272008-04-14 22:03:09 +00002618Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 QualType strType = getConstantStringStructType();
2620
2621 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002622
2623 std::string tmpName = InFileName;
2624 unsigned i;
2625 for (i=0; i < tmpName.length(); i++) {
2626 char c = tmpName.at(i);
2627 // replace any non alphanumeric characters with '_'.
2628 if (!isalpha(c) && (c < '0' || c > '9'))
2629 tmpName[i] = '_';
2630 }
2631 S += tmpName;
2632 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002633 S += utostr(NumObjCStringLiterals++);
2634
Steve Naroffba92b2e2008-03-27 22:29:16 +00002635 Preamble += "static __NSConstantStringImpl " + S;
2636 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2637 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002638 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002639 std::string prettyBufS;
2640 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002641 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2642 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002643 Preamble += prettyBuf.str();
2644 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002645 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002646
2647 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002648 &Context->Idents.get(S), strType, 0,
John McCalld931b082010-08-26 03:08:43 +00002649 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002650 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2651 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002652 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002653 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002654 VK_RValue, OK_Ordinary,
2655 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002656 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002657 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002658 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002659 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002660 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002661 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002662}
2663
Steve Naroff874e2322007-11-15 10:28:18 +00002664// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002665QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002666 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002667 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002668 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002669 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002670 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Steve Naroff874e2322007-11-15 10:28:18 +00002672 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002673 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002674 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002675 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002676
Steve Naroff874e2322007-11-15 10:28:18 +00002677 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002678 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002679 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2680 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002681 FieldTypes[i], 0,
2682 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002683 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002684 }
Mike Stump1eb44332009-09-09 15:08:12 +00002685
Douglas Gregor838db382010-02-11 01:19:42 +00002686 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002687 }
2688 return Context->getTagDeclType(SuperStructDecl);
2689}
2690
Steve Naroffb29b4272008-04-14 22:03:09 +00002691QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002692 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002693 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002694 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002695 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002696 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002698 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002699 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002701 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002702 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002703 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002704 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002705 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002706
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002707 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002708 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002709 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2710 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002711 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002712 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002713 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002714 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002715 }
2716
Douglas Gregor838db382010-02-11 01:19:42 +00002717 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002718 }
2719 return Context->getTagDeclType(ConstantStringDecl);
2720}
2721
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002722Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2723 SourceLocation StartLoc,
2724 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002725 if (!SelGetUidFunctionDecl)
2726 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002727 if (!MsgSendFunctionDecl)
2728 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002729 if (!MsgSendSuperFunctionDecl)
2730 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002731 if (!MsgSendStretFunctionDecl)
2732 SynthMsgSendStretFunctionDecl();
2733 if (!MsgSendSuperStretFunctionDecl)
2734 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002735 if (!MsgSendFpretFunctionDecl)
2736 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002737 if (!GetClassFunctionDecl)
2738 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002739 if (!GetSuperClassFunctionDecl)
2740 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002741 if (!GetMetaClassFunctionDecl)
2742 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Steve Naroff874e2322007-11-15 10:28:18 +00002744 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002745 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2746 // May need to use objc_msgSend_stret() as well.
2747 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002748 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2749 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002750 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002751 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002752 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002753 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002754 }
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Steve Naroff934f2762007-10-24 22:48:43 +00002756 // Synthesize a call to objc_msgSend().
2757 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002758 switch (Exp->getReceiverKind()) {
2759 case ObjCMessageExpr::SuperClass: {
2760 MsgSendFlavor = MsgSendSuperFunctionDecl;
2761 if (MsgSendStretFlavor)
2762 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2763 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregor04badcf2010-04-21 00:45:42 +00002765 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Douglas Gregor04badcf2010-04-21 00:45:42 +00002767 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002768
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769 // set the receiver to self, the first argument to all methods.
2770 InitExprs.push_back(
2771 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002772 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002773 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002774 Context->getObjCIdType(),
2775 VK_RValue,
2776 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Douglas Gregor04badcf2010-04-21 00:45:42 +00002779 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2780 llvm::SmallVector<Expr*, 8> ClsExprs;
2781 QualType argType = Context->getPointerType(Context->CharTy);
2782 ClsExprs.push_back(StringLiteral::Create(*Context,
2783 ClassDecl->getIdentifier()->getNameStart(),
2784 ClassDecl->getIdentifier()->getLength(),
2785 false, argType, SourceLocation()));
2786 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2787 &ClsExprs[0],
2788 ClsExprs.size(),
2789 StartLoc,
2790 EndLoc);
2791 // (Class)objc_getClass("CurrentClass")
2792 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2793 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002794 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795 ClsExprs.clear();
2796 ClsExprs.push_back(ArgExpr);
2797 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2798 &ClsExprs[0], ClsExprs.size(),
2799 StartLoc, EndLoc);
2800
2801 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2802 // To turn off a warning, type-cast to 'id'
2803 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2804 NoTypeInfoCStyleCastExpr(Context,
2805 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002806 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002807 // struct objc_super
2808 QualType superType = getSuperStructType();
2809 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002810
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 if (LangOpts.Microsoft) {
2812 SynthSuperContructorFunctionDecl();
2813 // Simulate a contructor call...
2814 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002815 superType, VK_LValue,
2816 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002817 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2818 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002819 superType, VK_LValue,
2820 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 // The code for super is a little tricky to prevent collision with
2822 // the structure definition in the header. The rewriter has it's own
2823 // internal definition (__rw_objc_super) that is uses. This is why
2824 // we need the cast below. For example:
2825 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2826 //
John McCall2de56d12010-08-25 11:45:40 +00002827 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002829 VK_RValue, OK_Ordinary,
2830 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2832 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002833 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002834 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 // (struct objc_super) { <exprs from above> }
2836 InitListExpr *ILE =
2837 new (Context) InitListExpr(*Context, SourceLocation(),
2838 &InitExprs[0], InitExprs.size(),
2839 SourceLocation());
2840 TypeSourceInfo *superTInfo
2841 = Context->getTrivialTypeSourceInfo(superType);
2842 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002843 superType, VK_LValue,
2844 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002846 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002848 VK_RValue, OK_Ordinary,
2849 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002850 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 MsgExprs.push_back(SuperRep);
2852 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002853 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854
2855 case ObjCMessageExpr::Class: {
2856 llvm::SmallVector<Expr*, 8> ClsExprs;
2857 QualType argType = Context->getPointerType(Context->CharTy);
2858 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002859 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002860 IdentifierInfo *clsName = Class->getIdentifier();
2861 ClsExprs.push_back(StringLiteral::Create(*Context,
2862 clsName->getNameStart(),
2863 clsName->getLength(),
2864 false, argType,
2865 SourceLocation()));
2866 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2867 &ClsExprs[0],
2868 ClsExprs.size(),
2869 StartLoc, EndLoc);
2870 MsgExprs.push_back(Cls);
2871 break;
2872 }
2873
2874 case ObjCMessageExpr::SuperInstance:{
2875 MsgSendFlavor = MsgSendSuperFunctionDecl;
2876 if (MsgSendStretFlavor)
2877 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2878 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2879 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2880 llvm::SmallVector<Expr*, 4> InitExprs;
2881
2882 InitExprs.push_back(
2883 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002884 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002886 Context->getObjCIdType(),
2887 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002888 ); // set the 'receiver'.
2889
2890 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2891 llvm::SmallVector<Expr*, 8> ClsExprs;
2892 QualType argType = Context->getPointerType(Context->CharTy);
2893 ClsExprs.push_back(StringLiteral::Create(*Context,
2894 ClassDecl->getIdentifier()->getNameStart(),
2895 ClassDecl->getIdentifier()->getLength(),
2896 false, argType, SourceLocation()));
2897 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2898 &ClsExprs[0],
2899 ClsExprs.size(),
2900 StartLoc, EndLoc);
2901 // (Class)objc_getClass("CurrentClass")
2902 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2903 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002904 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002905 ClsExprs.clear();
2906 ClsExprs.push_back(ArgExpr);
2907 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2908 &ClsExprs[0], ClsExprs.size(),
2909 StartLoc, EndLoc);
2910
2911 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2912 // To turn off a warning, type-cast to 'id'
2913 InitExprs.push_back(
2914 // set 'super class', using class_getSuperclass().
2915 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002916 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002917 // struct objc_super
2918 QualType superType = getSuperStructType();
2919 Expr *SuperRep;
2920
2921 if (LangOpts.Microsoft) {
2922 SynthSuperContructorFunctionDecl();
2923 // Simulate a contructor call...
2924 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002925 superType, VK_LValue,
2926 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002927 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2928 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002929 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 // The code for super is a little tricky to prevent collision with
2931 // the structure definition in the header. The rewriter has it's own
2932 // internal definition (__rw_objc_super) that is uses. This is why
2933 // we need the cast below. For example:
2934 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2935 //
John McCall2de56d12010-08-25 11:45:40 +00002936 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002937 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002938 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002939 SourceLocation());
2940 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2941 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002942 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002943 } else {
2944 // (struct objc_super) { <exprs from above> }
2945 InitListExpr *ILE =
2946 new (Context) InitListExpr(*Context, SourceLocation(),
2947 &InitExprs[0], InitExprs.size(),
2948 SourceLocation());
2949 TypeSourceInfo *superTInfo
2950 = Context->getTrivialTypeSourceInfo(superType);
2951 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002952 superType, VK_RValue, ILE,
2953 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002954 }
2955 MsgExprs.push_back(SuperRep);
2956 break;
2957 }
2958
2959 case ObjCMessageExpr::Instance: {
2960 // Remove all type-casts because it may contain objc-style types; e.g.
2961 // Foo<Proto> *.
2962 Expr *recExpr = Exp->getInstanceReceiver();
2963 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2964 recExpr = CE->getSubExpr();
2965 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002966 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002967 MsgExprs.push_back(recExpr);
2968 break;
2969 }
2970 }
2971
Steve Naroffbeaf2992007-11-03 11:27:19 +00002972 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002973 llvm::SmallVector<Expr*, 8> SelExprs;
2974 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002975 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002976 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002977 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002978 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002979 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002980 &SelExprs[0], SelExprs.size(),
2981 StartLoc,
2982 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002983 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002984
Steve Naroff934f2762007-10-24 22:48:43 +00002985 // Now push any user supplied arguments.
2986 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002987 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002988 // Make all implicit casts explicit...ICE comes in handy:-)
2989 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2990 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002991 QualType type = ICE->getType();
2992 if (needToScanForQualifiers(type))
2993 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002994 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002995 (void)convertBlockPointerToFunctionPointer(type);
John McCalla5bbc502010-11-15 09:46:46 +00002996 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002997 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002998 }
2999 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003000 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003001 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003002 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003003 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003004 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003005 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003006 }
Mike Stump1eb44332009-09-09 15:08:12 +00003007 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003008 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003009 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3010 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003011 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003012 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003013 }
Steve Naroffab972d32007-11-04 22:37:50 +00003014 // Generate the funky cast.
3015 CastExpr *cast;
3016 llvm::SmallVector<QualType, 8> ArgTypes;
3017 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Steve Naroffab972d32007-11-04 22:37:50 +00003019 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003020 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3021 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3022 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003023 ArgTypes.push_back(Context->getObjCIdType());
3024 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003025 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003026 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003027 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3028 E = OMD->param_end(); PI != E; ++PI) {
3029 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003030 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003031 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003032 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003033 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003034 ArgTypes.push_back(t);
3035 }
Chris Lattner89951a82009-02-20 18:43:26 +00003036 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3037 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003038 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003039 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003040 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003041 }
3042 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003043 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Steve Naroffab972d32007-11-04 22:37:50 +00003045 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003046 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003047 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003048
Mike Stump1eb44332009-09-09 15:08:12 +00003049 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003050 // If we don't do this cast, we get the following bizarre warning/note:
3051 // xx.m:13: warning: function called through a non-compatible type
3052 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003053 cast = NoTypeInfoCStyleCastExpr(Context,
3054 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003055 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003056
Steve Naroffab972d32007-11-04 22:37:50 +00003057 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003058 QualType castType =
3059 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3060 // If we don't have a method decl, force a variadic cast.
3061 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003062 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003063 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003064 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003065
3066 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003067 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003068
John McCall183700f2009-09-21 23:43:11 +00003069 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003070 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003071 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003072 FT->getResultType(), VK_RValue,
3073 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003074 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003075 if (MsgSendStretFlavor) {
3076 // We have the method which returns a struct/union. Must also generate
3077 // call to objc_msgSend_stret and hang both varieties on a conditional
3078 // expression which dictate which one to envoke depending on size of
3079 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003080
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003081 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003082 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003083 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003084 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003085 cast = NoTypeInfoCStyleCastExpr(Context,
3086 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003087 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003088 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003089 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3090 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003091 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003092 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003093 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003095 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003096 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003097
John McCall183700f2009-09-21 23:43:11 +00003098 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003099 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003100 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003101 FT->getResultType(), VK_RValue,
3102 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003103
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003104 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003105 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003106 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003107 Context->getSizeType(),
3108 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003109 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3110 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3111 // For X86 it is more complicated and some kind of target specific routine
3112 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003113 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003114 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003115 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3116 llvm::APInt(IntSize, 8),
3117 Context->IntTy,
3118 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003119 BinaryOperator *lessThanExpr =
3120 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3121 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003122 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003123 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003124 new (Context) ConditionalOperator(lessThanExpr,
3125 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003126 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003127 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003128 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3129 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003130 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003131 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003132 return ReplacingStmt;
3133}
3134
Steve Naroffb29b4272008-04-14 22:03:09 +00003135Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003136 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3137 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003138
Steve Naroff934f2762007-10-24 22:48:43 +00003139 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003140 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003142 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003143 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003144}
3145
Steve Naroff621edce2009-04-29 16:37:50 +00003146// typedef struct objc_object Protocol;
3147QualType RewriteObjC::getProtocolType() {
3148 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003149 TypeSourceInfo *TInfo
3150 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003151 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003152 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003153 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003154 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003155 }
3156 return Context->getTypeDeclType(ProtocolTypeDecl);
3157}
3158
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003159/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003160/// a synthesized/forward data reference (to the protocol's metadata).
3161/// The forward references (and metadata) are generated in
3162/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003163Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003164 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3165 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003166 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003167 ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003168 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003169 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3170 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003171 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003172 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003173 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003174 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003175 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003176 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003177 ReplaceStmt(Exp, castExpr);
3178 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003179 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003180 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003182}
3183
Mike Stump1eb44332009-09-09 15:08:12 +00003184bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003185 const char *endBuf) {
3186 while (startBuf < endBuf) {
3187 if (*startBuf == '#') {
3188 // Skip whitespace.
3189 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3190 ;
3191 if (!strncmp(startBuf, "if", strlen("if")) ||
3192 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3193 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3194 !strncmp(startBuf, "define", strlen("define")) ||
3195 !strncmp(startBuf, "undef", strlen("undef")) ||
3196 !strncmp(startBuf, "else", strlen("else")) ||
3197 !strncmp(startBuf, "elif", strlen("elif")) ||
3198 !strncmp(startBuf, "endif", strlen("endif")) ||
3199 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3200 !strncmp(startBuf, "include", strlen("include")) ||
3201 !strncmp(startBuf, "import", strlen("import")) ||
3202 !strncmp(startBuf, "include_next", strlen("include_next")))
3203 return true;
3204 }
3205 startBuf++;
3206 }
3207 return false;
3208}
3209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003210/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003211/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003212void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003213 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003214 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003215 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003216 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003217 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003218 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003219 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003220 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003221 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003222 SourceLocation LocStart = CDecl->getLocStart();
3223 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003224
Steve Narofffea763e82007-11-14 19:25:57 +00003225 const char *startBuf = SM->getCharacterData(LocStart);
3226 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003228 // If no ivars and no root or if its root, directly or indirectly,
3229 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003230 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3231 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003232 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003233 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003234 return;
3235 }
Mike Stump1eb44332009-09-09 15:08:12 +00003236
3237 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003238 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003239 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003240 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003241 if (LangOpts.Microsoft)
3242 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003243
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003244 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003245 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003246 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003247 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003248 // If the buffer contains preprocessor directives, we do more fine-grained
3249 // rewrites. This is intended to fix code that looks like (which occurs in
3250 // NSURL.h, for example):
3251 //
3252 // #ifdef XYZ
3253 // @interface Foo : NSObject
3254 // #else
3255 // @interface FooBar : NSObject
3256 // #endif
3257 // {
3258 // int i;
3259 // }
3260 // @end
3261 //
3262 // This clause is segregated to avoid breaking the common case.
3263 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003264 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003265 CDecl->getClassLoc();
3266 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003267 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003268
Chris Lattnercafeb352009-02-20 18:18:36 +00003269 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003270 // advance to the end of the referenced protocols.
3271 while (endHeader < cursor && *endHeader != '>') endHeader++;
3272 endHeader++;
3273 }
3274 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003275 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003276 } else {
3277 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003278 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003279 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003280 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003281 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003282 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003283 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003284 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003285 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003286
Steve Narofffea763e82007-11-14 19:25:57 +00003287 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003288 SourceLocation OnePastCurly =
3289 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003290 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003291 }
3292 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Steve Narofffea763e82007-11-14 19:25:57 +00003294 // Now comment out any visibility specifiers.
3295 while (cursor < endBuf) {
3296 if (*cursor == '@') {
3297 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003298 // Skip whitespace.
3299 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3300 /*scan*/;
3301
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003302 // FIXME: presence of @public, etc. inside comment results in
3303 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003304 if (!strncmp(cursor, "public", strlen("public")) ||
3305 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003306 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003307 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003308 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003309 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003310 // FIXME: If there are cases where '<' is used in ivar declaration part
3311 // of user code, then scan the ivar list and use needToScanForQualifiers
3312 // for type checking.
3313 else if (*cursor == '<') {
3314 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003315 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003316 cursor = strchr(cursor, '>');
3317 cursor++;
3318 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003319 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003320 } else if (*cursor == '^') { // rewrite block specifier.
3321 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003322 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003323 }
Steve Narofffea763e82007-11-14 19:25:57 +00003324 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003325 }
Steve Narofffea763e82007-11-14 19:25:57 +00003326 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003327 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003328 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003329 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003330 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003332 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003333 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003334 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003335 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003336 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003337 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003338 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003339 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003340}
3341
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003342// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003343/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003344template<typename MethodIterator>
3345void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3346 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003347 bool IsInstanceMethod,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003348 llvm::StringRef prefix,
3349 llvm::StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003350 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003351 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003352
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003353 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003354 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003355 SEL _cmd;
3356 char *method_types;
3357 void *_imp;
3358 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003359 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003360 Result += "\nstruct _objc_method {\n";
3361 Result += "\tSEL _cmd;\n";
3362 Result += "\tchar *method_types;\n";
3363 Result += "\tvoid *_imp;\n";
3364 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003365
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003366 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003367 }
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003369 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003370
Steve Naroff946a6932008-03-11 00:12:29 +00003371 /* struct {
3372 struct _objc_method_list *next_method;
3373 int method_count;
3374 struct _objc_method method_list[];
3375 }
3376 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003377 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003378 Result += "\nstatic struct {\n";
3379 Result += "\tstruct _objc_method_list *next_method;\n";
3380 Result += "\tint method_count;\n";
3381 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003382 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003383 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003384 Result += prefix;
3385 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3386 Result += "_METHODS_";
3387 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003388 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003389 Result += IsInstanceMethod ? "inst" : "cls";
3390 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003391 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003392
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003393 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003394 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003395 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003396 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003397 Result += "\", \"";
3398 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003399 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003400 Result += MethodInternalNames[*MethodBegin];
3401 Result += "}\n";
3402 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3403 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003404 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003405 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003406 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003407 Result += "\", \"";
3408 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003409 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003410 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003411 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003412 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003413 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003414}
3415
Steve Naroff621edce2009-04-29 16:37:50 +00003416/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003417void RewriteObjC::
Daniel Dunbar4087f272010-08-17 22:39:59 +00003418RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, llvm::StringRef prefix,
3419 llvm::StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003420 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003421
3422 // Output struct protocol_methods holder of method selector and type.
3423 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3424 /* struct protocol_methods {
3425 SEL _cmd;
3426 char *method_types;
3427 }
3428 */
3429 Result += "\nstruct _protocol_methods {\n";
3430 Result += "\tstruct objc_selector *_cmd;\n";
3431 Result += "\tchar *method_types;\n";
3432 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Steve Naroff621edce2009-04-29 16:37:50 +00003434 objc_protocol_methods = true;
3435 }
3436 // Do not synthesize the protocol more than once.
3437 if (ObjCSynthesizedProtocols.count(PDecl))
3438 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003440 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3441 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3442 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003443 /* struct _objc_protocol_method_list {
3444 int protocol_method_count;
3445 struct protocol_methods protocols[];
3446 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003447 */
Steve Naroff621edce2009-04-29 16:37:50 +00003448 Result += "\nstatic struct {\n";
3449 Result += "\tint protocol_method_count;\n";
3450 Result += "\tstruct _protocol_methods protocol_methods[";
3451 Result += utostr(NumMethods);
3452 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3453 Result += PDecl->getNameAsString();
3454 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3455 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003456
Steve Naroff621edce2009-04-29 16:37:50 +00003457 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003458 for (ObjCProtocolDecl::instmeth_iterator
3459 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003460 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003461 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003462 Result += "\t ,{{(struct objc_selector *)\"";
3463 else
3464 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003465 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003466 std::string MethodTypeString;
3467 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3468 Result += "\", \"";
3469 Result += MethodTypeString;
3470 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003471 }
Steve Naroff621edce2009-04-29 16:37:50 +00003472 Result += "\t }\n};\n";
3473 }
Mike Stump1eb44332009-09-09 15:08:12 +00003474
Steve Naroff621edce2009-04-29 16:37:50 +00003475 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003476 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3477 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003478 if (NumMethods > 0) {
3479 /* struct _objc_protocol_method_list {
3480 int protocol_method_count;
3481 struct protocol_methods protocols[];
3482 }
3483 */
3484 Result += "\nstatic struct {\n";
3485 Result += "\tint protocol_method_count;\n";
3486 Result += "\tstruct _protocol_methods protocol_methods[";
3487 Result += utostr(NumMethods);
3488 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3489 Result += PDecl->getNameAsString();
3490 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3491 "{\n\t";
3492 Result += utostr(NumMethods);
3493 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003494
Steve Naroff621edce2009-04-29 16:37:50 +00003495 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003496 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003497 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003498 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003499 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003500 Result += "\t ,{{(struct objc_selector *)\"";
3501 else
3502 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003503 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003504 std::string MethodTypeString;
3505 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3506 Result += "\", \"";
3507 Result += MethodTypeString;
3508 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003509 }
Steve Naroff621edce2009-04-29 16:37:50 +00003510 Result += "\t }\n};\n";
3511 }
3512
3513 // Output:
3514 /* struct _objc_protocol {
3515 // Objective-C 1.0 extensions
3516 struct _objc_protocol_extension *isa;
3517 char *protocol_name;
3518 struct _objc_protocol **protocol_list;
3519 struct _objc_protocol_method_list *instance_methods;
3520 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003521 };
Steve Naroff621edce2009-04-29 16:37:50 +00003522 */
3523 static bool objc_protocol = false;
3524 if (!objc_protocol) {
3525 Result += "\nstruct _objc_protocol {\n";
3526 Result += "\tstruct _objc_protocol_extension *isa;\n";
3527 Result += "\tchar *protocol_name;\n";
3528 Result += "\tstruct _objc_protocol **protocol_list;\n";
3529 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3530 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003531 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Steve Naroff621edce2009-04-29 16:37:50 +00003533 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003534 }
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Steve Naroff621edce2009-04-29 16:37:50 +00003536 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3537 Result += PDecl->getNameAsString();
3538 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3539 "{\n\t0, \"";
3540 Result += PDecl->getNameAsString();
3541 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003543 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3544 Result += PDecl->getNameAsString();
3545 Result += ", ";
3546 }
3547 else
3548 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003549 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003550 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3551 Result += PDecl->getNameAsString();
3552 Result += "\n";
3553 }
3554 else
3555 Result += "0\n";
3556 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Steve Naroff621edce2009-04-29 16:37:50 +00003558 // Mark this protocol as having been generated.
3559 if (!ObjCSynthesizedProtocols.insert(PDecl))
3560 assert(false && "protocol already synthesized");
3561
3562}
3563
3564void RewriteObjC::
3565RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Daniel Dunbar4087f272010-08-17 22:39:59 +00003566 llvm::StringRef prefix, llvm::StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003567 std::string &Result) {
3568 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003569
Steve Naroff621edce2009-04-29 16:37:50 +00003570 for (unsigned i = 0; i != Protocols.size(); i++)
3571 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3572
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003573 // Output the top lovel protocol meta-data for the class.
3574 /* struct _objc_protocol_list {
3575 struct _objc_protocol_list *next;
3576 int protocol_count;
3577 struct _objc_protocol *class_protocols[];
3578 }
3579 */
3580 Result += "\nstatic struct {\n";
3581 Result += "\tstruct _objc_protocol_list *next;\n";
3582 Result += "\tint protocol_count;\n";
3583 Result += "\tstruct _objc_protocol *class_protocols[";
3584 Result += utostr(Protocols.size());
3585 Result += "];\n} _OBJC_";
3586 Result += prefix;
3587 Result += "_PROTOCOLS_";
3588 Result += ClassName;
3589 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3590 "{\n\t0, ";
3591 Result += utostr(Protocols.size());
3592 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003594 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003595 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003596 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003598 for (unsigned i = 1; i != Protocols.size(); i++) {
3599 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003600 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003601 Result += "\n";
3602 }
3603 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003604}
3605
Steve Naroff621edce2009-04-29 16:37:50 +00003606
Mike Stump1eb44332009-09-09 15:08:12 +00003607/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003608/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003609void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003610 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003611 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003612 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003613 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003614 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003615 CDecl = CDecl->getNextClassCategory())
3616 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3617 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003619 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003620 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003621 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003623 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003624 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003625 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003626
3627 // If any of our property implementations have associated getters or
3628 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003629 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3630 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003631 Prop != PropEnd; ++Prop) {
3632 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3633 continue;
3634 if (!(*Prop)->getPropertyIvarDecl())
3635 continue;
3636 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3637 if (!PD)
3638 continue;
3639 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3640 InstanceMethods.push_back(Getter);
3641 if (PD->isReadOnly())
3642 continue;
3643 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3644 InstanceMethods.push_back(Setter);
3645 }
3646 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003647 true, "CATEGORY_", FullCategoryName.c_str(),
3648 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003650 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003651 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003652 false, "CATEGORY_", FullCategoryName.c_str(),
3653 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003655 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003656 // Null CDecl is case of a category implementation with no category interface
3657 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003658 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003659 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003660 /* struct _objc_category {
3661 char *category_name;
3662 char *class_name;
3663 struct _objc_method_list *instance_methods;
3664 struct _objc_method_list *class_methods;
3665 struct _objc_protocol_list *protocols;
3666 // Objective-C 1.0 extensions
3667 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003668 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003669 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003670 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003671 */
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003673 static bool objc_category = false;
3674 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003675 Result += "\nstruct _objc_category {\n";
3676 Result += "\tchar *category_name;\n";
3677 Result += "\tchar *class_name;\n";
3678 Result += "\tstruct _objc_method_list *instance_methods;\n";
3679 Result += "\tstruct _objc_method_list *class_methods;\n";
3680 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003681 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003682 Result += "\tstruct _objc_property_list *instance_properties;\n";
3683 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003684 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003685 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3687 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003688 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003689 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003691 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003692 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003694 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003695 Result += "\t, (struct _objc_method_list *)"
3696 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3697 Result += FullCategoryName;
3698 Result += "\n";
3699 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003700 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003701 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003702 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003703 Result += "\t, (struct _objc_method_list *)"
3704 "&_OBJC_CATEGORY_CLASS_METHODS_";
3705 Result += FullCategoryName;
3706 Result += "\n";
3707 }
3708 else
3709 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Chris Lattnercafeb352009-02-20 18:18:36 +00003711 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003712 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003713 Result += FullCategoryName;
3714 Result += "\n";
3715 }
3716 else
3717 Result += "\t, 0\n";
3718 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003719}
3720
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003721/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3722/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003723void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003724 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003725 if (ivar->isBitField()) {
3726 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3727 // place all bitfields at offset 0.
3728 Result += "0";
3729 } else {
3730 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003731 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003732 if (LangOpts.Microsoft)
3733 Result += "_IMPL";
3734 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003735 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003736 Result += ")";
3737 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003738}
3739
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003740//===----------------------------------------------------------------------===//
3741// Meta Data Emission
3742//===----------------------------------------------------------------------===//
3743
Steve Naroffb29b4272008-04-14 22:03:09 +00003744void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003745 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003746 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003748 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003749 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003750 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003751 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003752 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003753 }
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Chris Lattnerbe6df082007-12-12 07:56:42 +00003755 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003756 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003757 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003758 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003759 if (NumIvars > 0) {
3760 static bool objc_ivar = false;
3761 if (!objc_ivar) {
3762 /* struct _objc_ivar {
3763 char *ivar_name;
3764 char *ivar_type;
3765 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003766 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003767 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003768 Result += "\nstruct _objc_ivar {\n";
3769 Result += "\tchar *ivar_name;\n";
3770 Result += "\tchar *ivar_type;\n";
3771 Result += "\tint ivar_offset;\n";
3772 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003774 objc_ivar = true;
3775 }
3776
Steve Naroff946a6932008-03-11 00:12:29 +00003777 /* struct {
3778 int ivar_count;
3779 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003780 };
Steve Naroff946a6932008-03-11 00:12:29 +00003781 */
Mike Stump1eb44332009-09-09 15:08:12 +00003782 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003783 Result += "\tint ivar_count;\n";
3784 Result += "\tstruct _objc_ivar ivar_list[";
3785 Result += utostr(NumIvars);
3786 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003787 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003788 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003789 "{\n\t";
3790 Result += utostr(NumIvars);
3791 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003793 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003794 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003795 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003796 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003797 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003798 IV != IVEnd; ++IV)
3799 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003800 IVI = IDecl->ivar_begin();
3801 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003802 } else {
3803 IVI = CDecl->ivar_begin();
3804 IVE = CDecl->ivar_end();
3805 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003806 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003807 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003808 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003809 std::string TmpString, StrEncoding;
3810 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3811 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003812 Result += StrEncoding;
3813 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003814 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003815 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003816 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003817 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003818 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003819 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003820 std::string TmpString, StrEncoding;
3821 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3822 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003823 Result += StrEncoding;
3824 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003825 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003826 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003827 }
Mike Stump1eb44332009-09-09 15:08:12 +00003828
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003829 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003830 }
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003832 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003833 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003834 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003835
3836 // If any of our property implementations have associated getters or
3837 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003838 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3839 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003840 Prop != PropEnd; ++Prop) {
3841 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3842 continue;
3843 if (!(*Prop)->getPropertyIvarDecl())
3844 continue;
3845 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3846 if (!PD)
3847 continue;
3848 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003849 if (!Getter->isDefined())
3850 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003851 if (PD->isReadOnly())
3852 continue;
3853 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003854 if (!Setter->isDefined())
3855 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003856 }
3857 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003858 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003859
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003860 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003861 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003862 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003864 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003865 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003866 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003867
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003868 // Declaration of class/meta-class metadata
3869 /* struct _objc_class {
3870 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003871 const char *super_class_name;
3872 char *name;
3873 long version;
3874 long info;
3875 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003876 struct _objc_ivar_list *ivars;
3877 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003878 struct objc_cache *cache;
3879 struct objc_protocol_list *protocols;
3880 const char *ivar_layout;
3881 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003882 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003883 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003884 static bool objc_class = false;
3885 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003886 Result += "\nstruct _objc_class {\n";
3887 Result += "\tstruct _objc_class *isa;\n";
3888 Result += "\tconst char *super_class_name;\n";
3889 Result += "\tchar *name;\n";
3890 Result += "\tlong version;\n";
3891 Result += "\tlong info;\n";
3892 Result += "\tlong instance_size;\n";
3893 Result += "\tstruct _objc_ivar_list *ivars;\n";
3894 Result += "\tstruct _objc_method_list *methods;\n";
3895 Result += "\tstruct objc_cache *cache;\n";
3896 Result += "\tstruct _objc_protocol_list *protocols;\n";
3897 Result += "\tconst char *ivar_layout;\n";
3898 Result += "\tstruct _objc_class_ext *ext;\n";
3899 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003900 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003903 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003904 ObjCInterfaceDecl *RootClass = 0;
3905 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003906 while (SuperClass) {
3907 RootClass = SuperClass;
3908 SuperClass = SuperClass->getSuperClass();
3909 }
3910 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003911
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003912 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003913 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003914 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003916 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003917 Result += "\"";
3918
3919 if (SuperClass) {
3920 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003921 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003922 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003923 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003924 Result += "\"";
3925 }
3926 else {
3927 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003928 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003929 Result += "\"";
3930 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003931 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003932 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003933 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003934 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003935 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003936 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003937 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003939 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003941 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003942 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003943 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003944 Result += ",0,0\n";
3945 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003946 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 Result += "\t,0,0,0,0\n";
3948 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003950 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003951 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003952 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003953 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003955 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003956 if (SuperClass) {
3957 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003958 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003959 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003960 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 Result += "\"";
3962 }
3963 else {
3964 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003965 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003966 Result += "\"";
3967 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003968 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003969 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003970 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003971 Result += ",0";
3972 else {
3973 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003974 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003975 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003976 if (LangOpts.Microsoft)
3977 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003978 Result += ")";
3979 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003980 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003981 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003982 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 Result += "\n\t";
3984 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003985 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003986 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003987 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003988 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003989 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003990 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003991 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003992 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003993 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003994 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003995 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003996 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003997 Result += ", 0,0\n";
3998 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003999 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 Result += ",0,0,0\n";
4001 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004002}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004003
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004004/// RewriteImplementations - This routine rewrites all method implementations
4005/// and emits meta-data.
4006
Steve Narofface66252008-11-13 20:07:04 +00004007void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004008 int ClsDefCount = ClassImplementation.size();
4009 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004010
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004011 // Rewrite implemented methods
4012 for (int i = 0; i < ClsDefCount; i++)
4013 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004015 for (int i = 0; i < CatDefCount; i++)
4016 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004017}
Mike Stump1eb44332009-09-09 15:08:12 +00004018
Steve Narofface66252008-11-13 20:07:04 +00004019void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4020 int ClsDefCount = ClassImplementation.size();
4021 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004022
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004023 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004024 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004025 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004027 // For each implemented category, write out all its meta data.
4028 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004029 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004030
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004031 // Write objc_symtab metadata
4032 /*
4033 struct _objc_symtab
4034 {
4035 long sel_ref_cnt;
4036 SEL *refs;
4037 short cls_def_cnt;
4038 short cat_def_cnt;
4039 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004040 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004041 */
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004043 Result += "\nstruct _objc_symtab {\n";
4044 Result += "\tlong sel_ref_cnt;\n";
4045 Result += "\tSEL *refs;\n";
4046 Result += "\tshort cls_def_cnt;\n";
4047 Result += "\tshort cat_def_cnt;\n";
4048 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4049 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004052 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004053 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 + ", " + utostr(CatDefCount) + "\n";
4055 for (int i = 0; i < ClsDefCount; i++) {
4056 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 Result += "\n";
4059 }
Mike Stump1eb44332009-09-09 15:08:12 +00004060
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 for (int i = 0; i < CatDefCount; i++) {
4062 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004063 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004065 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004066 Result += "\n";
4067 }
Mike Stump1eb44332009-09-09 15:08:12 +00004068
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004069 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004070
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004071 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004073 /*
4074 struct _objc_module {
4075 long version;
4076 long size;
4077 const char *name;
4078 struct _objc_symtab *symtab;
4079 }
4080 */
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004082 Result += "\nstruct _objc_module {\n";
4083 Result += "\tlong version;\n";
4084 Result += "\tlong size;\n";
4085 Result += "\tconst char *name;\n";
4086 Result += "\tstruct _objc_symtab *symtab;\n";
4087 Result += "};\n\n";
4088 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004089 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004090 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004091 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004092 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004093
4094 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004095 if (ProtocolExprDecls.size()) {
4096 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4097 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004098 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004099 E = ProtocolExprDecls.end(); I != E; ++I) {
4100 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4101 Result += (*I)->getNameAsString();
4102 Result += " = &_OBJC_PROTOCOL_";
4103 Result += (*I)->getNameAsString();
4104 Result += ";\n";
4105 }
4106 Result += "#pragma data_seg(pop)\n\n";
4107 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004108 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004109 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004110 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4111 Result += "&_OBJC_MODULES;\n";
4112 Result += "#pragma data_seg(pop)\n\n";
4113 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004114}
Chris Lattner311ff022007-10-16 22:36:42 +00004115
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004116void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4117 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004118 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004119 assert(BlockByRefDeclNo.count(VD) &&
4120 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004121 if (def)
4122 ResultStr += "struct ";
4123 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004124 "_" + utostr(BlockByRefDeclNo[VD]) ;
4125}
4126
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004127static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4128 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4129 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4130 return false;
4131}
4132
Steve Naroff54055232008-10-27 17:20:55 +00004133std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004134 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004135 std::string Tag) {
4136 const FunctionType *AFT = CE->getFunctionType();
4137 QualType RT = AFT->getResultType();
4138 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004139 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004140 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004141
Steve Naroff54055232008-10-27 17:20:55 +00004142 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Douglas Gregor72564e72009-02-26 23:50:07 +00004144 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004145 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004146 // block (to reference imported block decl refs).
4147 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004148 } else if (BD->param_empty()) {
4149 S += "(" + StructRef + " *__cself)";
4150 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004151 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004152 assert(FT && "SynthesizeBlockFunc: No function proto");
4153 S += '(';
4154 // first add the implicit argument.
4155 S += StructRef + " *__cself, ";
4156 std::string ParamStr;
4157 for (BlockDecl::param_iterator AI = BD->param_begin(),
4158 E = BD->param_end(); AI != E; ++AI) {
4159 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004160 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004161 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004162 if (convertBlockPointerToFunctionPointer(QT))
4163 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004164 else
4165 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004166 S += ParamStr;
4167 }
4168 if (FT->isVariadic()) {
4169 if (!BD->param_empty()) S += ", ";
4170 S += "...";
4171 }
4172 S += ')';
4173 }
4174 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004175
Steve Naroff54055232008-10-27 17:20:55 +00004176 // Create local declarations to avoid rewriting all closure decl ref exprs.
4177 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004178 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004179 E = BlockByRefDecls.end(); I != E; ++I) {
4180 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004181 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004182 std::string TypeString;
4183 RewriteByRefString(TypeString, Name, (*I));
4184 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004185 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004186 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004187 }
Steve Naroff54055232008-10-27 17:20:55 +00004188 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004189 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004190 E = BlockByCopyDecls.end(); I != E; ++I) {
4191 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004192 // Handle nested closure invocation. For example:
4193 //
4194 // void (^myImportedClosure)(void);
4195 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004196 //
Steve Naroff54055232008-10-27 17:20:55 +00004197 // void (^anotherClosure)(void);
4198 // anotherClosure = ^(void) {
4199 // myImportedClosure(); // import and invoke the closure
4200 // };
4201 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004202 if (isTopLevelBlockPointerType((*I)->getType())) {
4203 RewriteBlockPointerTypeVariable(S, (*I));
4204 S += " = (";
4205 RewriteBlockPointerType(S, (*I)->getType());
4206 S += ")";
4207 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4208 }
4209 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004210 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004211 QualType QT = (*I)->getType();
4212 if (HasLocalVariableExternalStorage(*I))
4213 QT = Context->getPointerType(QT);
4214 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004215 S += Name + " = __cself->" +
4216 (*I)->getNameAsString() + "; // bound by copy\n";
4217 }
Steve Naroff54055232008-10-27 17:20:55 +00004218 }
4219 std::string RewrittenStr = RewrittenBlockExprs[CE];
4220 const char *cstr = RewrittenStr.c_str();
4221 while (*cstr++ != '{') ;
4222 S += cstr;
4223 S += "\n";
4224 return S;
4225}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004226
Steve Naroff54055232008-10-27 17:20:55 +00004227std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004228 llvm::StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004229 std::string Tag) {
4230 std::string StructRef = "struct " + Tag;
4231 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004232
Steve Naroff54055232008-10-27 17:20:55 +00004233 S += funcName;
4234 S += "_block_copy_" + utostr(i);
4235 S += "(" + StructRef;
4236 S += "*dst, " + StructRef;
4237 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004238 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004239 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004240 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004241 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004242 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004243 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004244 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004245 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004246 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004247 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004248 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004249 S += "}\n";
4250
Steve Naroff54055232008-10-27 17:20:55 +00004251 S += "\nstatic void __";
4252 S += funcName;
4253 S += "_block_dispose_" + utostr(i);
4254 S += "(" + StructRef;
4255 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004256 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004257 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004258 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004259 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004260 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004261 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004262 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004263 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004264 }
Mike Stump1eb44332009-09-09 15:08:12 +00004265 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004266 return S;
4267}
4268
Steve Naroff01aec112009-12-06 21:14:13 +00004269std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4270 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004271 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004272 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Steve Naroff54055232008-10-27 17:20:55 +00004274 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004275 S += " struct " + Desc;
4276 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Steve Naroff01aec112009-12-06 21:14:13 +00004278 Constructor += "(void *fp, "; // Invoke function pointer.
4279 Constructor += "struct " + Desc; // Descriptor pointer.
4280 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004281
Steve Naroff54055232008-10-27 17:20:55 +00004282 if (BlockDeclRefs.size()) {
4283 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004284 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004285 E = BlockByCopyDecls.end(); I != E; ++I) {
4286 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004287 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004288 std::string ArgName = "_" + FieldName;
4289 // Handle nested closure invocation. For example:
4290 //
4291 // void (^myImportedBlock)(void);
4292 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004293 //
Steve Naroff54055232008-10-27 17:20:55 +00004294 // void (^anotherBlock)(void);
4295 // anotherBlock = ^(void) {
4296 // myImportedBlock(); // import and invoke the closure
4297 // };
4298 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004299 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004300 S += "struct __block_impl *";
4301 Constructor += ", void *" + ArgName;
4302 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004303 QualType QT = (*I)->getType();
4304 if (HasLocalVariableExternalStorage(*I))
4305 QT = Context->getPointerType(QT);
4306 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4307 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004308 Constructor += ", " + ArgName;
4309 }
4310 S += FieldName + ";\n";
4311 }
4312 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004313 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004314 E = BlockByRefDecls.end(); I != E; ++I) {
4315 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004316 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004317 std::string ArgName = "_" + FieldName;
4318 // Handle nested closure invocation. For example:
4319 //
4320 // void (^myImportedBlock)(void);
4321 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004322 //
Steve Naroff54055232008-10-27 17:20:55 +00004323 // void (^anotherBlock)(void);
4324 // anotherBlock = ^(void) {
4325 // myImportedBlock(); // import and invoke the closure
4326 // };
4327 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004328 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004329 S += "struct __block_impl *";
4330 Constructor += ", void *" + ArgName;
4331 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004332 std::string TypeString;
4333 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004334 TypeString += " *";
4335 FieldName = TypeString + FieldName;
4336 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004337 Constructor += ", " + ArgName;
4338 }
4339 S += FieldName + "; // by ref\n";
4340 }
4341 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004342 Constructor += ", int flags=0)";
4343 // Initialize all "by copy" arguments.
4344 bool firsTime = true;
4345 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4346 E = BlockByCopyDecls.end(); I != E; ++I) {
4347 std::string Name = (*I)->getNameAsString();
4348 if (firsTime) {
4349 Constructor += " : ";
4350 firsTime = false;
4351 }
4352 else
4353 Constructor += ", ";
4354 if (isTopLevelBlockPointerType((*I)->getType()))
4355 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4356 else
4357 Constructor += Name + "(_" + Name + ")";
4358 }
4359 // Initialize all "by ref" arguments.
4360 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4361 E = BlockByRefDecls.end(); I != E; ++I) {
4362 std::string Name = (*I)->getNameAsString();
4363 if (firsTime) {
4364 Constructor += " : ";
4365 firsTime = false;
4366 }
4367 else
4368 Constructor += ", ";
4369 if (isTopLevelBlockPointerType((*I)->getType()))
4370 Constructor += Name + "((struct __block_impl *)_"
4371 + Name + "->__forwarding)";
4372 else
4373 Constructor += Name + "(_" + Name + "->__forwarding)";
4374 }
4375
4376 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004377 if (GlobalVarDecl)
4378 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4379 else
4380 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004381 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Steve Naroff01aec112009-12-06 21:14:13 +00004383 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004384 } else {
4385 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004386 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004387 if (GlobalVarDecl)
4388 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4389 else
4390 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004391 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4392 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004393 }
4394 Constructor += " ";
4395 Constructor += "}\n";
4396 S += Constructor;
4397 S += "};\n";
4398 return S;
4399}
4400
Steve Naroff01aec112009-12-06 21:14:13 +00004401std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4402 std::string ImplTag, int i,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004403 llvm::StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004404 unsigned hasCopy) {
4405 std::string S = "\nstatic struct " + DescTag;
4406
4407 S += " {\n unsigned long reserved;\n";
4408 S += " unsigned long Block_size;\n";
4409 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004410 S += " void (*copy)(struct ";
4411 S += ImplTag; S += "*, struct ";
4412 S += ImplTag; S += "*);\n";
4413
4414 S += " void (*dispose)(struct ";
4415 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004416 }
4417 S += "} ";
4418
4419 S += DescTag + "_DATA = { 0, sizeof(struct ";
4420 S += ImplTag + ")";
4421 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004422 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4423 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004424 }
4425 S += "};\n";
4426 return S;
4427}
4428
Steve Naroff54055232008-10-27 17:20:55 +00004429void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Daniel Dunbar4087f272010-08-17 22:39:59 +00004430 llvm::StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004431 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004432 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004433 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004434 bool RewriteSC = (GlobalVarDecl &&
4435 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004436 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004437 GlobalVarDecl->getType().getCVRQualifiers());
4438 if (RewriteSC) {
4439 std::string SC(" void __");
4440 SC += GlobalVarDecl->getNameAsString();
4441 SC += "() {}";
4442 InsertText(FunLocStart, SC);
4443 }
4444
Steve Naroff54055232008-10-27 17:20:55 +00004445 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004446 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4447 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004448 // Need to copy-in the inner copied-in variables not actually used in this
4449 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004450 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4451 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4452 ValueDecl *VD = Exp->getDecl();
4453 BlockDeclRefs.push_back(Exp);
4454 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4455 BlockByCopyDeclsPtrSet.insert(VD);
4456 BlockByCopyDecls.push_back(VD);
4457 }
4458 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4459 BlockByRefDeclsPtrSet.insert(VD);
4460 BlockByRefDecls.push_back(VD);
4461 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004462 // imported objects in the inner blocks not used in the outer
4463 // blocks must be copied/disposed in the outer block as well.
4464 if (Exp->isByRef() ||
4465 VD->getType()->isObjCObjectPointerType() ||
4466 VD->getType()->isBlockPointerType())
4467 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004468 }
Steve Naroff54055232008-10-27 17:20:55 +00004469
Daniel Dunbar4087f272010-08-17 22:39:59 +00004470 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4471 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004472
Steve Naroff01aec112009-12-06 21:14:13 +00004473 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004474
Benjamin Kramerd999b372010-02-14 14:14:16 +00004475 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004476
Steve Naroff01aec112009-12-06 21:14:13 +00004477 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004478
Benjamin Kramerd999b372010-02-14 14:14:16 +00004479 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004480
4481 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004482 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004483 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004484 }
Steve Naroff01aec112009-12-06 21:14:13 +00004485 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4486 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004487 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004488
Steve Naroff54055232008-10-27 17:20:55 +00004489 BlockDeclRefs.clear();
4490 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004491 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004492 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004493 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004494 ImportedBlockDecls.clear();
4495 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004496 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004497 // Must insert any 'const/volatile/static here. Since it has been
4498 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004499 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004500 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004501 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004502 if (GlobalVarDecl->getType().isConstQualified())
4503 SC += "const ";
4504 if (GlobalVarDecl->getType().isVolatileQualified())
4505 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004506 if (GlobalVarDecl->getType().isRestrictQualified())
4507 SC += "restrict ";
4508 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004509 }
4510
Steve Naroff54055232008-10-27 17:20:55 +00004511 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004512 InnerDeclRefsCount.clear();
4513 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004514 RewrittenBlockExprs.clear();
4515}
4516
4517void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4518 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004519 llvm::StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Steve Naroff54055232008-10-27 17:20:55 +00004521 SynthesizeBlockLiterals(FunLocStart, FuncName);
4522}
4523
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004524static void BuildUniqueMethodName(std::string &Name,
4525 ObjCMethodDecl *MD) {
4526 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004527 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004528 Name += "__" + MD->getSelector().getAsString();
4529 // Convert colons to underscores.
4530 std::string::size_type loc = 0;
4531 while ((loc = Name.find(":", loc)) != std::string::npos)
4532 Name.replace(loc, 1, "_");
4533}
4534
Steve Naroff54055232008-10-27 17:20:55 +00004535void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004536 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4537 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004538 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004539 std::string FuncName;
4540 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004541 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004542}
4543
4544void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004545 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004546 if (*CI) {
4547 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4548 GetBlockDeclRefExprs(CBE->getBody());
4549 else
4550 GetBlockDeclRefExprs(*CI);
4551 }
4552 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004553 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004554 // FIXME: Handle enums.
4555 if (!isa<FunctionDecl>(CDRE->getDecl()))
4556 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004557 }
4558 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4559 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4560 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004561 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4562 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004563 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004564 BlockDeclRefs.push_back(BDRE);
4565 }
4566
Steve Naroff54055232008-10-27 17:20:55 +00004567 return;
4568}
4569
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004570void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4571 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004572 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004573 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004574 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004575 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4576 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004577 GetInnerBlockDeclRefExprs(CBE->getBody(),
4578 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004579 InnerContexts);
4580 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004581 else
4582 GetInnerBlockDeclRefExprs(*CI,
4583 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004584 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004585
4586 }
4587 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004588 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004590 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004591 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004592 }
4593 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4594 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4595 if (Var->isFunctionOrMethodVarDecl())
4596 ImportedLocalExternalDecls.insert(Var);
4597 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004598
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004599 return;
4600}
4601
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004602/// convertFunctionTypeOfBlocks - This routine converts a function type
4603/// whose result type may be a block pointer or whose argument type(s)
4604/// might be block pointers to an equivalent funtion type replacing
4605/// all block pointers to function pointers.
4606QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4607 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4608 // FTP will be null for closures that don't take arguments.
4609 // Generate a funky cast.
4610 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004611 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004612 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004613
4614 if (FTP) {
4615 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4616 E = FTP->arg_type_end(); I && (I != E); ++I) {
4617 QualType t = *I;
4618 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004619 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004620 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004621 ArgTypes.push_back(t);
4622 }
4623 }
4624 QualType FuncType;
4625 // FIXME. Does this work if block takes no argument but has a return type
4626 // which is of block type?
4627 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004628 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004629 else FuncType = QualType(FT, 0);
4630 return FuncType;
4631}
4632
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004633Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004634 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004635 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004636
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004637 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004638 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004639 } else if (const BlockDeclRefExpr *CDRE =
4640 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004641 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004642 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004643 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004644 }
4645 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4646 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4647 }
4648 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4649 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4650 else if (const ConditionalOperator *CEXPR =
4651 dyn_cast<ConditionalOperator>(BlockExp)) {
4652 Expr *LHSExp = CEXPR->getLHS();
4653 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4654 Expr *RHSExp = CEXPR->getRHS();
4655 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4656 Expr *CONDExp = CEXPR->getCond();
4657 ConditionalOperator *CondExpr =
4658 new (Context) ConditionalOperator(CONDExp,
4659 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004660 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004661 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004662 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004663 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4664 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004665 } else {
4666 assert(1 && "RewriteBlockClass: Bad type");
4667 }
4668 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004669 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004670 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004671 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004672 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004673
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004674 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004675 SourceLocation(),
4676 &Context->Idents.get("__block_impl"));
4677 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004678
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004679 // Generate a funky cast.
4680 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004682 // Push the block argument type.
4683 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004684 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004685 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004686 E = FTP->arg_type_end(); I && (I != E); ++I) {
4687 QualType t = *I;
4688 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004689 if (!convertBlockPointerToFunctionPointer(t))
4690 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 ArgTypes.push_back(t);
4692 }
Steve Naroff54055232008-10-27 17:20:55 +00004693 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004694 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004695 QualType PtrToFuncCastType
4696 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004698 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004699
John McCall9d125032010-01-15 18:39:57 +00004700 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004701 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004702 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004703 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004704 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4705 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004706 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Douglas Gregor44b43212008-12-11 16:49:14 +00004708 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004709 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004710 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004711 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004712 FD->getType(), VK_LValue,
4713 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004715
John McCall9d125032010-01-15 18:39:57 +00004716 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004717 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004718 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004719
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004720 llvm::SmallVector<Expr*, 8> BlkExprs;
4721 // Add the implicit argument.
4722 BlkExprs.push_back(BlkCast);
4723 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004724 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004725 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004726 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004727 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004728 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4729 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004730 Exp->getType(), VK_RValue,
4731 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004732 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004733}
4734
Steve Naroff621edce2009-04-29 16:37:50 +00004735// We need to return the rewritten expression to handle cases where the
4736// BlockDeclRefExpr is embedded in another expression being rewritten.
4737// For example:
4738//
4739// int main() {
4740// __block Foo *f;
4741// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004742//
Steve Naroff621edce2009-04-29 16:37:50 +00004743// void (^myblock)() = ^() {
4744// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4745// i = 77;
4746// };
4747//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004748Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004749 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004750 // for each DeclRefExp where BYREFVAR is name of the variable.
4751 ValueDecl *VD;
4752 bool isArrow = true;
4753 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4754 VD = BDRE->getDecl();
4755 else {
4756 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4757 isArrow = false;
4758 }
4759
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004760 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4761 &Context->Idents.get("__forwarding"),
4762 Context->VoidPtrTy, 0,
4763 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004764 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4765 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004766 FD->getType(), VK_LValue,
4767 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004768
Daniel Dunbar4087f272010-08-17 22:39:59 +00004769 llvm::StringRef Name = VD->getName();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004770 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4771 &Context->Idents.get(Name),
4772 Context->VoidPtrTy, 0,
4773 /*BitWidth=*/0, /*Mutable=*/true);
4774 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004775 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004776
4777
4778
Steve Naroffdf8570d2009-02-02 17:19:26 +00004779 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004780 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4781 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004782 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004783 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004784}
4785
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004786// Rewrites the imported local variable V with external storage
4787// (static, extern, etc.) as *V
4788//
4789Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4790 ValueDecl *VD = DRE->getDecl();
4791 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4792 if (!ImportedLocalExternalDecls.count(Var))
4793 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004794 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4795 VK_LValue, OK_Ordinary,
4796 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004797 // Need parens to enforce precedence.
4798 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4799 Exp);
4800 ReplaceStmt(DRE, PE);
4801 return PE;
4802}
4803
Steve Naroffb2f9e512008-11-03 23:29:32 +00004804void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4805 SourceLocation LocStart = CE->getLParenLoc();
4806 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004807
4808 // Need to avoid trying to rewrite synthesized casts.
4809 if (LocStart.isInvalid())
4810 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004811 // Need to avoid trying to rewrite casts contained in macros.
4812 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4813 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004814
Steve Naroff54055232008-10-27 17:20:55 +00004815 const char *startBuf = SM->getCharacterData(LocStart);
4816 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004817 QualType QT = CE->getType();
4818 const Type* TypePtr = QT->getAs<Type>();
4819 if (isa<TypeOfExprType>(TypePtr)) {
4820 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4821 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4822 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004823 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004824 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004825 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004826 return;
4827 }
Steve Naroff54055232008-10-27 17:20:55 +00004828 // advance the location to startArgList.
4829 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004830
Steve Naroff54055232008-10-27 17:20:55 +00004831 while (*argPtr++ && (argPtr < endBuf)) {
4832 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004833 case '^':
4834 // Replace the '^' with '*'.
4835 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004836 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004837 break;
Steve Naroff54055232008-10-27 17:20:55 +00004838 }
4839 }
4840 return;
4841}
4842
4843void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4844 SourceLocation DeclLoc = FD->getLocation();
4845 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Steve Naroff54055232008-10-27 17:20:55 +00004847 // We have 1 or more arguments that have closure pointers.
4848 const char *startBuf = SM->getCharacterData(DeclLoc);
4849 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004850
Steve Naroff54055232008-10-27 17:20:55 +00004851 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004852
Steve Naroff54055232008-10-27 17:20:55 +00004853 parenCount++;
4854 // advance the location to startArgList.
4855 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4856 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Steve Naroff54055232008-10-27 17:20:55 +00004858 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Steve Naroff54055232008-10-27 17:20:55 +00004860 while (*argPtr++ && parenCount) {
4861 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004862 case '^':
4863 // Replace the '^' with '*'.
4864 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004865 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004866 break;
4867 case '(':
4868 parenCount++;
4869 break;
4870 case ')':
4871 parenCount--;
4872 break;
Steve Naroff54055232008-10-27 17:20:55 +00004873 }
4874 }
4875 return;
4876}
4877
4878bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004879 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004880 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004881 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004882 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004883 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004884 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004885 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004886 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004887 }
4888 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004889 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004890 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004891 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004892 return true;
4893 }
4894 return false;
4895}
4896
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004897bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4898 const FunctionProtoType *FTP;
4899 const PointerType *PT = QT->getAs<PointerType>();
4900 if (PT) {
4901 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4902 } else {
4903 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4904 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4905 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4906 }
4907 if (FTP) {
4908 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004909 E = FTP->arg_type_end(); I != E; ++I) {
4910 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004911 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004912 if ((*I)->isObjCObjectPointerType() &&
4913 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4914 return true;
4915 }
4916
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004917 }
4918 return false;
4919}
4920
Ted Kremenek8189cde2009-02-07 01:47:29 +00004921void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4922 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004923 const char *argPtr = strchr(Name, '(');
4924 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Steve Naroff54055232008-10-27 17:20:55 +00004926 LParen = argPtr; // output the start.
4927 argPtr++; // skip past the left paren.
4928 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Steve Naroff54055232008-10-27 17:20:55 +00004930 while (*argPtr && parenCount) {
4931 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004932 case '(': parenCount++; break;
4933 case ')': parenCount--; break;
4934 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004935 }
4936 if (parenCount) argPtr++;
4937 }
4938 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4939 RParen = argPtr; // output the end
4940}
4941
4942void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4943 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4944 RewriteBlockPointerFunctionArgs(FD);
4945 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004946 }
Steve Naroff54055232008-10-27 17:20:55 +00004947 // Handle Variables and Typedefs.
4948 SourceLocation DeclLoc = ND->getLocation();
4949 QualType DeclT;
4950 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4951 DeclT = VD->getType();
4952 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4953 DeclT = TDD->getUnderlyingType();
4954 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4955 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004956 else
Steve Naroff54055232008-10-27 17:20:55 +00004957 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004958
Steve Naroff54055232008-10-27 17:20:55 +00004959 const char *startBuf = SM->getCharacterData(DeclLoc);
4960 const char *endBuf = startBuf;
4961 // scan backward (from the decl location) for the end of the previous decl.
4962 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4963 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004964 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4965 std::string buf;
4966 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004967 // *startBuf != '^' if we are dealing with a pointer to function that
4968 // may take block argument types (which will be handled below).
4969 if (*startBuf == '^') {
4970 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004971 buf = '*';
4972 startBuf++;
4973 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004974 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004975 while (*startBuf != ')') {
4976 buf += *startBuf;
4977 startBuf++;
4978 OrigLength++;
4979 }
4980 buf += ')';
4981 OrigLength++;
4982
4983 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4984 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004985 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004986 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004987 DeclLoc = ND->getLocation();
4988 startBuf = SM->getCharacterData(DeclLoc);
4989 const char *argListBegin, *argListEnd;
4990 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4991 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004992 if (*argListBegin == '^')
4993 buf += '*';
4994 else if (*argListBegin == '<') {
4995 buf += "/*";
4996 buf += *argListBegin++;
4997 OrigLength++;;
4998 while (*argListBegin != '>') {
4999 buf += *argListBegin++;
5000 OrigLength++;
5001 }
5002 buf += *argListBegin;
5003 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005004 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005005 else
5006 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005007 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005008 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005009 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005010 buf += ')';
5011 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005012 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005013 ReplaceText(Start, OrigLength, buf);
5014
Steve Naroff54055232008-10-27 17:20:55 +00005015 return;
5016}
5017
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005018
5019/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5020/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5021/// struct Block_byref_id_object *src) {
5022/// _Block_object_assign (&_dest->object, _src->object,
5023/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5024/// [|BLOCK_FIELD_IS_WEAK]) // object
5025/// _Block_object_assign(&_dest->object, _src->object,
5026/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5027/// [|BLOCK_FIELD_IS_WEAK]) // block
5028/// }
5029/// And:
5030/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5031/// _Block_object_dispose(_src->object,
5032/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5033/// [|BLOCK_FIELD_IS_WEAK]) // object
5034/// _Block_object_dispose(_src->object,
5035/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5036/// [|BLOCK_FIELD_IS_WEAK]) // block
5037/// }
5038
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005039std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5040 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005041 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005042 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005043 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005044 CopyDestroyCache.insert(flag);
5045 S = "static void __Block_byref_id_object_copy_";
5046 S += utostr(flag);
5047 S += "(void *dst, void *src) {\n";
5048
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005049 // offset into the object pointer is computed as:
5050 // void * + void* + int + int + void* + void *
5051 unsigned IntSize =
5052 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5053 unsigned VoidPtrSize =
5054 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5055
5056 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
5057 S += " _Block_object_assign((char*)dst + ";
5058 S += utostr(offset);
5059 S += ", *(void * *) ((char*)src + ";
5060 S += utostr(offset);
5061 S += "), ";
5062 S += utostr(flag);
5063 S += ");\n}\n";
5064
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005065 S += "static void __Block_byref_id_object_dispose_";
5066 S += utostr(flag);
5067 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005068 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5069 S += utostr(offset);
5070 S += "), ";
5071 S += utostr(flag);
5072 S += ");\n}\n";
5073 return S;
5074}
5075
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005076/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5077/// the declaration into:
5078/// struct __Block_byref_ND {
5079/// void *__isa; // NULL for everything except __weak pointers
5080/// struct __Block_byref_ND *__forwarding;
5081/// int32_t __flags;
5082/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005083/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5084/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005085/// typex ND;
5086/// };
5087///
5088/// It then replaces declaration of ND variable with:
5089/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5090/// __size=sizeof(struct __Block_byref_ND),
5091/// ND=initializer-if-any};
5092///
5093///
5094void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005095 // Insert declaration for the function in which block literal is
5096 // used.
5097 if (CurFunctionDeclToDeclareForBlock)
5098 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005099 int flag = 0;
5100 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005101 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005102 if (DeclLoc.isInvalid())
5103 // If type location is missing, it is because of missing type (a warning).
5104 // Use variable's location which is good for this case.
5105 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005106 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005107 SourceLocation X = ND->getLocEnd();
5108 X = SM->getInstantiationLoc(X);
5109 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005110 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005111 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005112 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005113 ByrefType += " {\n";
5114 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005115 RewriteByRefString(ByrefType, Name, ND);
5116 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005117 ByrefType += " int __flags;\n";
5118 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005119 // Add void *__Block_byref_id_object_copy;
5120 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005121 QualType Ty = ND->getType();
5122 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5123 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005124 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5125 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005126 }
5127
5128 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005129 ByrefType += " " + Name + ";\n";
5130 ByrefType += "};\n";
5131 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005132 SourceLocation FunLocStart;
5133 if (CurFunctionDef)
5134 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5135 else {
5136 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5137 FunLocStart = CurMethodDef->getLocStart();
5138 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005139 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005140 if (Ty.isObjCGCWeak()) {
5141 flag |= BLOCK_FIELD_IS_WEAK;
5142 isa = 1;
5143 }
5144
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005145 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005146 flag = BLOCK_BYREF_CALLER;
5147 QualType Ty = ND->getType();
5148 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5149 if (Ty->isBlockPointerType())
5150 flag |= BLOCK_FIELD_IS_BLOCK;
5151 else
5152 flag |= BLOCK_FIELD_IS_OBJECT;
5153 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005154 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005155 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005156 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005157
5158 // struct __Block_byref_ND ND =
5159 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5160 // initializer-if-any};
5161 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005162 unsigned flags = 0;
5163 if (HasCopyAndDispose)
5164 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005165 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005166 ByrefType.clear();
5167 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005168 std::string ForwardingCastType("(");
5169 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005170 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005171 ByrefType += " " + Name + " = {(void*)";
5172 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005173 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005174 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005175 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005176 ByrefType += "sizeof(";
5177 RewriteByRefString(ByrefType, Name, ND);
5178 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005179 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005180 ByrefType += ", __Block_byref_id_object_copy_";
5181 ByrefType += utostr(flag);
5182 ByrefType += ", __Block_byref_id_object_dispose_";
5183 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005184 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005185 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005186 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005187 }
5188 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005189 SourceLocation startLoc;
5190 Expr *E = ND->getInit();
5191 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5192 startLoc = ECE->getLParenLoc();
5193 else
5194 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005195 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005196 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005197 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005198 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005199 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005200 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005201 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005202 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005203 ByrefType += "sizeof(";
5204 RewriteByRefString(ByrefType, Name, ND);
5205 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005206 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005207 ByrefType += "__Block_byref_id_object_copy_";
5208 ByrefType += utostr(flag);
5209 ByrefType += ", __Block_byref_id_object_dispose_";
5210 ByrefType += utostr(flag);
5211 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005212 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005213 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005214
5215 // Complete the newly synthesized compound expression by inserting a right
5216 // curly brace before the end of the declaration.
5217 // FIXME: This approach avoids rewriting the initializer expression. It
5218 // also assumes there is only one declarator. For example, the following
5219 // isn't currently supported by this routine (in general):
5220 //
5221 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5222 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005223 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5224 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005225 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5226 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005227 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005228
Benjamin Kramerd999b372010-02-14 14:14:16 +00005229 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005230 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005231 return;
5232}
5233
Mike Stump1eb44332009-09-09 15:08:12 +00005234void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005235 // Add initializers for any closure decl refs.
5236 GetBlockDeclRefExprs(Exp->getBody());
5237 if (BlockDeclRefs.size()) {
5238 // Unique all "by copy" declarations.
5239 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005240 if (!BlockDeclRefs[i]->isByRef()) {
5241 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5242 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5243 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5244 }
5245 }
Steve Naroff54055232008-10-27 17:20:55 +00005246 // Unique all "by ref" declarations.
5247 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5248 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005249 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5250 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5251 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5252 }
Steve Naroff54055232008-10-27 17:20:55 +00005253 }
5254 // Find any imported blocks...they will need special attention.
5255 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005256 if (BlockDeclRefs[i]->isByRef() ||
5257 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005258 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005259 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005260 }
5261}
5262
Daniel Dunbar4087f272010-08-17 22:39:59 +00005263FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(llvm::StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005264 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005265 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005266 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
John McCalld931b082010-08-26 03:08:43 +00005267 ID, FType, 0, SC_Extern,
5268 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005269}
5270
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005271Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5272 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005273 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005274 Blocks.push_back(Exp);
5275
5276 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005277
5278 // Add inner imported variables now used in current block.
5279 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005280 if (!InnerBlockDeclRefs.empty()) {
5281 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5282 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5283 ValueDecl *VD = Exp->getDecl();
5284 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005285 // We need to save the copied-in variables in nested
5286 // blocks because it is needed at the end for some of the API generations.
5287 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005288 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5289 BlockDeclRefs.push_back(Exp);
5290 BlockByCopyDeclsPtrSet.insert(VD);
5291 BlockByCopyDecls.push_back(VD);
5292 }
5293 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5294 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5295 BlockDeclRefs.push_back(Exp);
5296 BlockByRefDeclsPtrSet.insert(VD);
5297 BlockByRefDecls.push_back(VD);
5298 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005299 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005300 // Find any imported blocks...they will need special attention.
5301 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5302 if (InnerBlockDeclRefs[i]->isByRef() ||
5303 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5304 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5305 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005306 }
5307 InnerDeclRefsCount.push_back(countOfInnerDecls);
5308
Steve Narofffa15fd92008-10-28 20:29:00 +00005309 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005310
Steve Narofffa15fd92008-10-28 20:29:00 +00005311 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005312 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005313 else if (CurMethodDef)
5314 BuildUniqueMethodName(FuncName, CurMethodDef);
5315 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005316 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005317
Steve Narofffa15fd92008-10-28 20:29:00 +00005318 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005319
Steve Narofffa15fd92008-10-28 20:29:00 +00005320 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5321 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Steve Narofffa15fd92008-10-28 20:29:00 +00005323 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005324 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5325 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005326
5327 FunctionDecl *FD;
5328 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005329
Steve Narofffa15fd92008-10-28 20:29:00 +00005330 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005331 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005332 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5333 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005334
Steve Narofffa15fd92008-10-28 20:29:00 +00005335 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005336
Steve Narofffdc03722008-10-29 21:23:59 +00005337 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005338 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005339 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005340 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005341 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005342 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005343 InitExprs.push_back(castExpr);
5344
Steve Naroff01aec112009-12-06 21:14:13 +00005345 // Initialize the block descriptor.
5346 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005347
Steve Naroff01aec112009-12-06 21:14:13 +00005348 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5349 &Context->Idents.get(DescData.c_str()),
5350 Context->VoidPtrTy, 0,
John McCalld931b082010-08-26 03:08:43 +00005351 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005352 UnaryOperator *DescRefExpr =
5353 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5354 Context->VoidPtrTy,
5355 VK_LValue,
5356 SourceLocation()),
5357 UO_AddrOf,
5358 Context->getPointerType(Context->VoidPtrTy),
5359 VK_RValue, OK_Ordinary,
5360 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005361 InitExprs.push_back(DescRefExpr);
5362
Steve Narofffa15fd92008-10-28 20:29:00 +00005363 // Add initializers for any closure decl refs.
5364 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005365 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005367 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005368 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005369 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005370 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005371 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005372 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5373 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005374 if (HasLocalVariableExternalStorage(*I)) {
5375 QualType QT = (*I)->getType();
5376 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005377 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5378 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005379 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005380 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005381 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005382 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5383 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005384 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005385 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005386 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005387 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005388 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5389 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005390 if (HasLocalVariableExternalStorage(*I)) {
5391 QualType QT = (*I)->getType();
5392 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005393 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5394 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005395 }
5396
Steve Narofffa15fd92008-10-28 20:29:00 +00005397 }
Mike Stump1eb44332009-09-09 15:08:12 +00005398 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005399 }
5400 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005401 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005402 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005403 ValueDecl *ND = (*I);
5404 std::string Name(ND->getNameAsString());
5405 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005406 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005407 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5408 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005409 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005410 SourceLocation(), II);
5411 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5412 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5413
Daniel Dunbar4087f272010-08-17 22:39:59 +00005414 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005415 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5416 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005417 bool isNestedCapturedVar = false;
5418 if (block)
5419 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5420 ce = block->capture_end(); ci != ce; ++ci) {
5421 const VarDecl *variable = ci->getVariable();
5422 if (variable == ND && ci->isNested()) {
5423 assert (ci->isByRef() &&
5424 "SynthBlockInitExpr - captured block variable is not byref");
5425 isNestedCapturedVar = true;
5426 break;
5427 }
5428 }
5429 // captured nested byref variable has its address passed. Do not take
5430 // its address again.
5431 if (!isNestedCapturedVar)
5432 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005433 Context->getPointerType(Exp->getType()),
5434 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005435 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005436 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005437 }
5438 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005439 if (ImportedBlockDecls.size()) {
5440 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5441 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005442 unsigned IntSize =
5443 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005444 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5445 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005446 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005447 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005448 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005449 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005450 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005451 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005452 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005453 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005454 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005455 BlockDeclRefs.clear();
5456 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005457 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005458 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005459 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005460 ImportedBlockDecls.clear();
5461 return NewRep;
5462}
5463
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005464bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5465 if (const ObjCForCollectionStmt * CS =
5466 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5467 return CS->getElement() == DS;
5468 return false;
5469}
5470
Steve Narofffa15fd92008-10-28 20:29:00 +00005471//===----------------------------------------------------------------------===//
5472// Function Body / Expression rewriting
5473//===----------------------------------------------------------------------===//
5474
Steve Naroffc77a6362008-12-04 16:24:46 +00005475// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5476// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5477// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5478// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5479// Since the rewriter isn't capable of rewriting rewritten code, it's important
5480// we get this right.
5481void RewriteObjC::CollectPropertySetters(Stmt *S) {
5482 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005483 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005484 if (*CI)
5485 CollectPropertySetters(*CI);
5486
5487 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5488 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005489 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5490 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005491 }
5492 }
5493}
5494
Steve Narofffa15fd92008-10-28 20:29:00 +00005495Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005496 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005497 isa<DoStmt>(S) || isa<ForStmt>(S))
5498 Stmts.push_back(S);
5499 else if (isa<ObjCForCollectionStmt>(S)) {
5500 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005501 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005502 }
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Steve Narofffa15fd92008-10-28 20:29:00 +00005504 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005505
Steve Narofffa15fd92008-10-28 20:29:00 +00005506 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005507 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005508 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005509 Stmt *newStmt;
5510 Stmt *S = (*CI);
5511 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5512 Expr *OldBase = IvarRefExpr->getBase();
5513 bool replaced = false;
5514 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5515 if (replaced) {
5516 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5517 ReplaceStmt(OldBase, IRE->getBase());
5518 else
5519 ReplaceStmt(S, newStmt);
5520 }
5521 }
5522 else
5523 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005524 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005525 *CI = newStmt;
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005526 // If dealing with an assignment with LHS being a property reference
5527 // expression, the entire assignment tree is rewritten into a property
5528 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5529 // RHS again.
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005530 if (Expr *Exp = dyn_cast<Expr>(S))
John McCall12f78a62010-12-02 01:19:52 +00005531 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005532 if (PropSetters[Exp]) {
5533 ++CI;
5534 continue;
5535 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005536 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005537 }
Mike Stump1eb44332009-09-09 15:08:12 +00005538
Steve Narofffa15fd92008-10-28 20:29:00 +00005539 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005540 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005541 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5542 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005543 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005544 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005545 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005546 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005547 Stmt *SaveCurrentBody = CurrentBody;
5548 CurrentBody = BE->getBody();
5549 PropParentMap = 0;
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005551 CurrentBody = SaveCurrentBody;
5552 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005553 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005554 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005555 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005556 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005557
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005558 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5559
Steve Narofffa15fd92008-10-28 20:29:00 +00005560 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005561 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005562 return blockTranscribed;
5563 }
5564 // Handle specific things.
5565 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5566 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005567
John McCall12f78a62010-12-02 01:19:52 +00005568 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005569 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5570 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5571
5572 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005573 if (BinOp) {
5574 // Because the rewriter doesn't allow us to rewrite rewritten code,
5575 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005576 DisableReplaceStmt = true;
5577 // Save the source range. Even if we disable the replacement, the
5578 // rewritten node will have been inserted into the tree. If the synthesized
5579 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005580 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005581 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5582 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005583 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005584 // Need to rewrite the ivar access expression if need be.
5585 if (isa<ObjCIvarRefExpr>(newStmt)) {
5586 bool replaced = false;
5587 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5588 }
5589
Steve Naroffb619d952008-12-09 12:56:34 +00005590 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005591 //
5592 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5593 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5594 // to see the original expression). Consider this example:
5595 //
5596 // Foo *obj1, *obj2;
5597 //
5598 // obj1.i = [obj2 rrrr];
5599 //
5600 // 'BinOp' for the previous expression looks like:
5601 //
5602 // (BinaryOperator 0x231ccf0 'int' '='
5603 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5604 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5605 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5606 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5607 //
5608 // 'newStmt' represents the rewritten message expression. For example:
5609 //
5610 // (CallExpr 0x231d300 'id':'struct objc_object *'
5611 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5612 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5613 // (CStyleCastExpr 0x231d220 'void *'
5614 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5615 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005616 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005617 // can be used as the setter argument. ReplaceStmt() will still 'see'
5618 // the original RHS (since we haven't altered BinOp).
5619 //
Mike Stump1eb44332009-09-09 15:08:12 +00005620 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005621 // node. As a result, we now leak the original AST nodes.
5622 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005623 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005624 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005625 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005626 }
5627 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005628
Steve Narofffa15fd92008-10-28 20:29:00 +00005629 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5630 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005631
Steve Narofffa15fd92008-10-28 20:29:00 +00005632 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5633 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005634
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005636#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005637 // Before we rewrite it, put the original message expression in a comment.
5638 SourceLocation startLoc = MessExpr->getLocStart();
5639 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005640
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 const char *startBuf = SM->getCharacterData(startLoc);
5642 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005643
Steve Narofffa15fd92008-10-28 20:29:00 +00005644 std::string messString;
5645 messString += "// ";
5646 messString.append(startBuf, endBuf-startBuf+1);
5647 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005648
5649 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 // InsertText(clang::SourceLocation, char const*, unsigned int).
5651 // InsertText(startLoc, messString.c_str(), messString.size());
5652 // Tried this, but it didn't work either...
5653 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005654#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005655 return RewriteMessageExpr(MessExpr);
5656 }
Mike Stump1eb44332009-09-09 15:08:12 +00005657
Steve Narofffa15fd92008-10-28 20:29:00 +00005658 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5659 return RewriteObjCTryStmt(StmtTry);
5660
5661 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5662 return RewriteObjCSynchronizedStmt(StmtTry);
5663
5664 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5665 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005666
Steve Narofffa15fd92008-10-28 20:29:00 +00005667 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5668 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005669
5670 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005671 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005672 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 OrigStmtRange.getEnd());
5674 if (BreakStmt *StmtBreakStmt =
5675 dyn_cast<BreakStmt>(S))
5676 return RewriteBreakStmt(StmtBreakStmt);
5677 if (ContinueStmt *StmtContinueStmt =
5678 dyn_cast<ContinueStmt>(S))
5679 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005680
5681 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 // and cast exprs.
5683 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5684 // FIXME: What we're doing here is modifying the type-specifier that
5685 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005686 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005687 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5688 // the context of an ObjCForCollectionStmt. For example:
5689 // NSArray *someArray;
5690 // for (id <FooProtocol> index in someArray) ;
5691 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5692 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005693 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005694 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Steve Narofffa15fd92008-10-28 20:29:00 +00005696 // Blocks rewrite rules.
5697 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5698 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005699 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005700 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005701 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005702 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005703 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005704 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005705 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005706 if (VD->hasAttr<BlocksAttr>()) {
5707 static unsigned uniqueByrefDeclCount = 0;
5708 assert(!BlockByRefDeclNo.count(ND) &&
5709 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5710 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005711 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005712 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005713 else
5714 RewriteTypeOfDecl(VD);
5715 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 }
5717 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005718 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005719 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005720 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5722 }
5723 }
5724 }
Mike Stump1eb44332009-09-09 15:08:12 +00005725
Steve Narofffa15fd92008-10-28 20:29:00 +00005726 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5727 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005728
5729 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005730 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5731 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005732 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5733 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005734 && "Statement stack mismatch");
5735 Stmts.pop_back();
5736 }
5737 // Handle blocks rewriting.
5738 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5739 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005740 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005742 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5743 ValueDecl *VD = DRE->getDecl();
5744 if (VD->hasAttr<BlocksAttr>())
5745 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005746 if (HasLocalVariableExternalStorage(VD))
5747 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005748 }
5749
Steve Narofffa15fd92008-10-28 20:29:00 +00005750 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005751 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005752 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005753 ReplaceStmt(S, BlockCall);
5754 return BlockCall;
5755 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005757 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005758 RewriteCastExpr(CE);
5759 }
5760#if 0
5761 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005762 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5763 ICE->getSubExpr(),
5764 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005765 // Get the new text.
5766 std::string SStr;
5767 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005768 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005769 const std::string &Str = Buf.str();
5770
5771 printf("CAST = %s\n", &Str[0]);
5772 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5773 delete S;
5774 return Replacement;
5775 }
5776#endif
5777 // Return this stmt unmodified.
5778 return S;
5779}
5780
Steve Naroff3d7e7862009-12-05 15:55:59 +00005781void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5782 for (RecordDecl::field_iterator i = RD->field_begin(),
5783 e = RD->field_end(); i != e; ++i) {
5784 FieldDecl *FD = *i;
5785 if (isTopLevelBlockPointerType(FD->getType()))
5786 RewriteBlockPointerDecl(FD);
5787 if (FD->getType()->isObjCQualifiedIdType() ||
5788 FD->getType()->isObjCQualifiedInterfaceType())
5789 RewriteObjCQualifiedInterfaceTypes(FD);
5790 }
5791}
5792
Steve Narofffa15fd92008-10-28 20:29:00 +00005793/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5794/// main file of the input.
5795void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5796 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005797 if (FD->isOverloadedOperator())
5798 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005799
Steve Narofffa15fd92008-10-28 20:29:00 +00005800 // Since function prototypes don't have ParmDecl's, we check the function
5801 // prototype. This enables us to rewrite function declarations and
5802 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005803 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005804
Sebastian Redld3a413d2009-04-26 20:35:05 +00005805 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005806 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005807 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005808 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005809 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005810 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005811 Body =
5812 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5813 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005814 CurrentBody = 0;
5815 if (PropParentMap) {
5816 delete PropParentMap;
5817 PropParentMap = 0;
5818 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005819 // This synthesizes and inserts the block "impl" struct, invoke function,
5820 // and any copy/dispose helper functions.
5821 InsertBlockLiteralsWithinFunction(FD);
5822 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005823 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005824 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005825 return;
5826 }
5827 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005828 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005829 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005830 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005831 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005832 Body =
5833 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5834 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005835 CurrentBody = 0;
5836 if (PropParentMap) {
5837 delete PropParentMap;
5838 PropParentMap = 0;
5839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 InsertBlockLiteralsWithinMethod(MD);
5841 CurMethodDef = 0;
5842 }
5843 }
5844 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5845 ClassImplementation.push_back(CI);
5846 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5847 CategoryImplementation.push_back(CI);
5848 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5849 RewriteForwardClassDecl(CD);
5850 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5851 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005852 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005853 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005854 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005855 CheckFunctionPointerDecl(VD->getType(), VD);
5856 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005857 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005858 RewriteCastExpr(CE);
5859 }
5860 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005861 } else if (VD->getType()->isRecordType()) {
5862 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5863 if (RD->isDefinition())
5864 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005865 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005866 if (VD->getInit()) {
5867 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005868 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005869 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005870 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005871 CurrentBody = 0;
5872 if (PropParentMap) {
5873 delete PropParentMap;
5874 PropParentMap = 0;
5875 }
Mike Stump1eb44332009-09-09 15:08:12 +00005876 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005877 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005878 GlobalVarDecl = 0;
5879
5880 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005881 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005882 RewriteCastExpr(CE);
5883 }
5884 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005885 return;
5886 }
5887 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005888 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005890 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005891 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5892 return;
5893 }
5894 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005895 if (RD->isDefinition())
5896 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005897 return;
5898 }
5899 // Nothing yet.
5900}
5901
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005902void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005903 if (Diags.hasErrorOccurred())
5904 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005905
Steve Narofffa15fd92008-10-28 20:29:00 +00005906 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005907
Steve Naroff621edce2009-04-29 16:37:50 +00005908 // Here's a great place to add any extra declarations that may be needed.
5909 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005910 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005911 E = ProtocolExprDecls.end(); I != E; ++I)
5912 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5913
Benjamin Kramerd999b372010-02-14 14:14:16 +00005914 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005915 if (ClassImplementation.size() || CategoryImplementation.size())
5916 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005917
Steve Narofffa15fd92008-10-28 20:29:00 +00005918 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5919 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005920 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005921 Rewrite.getRewriteBufferFor(MainFileID)) {
5922 //printf("Changed:\n");
5923 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5924 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005925 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005926 }
Steve Narofface66252008-11-13 20:07:04 +00005927
Steve Naroff621edce2009-04-29 16:37:50 +00005928 if (ClassImplementation.size() || CategoryImplementation.size() ||
5929 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005930 // Rewrite Objective-c meta data*
5931 std::string ResultStr;
5932 SynthesizeMetaDataIntoBuffer(ResultStr);
5933 // Emit metadata.
5934 *OutFile << ResultStr;
5935 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005936 OutFile->flush();
5937}