blob: cba92987a3d6ce3b16f682be715db097cc33fae9 [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, 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).
145 llvm::DenseMap<ObjCPropertyRefExpr *, 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
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +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) {
198 // Measaure the old text.
199 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 RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000239
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000271 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000273 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000274 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000275 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000276 bool isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000277 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000278 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000279 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000282 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000283 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Steve Naroff8599e7a2008-12-08 16:43:47 +0000285 Stmt *CurrentBody;
286 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000289 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
290 bool &replaced);
291 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000292 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000293 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000294 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000295 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000296 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000297 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000298 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000299 void WarnAboutReturnGotoStmts(Stmt *S);
300 void HasReturnStmts(Stmt *S, bool &hasReturns);
301 void RewriteTryReturnStmts(Stmt *S);
302 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000303 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000304 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
306 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000310 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000311 Expr **args, unsigned nargs,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
314 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000317 Stmt *RewriteBreakStmt(BreakStmt *S);
318 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000319 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Steve Naroff09b266e2007-10-30 23:14:51 +0000321 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000322 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000323 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000324 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000325 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000326 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000327 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000328 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000329 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000330 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattnerf04da132007-10-24 17:06:59 +0000332 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000333 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor653f1b12009-04-23 01:02:12 +0000339 template<typename MethodIterator>
340 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
341 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000342 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000343 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000344 const char *ClassName,
345 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Steve Naroff621edce2009-04-29 16:37:50 +0000347 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
348 const char *prefix,
349 const char *ClassName,
350 std::string &Result);
351 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000352 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000353 const char *ClassName,
354 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000355 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000356 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000357 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockCall(CallExpr *Exp);
372 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000373 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000375 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000376 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000377 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
379 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000380 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000382 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000383 std::string SynthesizeBlockImpl(BlockExpr *CE,
384 std::string Tag, std::string Desc);
385 std::string SynthesizeBlockDescriptor(std::string DescTag,
386 std::string ImplTag,
387 int i, const char *funcName,
388 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000389 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000390 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000391 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000392 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Steve Naroff54055232008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
397 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 // FIXME: This predicate seems like it would be useful to add to ASTContext.
407 bool isObjCType(QualType T) {
408 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
409 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Steve Naroff54055232008-10-27 17:20:55 +0000411 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Naroff54055232008-10-27 17:20:55 +0000413 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
414 OCT == Context->getCanonicalType(Context->getObjCClassType()))
415 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Ted Kremenek6217b802009-07-29 21:53:49 +0000417 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000418 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000419 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000420 return true;
421 }
422 return false;
423 }
424 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000425 void GetExtentOfArgList(const char *Name, const char *&LParen,
426 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000427 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Steve Narofffa15fd92008-10-28 20:29:00 +0000429 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000430 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
431 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Steve Naroff621edce2009-04-29 16:37:50 +0000433 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000435 if (From[i] == '"')
436 To += "\\\"";
437 else
438 To += From[i];
439 }
440 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000441 };
John McCall9d125032010-01-15 18:39:57 +0000442
443 // Helper function: create a CStyleCastExpr with trivial type source info.
444 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
445 CastExpr::CastKind Kind, Expr *E) {
446 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
447 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
448 SourceLocation(), SourceLocation());
449 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000450}
451
Mike Stump1eb44332009-09-09 15:08:12 +0000452void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
453 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000454 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000456 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000457 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000458 // All the args are checked/rewritten. Don't call twice!
459 RewriteBlockPointerDecl(D);
460 break;
461 }
462 }
463}
464
465void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000466 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000467 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000468 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000469}
470
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000471static bool IsHeaderFile(const std::string &Filename) {
472 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000474 if (DotPos == std::string::npos) {
475 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000476 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
480 // C header: .h
481 // C++ header: .hh or .H;
482 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000483}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000484
Eli Friedman66d6f042009-05-18 22:20:00 +0000485RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000486 Diagnostic &D, const LangOptions &LOpts,
487 bool silenceMacroWarn)
488 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
489 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000490 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000491 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000492 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000493 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000494 "rewriter doesn't support user-specified control flow semantics "
495 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000496}
497
Eli Friedmanbce831b2009-05-18 22:29:17 +0000498ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
499 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000501 const LangOptions &LOpts,
502 bool SilenceRewriteMacroWarning) {
503 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000504}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000505
Steve Naroffb29b4272008-04-14 22:03:09 +0000506void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000507 Context = &context;
508 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000509 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000510 MsgSendFunctionDecl = 0;
511 MsgSendSuperFunctionDecl = 0;
512 MsgSendStretFunctionDecl = 0;
513 MsgSendSuperStretFunctionDecl = 0;
514 MsgSendFpretFunctionDecl = 0;
515 GetClassFunctionDecl = 0;
516 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000517 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000518 SelGetUidFunctionDecl = 0;
519 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 ConstantStringClassReference = 0;
521 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000522 CurMethodDef = 0;
523 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000524 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000525 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000526 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000527 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000528 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000529 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000530 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000531 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000532 PropParentMap = 0;
533 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000534 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000535 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000537 // Get the ID and start/end of the main file.
538 MainFileID = SM->getMainFileID();
539 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
540 MainFileStart = MainBuf->getBufferStart();
541 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattner2c78b872009-04-14 23:22:57 +0000543 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000545 // declaring objc_selector outside the parameter list removes a silly
546 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000547 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000548 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000550 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000552 if (LangOpts.Microsoft) {
553 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000554 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
555 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000557 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
560 Preamble += "typedef struct objc_object Protocol;\n";
561 Preamble += "#define _REWRITER_typedef_Protocol\n";
562 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000563 if (LangOpts.Microsoft) {
564 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
565 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
566 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000567 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
581 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000589 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000590 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
595 Preamble += "struct __objcFastEnumerationState {\n\t";
596 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000597 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "unsigned long *mutationsPtr;\n\t";
599 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "#define __FASTENUMERATIONSTATE\n";
602 Preamble += "#endif\n";
603 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
604 Preamble += "struct __NSConstantStringImpl {\n";
605 Preamble += " int *isa;\n";
606 Preamble += " int flags;\n";
607 Preamble += " char *str;\n";
608 Preamble += " long length;\n";
609 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000610 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
611 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
612 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000614 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000617 // Blocks preamble.
618 Preamble += "#ifndef BLOCK_IMPL\n";
619 Preamble += "#define BLOCK_IMPL\n";
620 Preamble += "struct __block_impl {\n";
621 Preamble += " void *isa;\n";
622 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000623 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000624 Preamble += " void *FuncPtr;\n";
625 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000626 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000627 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000628 Preamble += "extern \"C\" __declspec(dllexport) "
629 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000630 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
631 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
633 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000636 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
638 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000639 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000640 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
642 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000643 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000644 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000645 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000646 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000647 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000648 Preamble += "#define __weak\n";
649 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000650 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
651 // as this avoids warning in any 64bit/32bit compilation model.
652 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000653}
654
655
Chris Lattnerf04da132007-10-24 17:06:59 +0000656//===----------------------------------------------------------------------===//
657// Top Level Driver Code
658//===----------------------------------------------------------------------===//
659
Chris Lattner682bf922009-03-29 16:50:03 +0000660void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000661 if (Diags.hasErrorOccurred())
662 return;
663
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000664 // Two cases: either the decl could be in the main file, or it could be in a
665 // #included file. If the former, rewrite it now. If the later, check to see
666 // if we rewrote the #include/#import.
667 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000668 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000670 // If this is for a builtin, ignore it.
671 if (Loc.isInvalid()) return;
672
Steve Naroffebf2b562007-10-23 23:50:29 +0000673 // Look for built-in declarations that we need to refer during the rewrite.
674 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000675 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000676 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000677 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000678 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000679 ConstantStringClassReference = FVD;
680 return;
681 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000682 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000683 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000685 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000687 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000688 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000689 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000690 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000691 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
692 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000693 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
694 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000695 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000696 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000697 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000698 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000699 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000700 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000701}
702
Chris Lattnerf04da132007-10-24 17:06:59 +0000703//===----------------------------------------------------------------------===//
704// Syntactic (non-AST) Rewriting Code
705//===----------------------------------------------------------------------===//
706
Steve Naroffb29b4272008-04-14 22:03:09 +0000707void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000708 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000709 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
710 const char *MainBufStart = MainBuf.begin();
711 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000712 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000714 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
716 if (*BufPtr == '#') {
717 if (++BufPtr == MainBufEnd)
718 return;
719 while (*BufPtr == ' ' || *BufPtr == '\t')
720 if (++BufPtr == MainBufEnd)
721 return;
722 if (!strncmp(BufPtr, "import", ImportLen)) {
723 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000724 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000725 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000726 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000727 BufPtr += ImportLen;
728 }
729 }
730 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000731}
732
Steve Naroffb29b4272008-04-14 22:03:09 +0000733void RewriteObjC::RewriteTabs() {
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();
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerf04da132007-10-24 17:06:59 +0000738 // Loop over the whole file, looking for tabs.
739 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
740 if (*BufPtr != '\t')
741 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattnerf04da132007-10-24 17:06:59 +0000743 // Okay, we found a tab. This tab will turn into at least one character,
744 // but it depends on which 'virtual column' it is in. Compute that now.
745 unsigned VCol = 0;
746 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
747 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
748 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Chris Lattnerf04da132007-10-24 17:06:59 +0000750 // Okay, now that we know the virtual column, we know how many spaces to
751 // insert. We assume 8-character tab-stops.
752 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Chris Lattnerf04da132007-10-24 17:06:59 +0000754 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000755 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
756 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Chris Lattnerf04da132007-10-24 17:06:59 +0000758 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000759 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000760 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000761}
762
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
764 ObjCIvarDecl *OID) {
765 std::string S;
766 S = "((struct ";
767 S += ClassDecl->getIdentifier()->getName();
768 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000769 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770 return S;
771}
772
Steve Naroffa0876e82008-12-02 17:36:43 +0000773void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
774 ObjCImplementationDecl *IMD,
775 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000776 static bool objcGetPropertyDefined = false;
777 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000778 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000779 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 const char *startBuf = SM->getCharacterData(startLoc);
781 assert((*startBuf == '@') && "bogus @synthesize location");
782 const char *semiBuf = strchr(startBuf, ';');
783 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000784 SourceLocation onePastSemiLoc =
785 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786
787 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
788 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Steve Naroffeb0646c2008-12-02 15:48:25 +0000790 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000791 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000795 if (!OID)
796 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000797 unsigned Attributes = PD->getPropertyAttributes();
798 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
799 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
800 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000801 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000802 if (GenGetProperty && !objcGetPropertyDefined) {
803 objcGetPropertyDefined = true;
804 // FIXME. Is this attribute correct in all cases?
805 Getr = "\nextern \"C\" __declspec(dllimport) "
806 "id objc_getProperty(id, SEL, long, bool);\n";
807 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000808 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
809 Getr += "{ ";
810 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000811 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000812 if (GenGetProperty) {
813 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
814 Getr += "typedef ";
815 const FunctionType *FPRetType = 0;
816 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
817 FPRetType);
818 Getr += " _TYPE";
819 if (FPRetType) {
820 Getr += ")"; // close the precedence "scope" for "*".
821
822 // Now, emit the argument types (if any).
823 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
824 Getr += "(";
825 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
826 if (i) Getr += ", ";
827 std::string ParamStr = FT->getArgType(i).getAsString();
828 Getr += ParamStr;
829 }
830 if (FT->isVariadic()) {
831 if (FT->getNumArgs()) Getr += ", ";
832 Getr += "...";
833 }
834 Getr += ")";
835 } else
836 Getr += "()";
837 }
838 Getr += ";\n";
839 Getr += "return (_TYPE)";
840 Getr += "objc_getProperty(self, _cmd, ";
841 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
842 Getr += ", 1)";
843 }
844 else
845 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000846 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000847 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000848 if (PD->isReadOnly())
849 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Steve Naroffeb0646c2008-12-02 15:48:25 +0000851 // Generate the 'setter' function.
852 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000853 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
854 ObjCPropertyDecl::OBJC_PR_copy);
855 if (GenSetProperty && !objcSetPropertyDefined) {
856 objcSetPropertyDefined = true;
857 // FIXME. Is this attribute correct in all cases?
858 Setr = "\nextern \"C\" __declspec(dllimport) "
859 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
860 }
861
Steve Naroffeb0646c2008-12-02 15:48:25 +0000862 RewriteObjCMethodDecl(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, ";
868 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
869 Setr += ", (id)";
870 Setr += PD->getNameAsCString();
871 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 {
882 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
883 Setr += PD->getNameAsCString();
884 }
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.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000972 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000973}
974
Steve Naroffb29b4272008-04-14 22:03:09 +0000975void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000976 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Steve Naroff752d6ef2007-10-30 16:42:30 +0000978 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000979 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000980
981 for (ObjCProtocolDecl::instmeth_iterator
982 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000985 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000986 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000988 RewriteMethodDeclaration(*I);
989
Steve Naroff752d6ef2007-10-30 16:42:30 +0000990 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000991 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000993
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000994 // Must comment out @optional/@required
995 const char *startBuf = SM->getCharacterData(LocStart);
996 const char *endBuf = SM->getCharacterData(LocEnd);
997 for (const char *p = startBuf; p < endBuf; p++) {
998 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000999 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001000 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001002 }
1003 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
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("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001007 }
1008 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001009}
1010
Steve Naroffb29b4272008-04-14 22:03:09 +00001011void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001012 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001013 if (LocStart.isInvalid())
1014 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001015 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001016 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017}
1018
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001019void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1020 const FunctionType *&FPRetType) {
1021 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001022 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001023 else if (T->isFunctionPointerType() ||
1024 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001025 // needs special handling, since pointer-to-functions have special
1026 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001028 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001029 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001032 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001033 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +00001034 ResultStr += FPRetType->getResultType().getAsString();
1035 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001036 }
1037 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001038 ResultStr += T.getAsString();
1039}
1040
1041void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1042 std::string &ResultStr) {
1043 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1044 const FunctionType *FPRetType = 0;
1045 ResultStr += "\nstatic ";
1046 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001047 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001049 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001050 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001052 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001053 NameStr += "_I_";
1054 else
1055 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001057 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001058 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001059
1060 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001061 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001062 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001063 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001066 {
1067 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001068 int len = selString.size();
1069 for (int i = 0; i < len; i++)
1070 if (selString[i] == ':')
1071 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001072 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001074 // Remember this name for metadata emission
1075 MethodInternalNames[OMD] = NameStr;
1076 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 // Rewrite arguments
1079 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001082 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001083 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001085 if (!LangOpts.Microsoft) {
1086 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1087 ResultStr += "struct ";
1088 }
1089 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001090 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001091 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001092 }
1093 else
Steve Naroff621edce2009-04-29 16:37:50 +00001094 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001097 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001101 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1102 E = OMD->param_end(); PI != E; ++PI) {
1103 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001105 if (PDecl->getType()->isObjCQualifiedIdType()) {
1106 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001108 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001110 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001111 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001112 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001113 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1114 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001115 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001116 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001117 ResultStr += Name;
1118 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001120 if (OMD->isVariadic())
1121 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001122 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Steve Naroff76e429d2008-07-16 14:40:40 +00001124 if (FPRetType) {
1125 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Steve Naroff76e429d2008-07-16 14:40:40 +00001127 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001128 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001129 ResultStr += "(";
1130 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1131 if (i) ResultStr += ", ";
1132 std::string ParamStr = FT->getArgType(i).getAsString();
1133 ResultStr += ParamStr;
1134 }
1135 if (FT->isVariadic()) {
1136 if (FT->getNumArgs()) ResultStr += ", ";
1137 ResultStr += "...";
1138 }
1139 ResultStr += ")";
1140 } else {
1141 ResultStr += "()";
1142 }
1143 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001145void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001146 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1147 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001149 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001151 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001152 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1153 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001154 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001156 ObjCMethodDecl *OMD = *I;
1157 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001159 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001160
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 const char *startBuf = SM->getCharacterData(LocStart);
1162 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001163 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001166 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001167 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1168 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001169 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001171 ObjCMethodDecl *OMD = *I;
1172 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001180 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001181 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001182 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001183 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001184 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001185 }
1186
Benjamin Kramerd999b372010-02-14 14:14:16 +00001187 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001188}
1189
Steve Naroffb29b4272008-04-14 22:03:09 +00001190void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001191 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001193 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001194 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001196 ResultStr += "\n";
1197 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001199 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001200 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001201 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001202 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001203 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001204 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001205 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
1208 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001210 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001211 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001213 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001214 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001215 for (ObjCInterfaceDecl::classmeth_iterator
1216 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001217 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001218 RewriteMethodDeclaration(*I);
1219
Steve Naroff2feac5e2007-10-30 03:43:13 +00001220 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001221 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001222}
1223
Steve Naroffb619d952008-12-09 12:56:34 +00001224Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1225 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001226 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1227 // This allows us to reuse all the fun and games in SynthMessageExpr().
1228 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1229 ObjCMessageExpr *MsgExpr;
1230 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1231 llvm::SmallVector<Expr *, 1> ExprVec;
1232 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Steve Naroff8599e7a2008-12-08 16:43:47 +00001234 Stmt *Receiver = PropRefExpr->getBase();
1235 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1236 if (PRE && PropGetters[PRE]) {
1237 // This allows us to handle chain/nested property getters.
1238 Receiver = PropGetters[PRE];
1239 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001240 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001241 PDecl->getSetterName(), PDecl->getType(),
1242 PDecl->getSetterMethodDecl(),
1243 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001244 &ExprVec[0], 1);
1245 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Steve Naroffc77a6362008-12-04 16:24:46 +00001247 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001248 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001249 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001250 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1251 // to things that stay around.
1252 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001253 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001254}
1255
Steve Naroffc77a6362008-12-04 16:24:46 +00001256Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001257 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1258 // This allows us to reuse all the fun and games in SynthMessageExpr().
1259 ObjCMessageExpr *MsgExpr;
1260 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Steve Naroff8599e7a2008-12-08 16:43:47 +00001262 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Steve Naroff8599e7a2008-12-08 16:43:47 +00001264 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1265 if (PRE && PropGetters[PRE]) {
1266 // This allows us to handle chain/nested property getters.
1267 Receiver = PropGetters[PRE];
1268 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001269 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001270 PDecl->getGetterName(), PDecl->getType(),
1271 PDecl->getGetterMethodDecl(),
1272 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001273 0, 0);
1274
Steve Naroff4c3580e2008-12-04 23:50:32 +00001275 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001276
1277 if (!PropParentMap)
1278 PropParentMap = new ParentMap(CurrentBody);
1279
1280 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1281 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1282 // We stash away the ReplacingStmt since actually doing the
1283 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1284 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001285 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1286 // to things that stay around.
1287 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001288 return PropRefExpr; // return the original...
1289 } else {
1290 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001291 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001292 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1293 // to things that stay around.
1294 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001295 return ReplacingStmt;
1296 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001297}
1298
Mike Stump1eb44332009-09-09 15:08:12 +00001299Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001300 SourceLocation OrigStart,
1301 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001302 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001303 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001304 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001305 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001306 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001307 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001308 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001309 // lookup which class implements the instance variable.
1310 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001311 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001312 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001313 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Steve Narofff0757612008-05-08 17:52:16 +00001315 // Synthesize an explicit cast to gain access to the ivar.
1316 std::string RecName = clsDeclared->getIdentifier()->getName();
1317 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001318 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001319 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001320 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001321 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1322 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001323 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1324 CastExpr::CK_Unknown,
1325 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001326 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001327 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1328 IV->getBase()->getLocEnd(),
1329 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001330 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001331 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001332 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001333 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1334 IV->getLocation(),
1335 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001336 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001337 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001338 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001339 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001340 // Cannot delete IV->getBase(), since PE points to it.
1341 // Replace the old base with the cast. This is important when doing
1342 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001343 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001344 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001345 }
Steve Naroff84472a82008-04-18 21:55:08 +00001346 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001347 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001348
Steve Naroff9f525972008-05-06 23:20:07 +00001349 // Explicit ivar refs need to have a cast inserted.
1350 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001351 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001352 ObjCInterfaceType *iFaceDecl =
1353 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001354 // lookup which class implements the instance variable.
1355 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001356 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001357 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001358 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001359
Steve Naroff9f525972008-05-06 23:20:07 +00001360 // Synthesize an explicit cast to gain access to the ivar.
1361 std::string RecName = clsDeclared->getIdentifier()->getName();
1362 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001363 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001364 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001365 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001366 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1367 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001368 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1369 CastExpr::CK_Unknown,
1370 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001371 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001372 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001373 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001374 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001375 // Cannot delete IV->getBase(), since PE points to it.
1376 // Replace the old base with the cast. This is important when doing
1377 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001378 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001379 return IV;
1380 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001381 }
Steve Naroff84472a82008-04-18 21:55:08 +00001382 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001383}
1384
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001385Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1386 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1387 CI != E; ++CI) {
1388 if (*CI) {
1389 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1390 if (newStmt)
1391 *CI = newStmt;
1392 }
1393 }
1394 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1395 SourceRange OrigStmtRange = S->getSourceRange();
1396 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1397 replaced);
1398 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001399 }
1400 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1401 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1402 return newStmt;
1403 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001404 return S;
1405}
1406
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407/// SynthCountByEnumWithState - To print:
1408/// ((unsigned int (*)
1409/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001410/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001412/// "countByEnumeratingWithState:objects:count:"),
1413/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414/// (id *)items, (unsigned int)16)
1415///
Steve Naroffb29b4272008-04-14 22:03:09 +00001416void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1418 "id *, unsigned int))(void *)objc_msgSend)";
1419 buf += "\n\t\t";
1420 buf += "((id)l_collection,\n\t\t";
1421 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1422 buf += "\n\t\t";
1423 buf += "&enumState, "
1424 "(id *)items, (unsigned int)16)";
1425}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001426
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001427/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1428/// statement to exit to its outer synthesized loop.
1429///
Steve Naroffb29b4272008-04-14 22:03:09 +00001430Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001431 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1432 return S;
1433 // replace break with goto __break_label
1434 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436 SourceLocation startLoc = S->getLocStart();
1437 buf = "goto __break_label_";
1438 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001439 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001440
1441 return 0;
1442}
1443
1444/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1445/// statement to continue with its inner synthesized loop.
1446///
Steve Naroffb29b4272008-04-14 22:03:09 +00001447Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001448 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1449 return S;
1450 // replace continue with goto __continue_label
1451 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001453 SourceLocation startLoc = S->getLocStart();
1454 buf = "goto __continue_label_";
1455 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001456 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458 return 0;
1459}
1460
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001461/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001462/// It rewrites:
1463/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001464
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001465/// Into:
1466/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001467/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001468/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001469/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001470/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001471/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001473/// if (limit) {
1474/// unsigned long startMutations = *enumState.mutationsPtr;
1475/// do {
1476/// unsigned long counter = 0;
1477/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001478/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001480/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001481/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001482/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001483/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001484/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001485/// objects:items count:16]);
1486/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001488/// }
1489/// else
1490/// elem = nil;
1491/// }
1492///
Steve Naroffb29b4272008-04-14 22:03:09 +00001493Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001494 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001495 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001496 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001497 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001498 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001499 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001500
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001502 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001504 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 std::string buf;
1506 buf = "\n{\n\t";
1507 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1508 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001509 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001510 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001511 if (ElementType->isObjCQualifiedIdType() ||
1512 ElementType->isObjCQualifiedInterfaceType())
1513 // Simply use 'id' for all qualified types.
1514 elementTypeAsString = "id";
1515 else
1516 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001517 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001519 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001520 buf += elementName;
1521 buf += ";\n\t";
1522 }
Chris Lattner06767512008-04-08 05:52:18 +00001523 else {
1524 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001525 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001526 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1527 if (VD->getType()->isObjCQualifiedIdType() ||
1528 VD->getType()->isObjCQualifiedInterfaceType())
1529 // Simply use 'id' for all qualified types.
1530 elementTypeAsString = "id";
1531 else
1532 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535 // struct __objcFastEnumerationState enumState = { 0 };
1536 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1537 // id items[16];
1538 buf += "id items[16];\n\t";
1539 // id l_collection = (id)
1540 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001541 // Find start location of 'collection' the hard way!
1542 const char *startCollectionBuf = startBuf;
1543 startCollectionBuf += 3; // skip 'for'
1544 startCollectionBuf = strchr(startCollectionBuf, '(');
1545 startCollectionBuf++; // skip '('
1546 // find 'in' and skip it.
1547 while (*startCollectionBuf != ' ' ||
1548 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1549 (*(startCollectionBuf+3) != ' ' &&
1550 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1551 startCollectionBuf++;
1552 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001553
1554 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001555 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001556 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001557 SourceLocation rightParenLoc = S->getRParenLoc();
1558 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1559 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001560 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001562 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1563 // objects:items count:16];
1564 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001565 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566 // ((unsigned int (*)
1567 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // "countByEnumeratingWithState:objects:count:"),
1571 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // (id *)items, (unsigned int)16);
1573 buf += "unsigned long limit =\n\t\t";
1574 SynthCountByEnumWithState(buf);
1575 buf += ";\n\t";
1576 /// if (limit) {
1577 /// unsigned long startMutations = *enumState.mutationsPtr;
1578 /// do {
1579 /// unsigned long counter = 0;
1580 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001581 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001582 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001583 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001584 buf += "if (limit) {\n\t";
1585 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1586 buf += "do {\n\t\t";
1587 buf += "unsigned long counter = 0;\n\t\t";
1588 buf += "do {\n\t\t\t";
1589 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1590 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1591 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001592 buf += " = (";
1593 buf += elementTypeAsString;
1594 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001595 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001596 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001598 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001600 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001601 /// objects:items count:16]);
1602 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001603 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 /// }
1605 /// else
1606 /// elem = nil;
1607 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001608 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001609 buf = ";\n\t";
1610 buf += "__continue_label_";
1611 buf += utostr(ObjCBcLabelNo.back());
1612 buf += ": ;";
1613 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001614 buf += "} while (counter < limit);\n\t";
1615 buf += "} while (limit = ";
1616 SynthCountByEnumWithState(buf);
1617 buf += ");\n\t";
1618 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001619 buf += " = ((";
1620 buf += elementTypeAsString;
1621 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001622 buf += "__break_label_";
1623 buf += utostr(ObjCBcLabelNo.back());
1624 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 buf += "}\n\t";
1626 buf += "else\n\t\t";
1627 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001628 buf += " = ((";
1629 buf += elementTypeAsString;
1630 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001631 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001634 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001635 if (isa<CompoundStmt>(S->getBody())) {
1636 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001637 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001638 } else {
1639 /* Need to treat single statements specially. For example:
1640 *
1641 * for (A *a in b) if (stuff()) break;
1642 * for (A *a in b) xxxyy;
1643 *
1644 * The following code simply scans ahead to the semi to find the actual end.
1645 */
1646 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1647 const char *semiBuf = strchr(stmtBuf, ';');
1648 assert(semiBuf && "Can't find ';'");
1649 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001650 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001651 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001652 Stmts.pop_back();
1653 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001655}
1656
Mike Stump1eb44332009-09-09 15:08:12 +00001657/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001658/// This routine rewrites @synchronized(expr) stmt;
1659/// into:
1660/// objc_sync_enter(expr);
1661/// @try stmt @finally { objc_sync_exit(expr); }
1662///
Steve Naroffb29b4272008-04-14 22:03:09 +00001663Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001664 // Get the start location and compute the semi location.
1665 SourceLocation startLoc = S->getLocStart();
1666 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001668 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001669
1670 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001671 buf = "objc_sync_enter((id)";
1672 const char *lparenBuf = startBuf;
1673 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001674 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001675 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1676 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001677 // been rewritten! (which implies the SourceLocation's are invalid).
1678 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001679 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001680 while (*endBuf != ')') endBuf--;
1681 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001682 buf = ");\n";
1683 // declare a new scope with two variables, _stack and _rethrow.
1684 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1685 buf += "int buf[18/*32-bit i386*/];\n";
1686 buf += "char *pointers[4];} _stack;\n";
1687 buf += "id volatile _rethrow = 0;\n";
1688 buf += "objc_exception_try_enter(&_stack);\n";
1689 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001690 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001691 startLoc = S->getSynchBody()->getLocEnd();
1692 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Steve Naroffc7089f12008-08-19 13:04:19 +00001694 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001695 SourceLocation lastCurlyLoc = startLoc;
1696 buf = "}\nelse {\n";
1697 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001698 buf += "}\n";
1699 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001701
1702 std::string syncBuf;
1703 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001704 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1705 CastExpr::CK_Unknown,
1706 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001707 std::string syncExprBufS;
1708 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001709 syncExpr->printPretty(syncExprBuf, *Context, 0,
1710 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001711 syncBuf += syncExprBuf.str();
1712 syncBuf += ");";
1713
1714 buf += syncBuf;
1715 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001716 buf += "}\n";
1717 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Benjamin Kramerd999b372010-02-14 14:14:16 +00001719 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001720
1721 bool hasReturns = false;
1722 HasReturnStmts(S->getSynchBody(), hasReturns);
1723 if (hasReturns)
1724 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1725
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001726 return 0;
1727}
1728
Steve Naroffb85e77a2009-12-05 21:43:12 +00001729void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1730{
Steve Naroff8c565152008-12-05 17:03:39 +00001731 // Perform a bottom up traversal of all children.
1732 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1733 CI != E; ++CI)
1734 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001735 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001736
Steve Naroffb85e77a2009-12-05 21:43:12 +00001737 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001738 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001739 TryFinallyContainsReturnDiag);
1740 }
1741 return;
1742}
1743
Steve Naroffb85e77a2009-12-05 21:43:12 +00001744void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1745{
1746 // Perform a bottom up traversal of all children.
1747 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1748 CI != E; ++CI)
1749 if (*CI)
1750 HasReturnStmts(*CI, hasReturns);
1751
1752 if (isa<ReturnStmt>(S))
1753 hasReturns = true;
1754 return;
1755}
1756
1757void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1758 // Perform a bottom up traversal of all children.
1759 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1760 CI != E; ++CI)
1761 if (*CI) {
1762 RewriteTryReturnStmts(*CI);
1763 }
1764 if (isa<ReturnStmt>(S)) {
1765 SourceLocation startLoc = S->getLocStart();
1766 const char *startBuf = SM->getCharacterData(startLoc);
1767
1768 const char *semiBuf = strchr(startBuf, ';');
1769 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1770 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1771
1772 std::string buf;
1773 buf = "{ objc_exception_try_exit(&_stack); return";
1774
Benjamin Kramerd999b372010-02-14 14:14:16 +00001775 ReplaceText(startLoc, 6, buf);
1776 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001777 }
1778 return;
1779}
1780
1781void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1782 // Perform a bottom up traversal of all children.
1783 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1784 CI != E; ++CI)
1785 if (*CI) {
1786 RewriteSyncReturnStmts(*CI, syncExitBuf);
1787 }
1788 if (isa<ReturnStmt>(S)) {
1789 SourceLocation startLoc = S->getLocStart();
1790 const char *startBuf = SM->getCharacterData(startLoc);
1791
1792 const char *semiBuf = strchr(startBuf, ';');
1793 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1794 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1795
1796 std::string buf;
1797 buf = "{ objc_exception_try_exit(&_stack);";
1798 buf += syncExitBuf;
1799 buf += " return";
1800
Benjamin Kramerd999b372010-02-14 14:14:16 +00001801 ReplaceText(startLoc, 6, buf);
1802 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001803 }
1804 return;
1805}
1806
Steve Naroffb29b4272008-04-14 22:03:09 +00001807Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001808 // Get the start location and compute the semi location.
1809 SourceLocation startLoc = S->getLocStart();
1810 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001811
Steve Naroff75730982007-11-07 04:08:17 +00001812 assert((*startBuf == '@') && "bogus @try location");
1813
1814 std::string buf;
1815 // declare a new scope with two variables, _stack and _rethrow.
1816 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1817 buf += "int buf[18/*32-bit i386*/];\n";
1818 buf += "char *pointers[4];} _stack;\n";
1819 buf += "id volatile _rethrow = 0;\n";
1820 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001821 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001822
Benjamin Kramerd999b372010-02-14 14:14:16 +00001823 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Steve Naroff75730982007-11-07 04:08:17 +00001825 startLoc = S->getTryBody()->getLocEnd();
1826 startBuf = SM->getCharacterData(startLoc);
1827
1828 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Steve Naroff75730982007-11-07 04:08:17 +00001830 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001831 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1832 if (catchList) {
1833 startLoc = startLoc.getFileLocWithOffset(1);
1834 buf = " /* @catch begin */ else {\n";
1835 buf += " id _caught = objc_exception_extract(&_stack);\n";
1836 buf += " objc_exception_try_enter (&_stack);\n";
1837 buf += " if (_setjmp(_stack.buf))\n";
1838 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1839 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Benjamin Kramerd999b372010-02-14 14:14:16 +00001841 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001842 } else { /* no catch list */
1843 buf = "}\nelse {\n";
1844 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1845 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001846 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001847 }
Steve Naroff75730982007-11-07 04:08:17 +00001848 bool sawIdTypedCatch = false;
1849 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001850 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001851 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001852
Mike Stump1eb44332009-09-09 15:08:12 +00001853 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001854 buf = "if ("; // we are generating code for the first catch clause
1855 else
1856 buf = "else if (";
1857 startLoc = catchList->getLocStart();
1858 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Steve Naroff75730982007-11-07 04:08:17 +00001860 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Steve Naroff75730982007-11-07 04:08:17 +00001862 const char *lParenLoc = strchr(startBuf, '(');
1863
Steve Naroffbe4b3332008-02-01 22:08:12 +00001864 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001865 // Now rewrite the body...
1866 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001867 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1868 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001869 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1870 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001871 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Steve Naroffe12e6922008-02-01 20:02:07 +00001873 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001874 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001875 } else if (catchDecl) {
1876 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001877 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001878 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001879 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001880 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001881 } else if (t->isObjCObjectPointerType()) {
1882 QualType InterfaceTy = t->getPointeeType();
1883 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1884 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001885 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001886 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001887 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001888 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001889 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001890 }
1891 }
1892 // Now rewrite the body...
1893 lastCatchBody = catchList->getCatchBody();
1894 SourceLocation rParenLoc = catchList->getRParenLoc();
1895 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1896 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1897 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1898 assert((*rParenBuf == ')') && "bogus @catch paren location");
1899 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Mike Stump1eb44332009-09-09 15:08:12 +00001901 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001902 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001903 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001904 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001905 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001906 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001907 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001908 catchList = catchList->getNextCatchStmt();
1909 }
1910 // Complete the catch list...
1911 if (lastCatchBody) {
1912 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001913 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1914 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Steve Naroff378f47a2008-09-11 15:29:03 +00001916 // Insert the last (implicit) else clause *before* the right curly brace.
1917 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1918 buf = "} /* last catch end */\n";
1919 buf += "else {\n";
1920 buf += " _rethrow = _caught;\n";
1921 buf += " objc_exception_try_exit(&_stack);\n";
1922 buf += "} } /* @catch end */\n";
1923 if (!S->getFinallyStmt())
1924 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001925 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Steve Naroff75730982007-11-07 04:08:17 +00001927 // Set lastCurlyLoc
1928 lastCurlyLoc = lastCatchBody->getLocEnd();
1929 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001930 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001931 startLoc = finalStmt->getLocStart();
1932 startBuf = SM->getCharacterData(startLoc);
1933 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Benjamin Kramerd999b372010-02-14 14:14:16 +00001935 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Steve Naroff75730982007-11-07 04:08:17 +00001937 Stmt *body = finalStmt->getFinallyBody();
1938 SourceLocation startLoc = body->getLocStart();
1939 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001940 assert(*SM->getCharacterData(startLoc) == '{' &&
1941 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001942 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001943 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Steve Naroff75730982007-11-07 04:08:17 +00001945 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001946 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001947 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001948 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Steve Naroff75730982007-11-07 04:08:17 +00001950 // Set lastCurlyLoc
1951 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Steve Naroff8c565152008-12-05 17:03:39 +00001953 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001954 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001955 } else { /* no finally clause - make sure we synthesize an implicit one */
1956 buf = "{ /* implicit finally clause */\n";
1957 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1958 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1959 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001960 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001961
1962 // Now check for any return/continue/go statements within the @try.
1963 // The implicit finally clause won't called if the @try contains any
1964 // jump statements.
1965 bool hasReturns = false;
1966 HasReturnStmts(S->getTryBody(), hasReturns);
1967 if (hasReturns)
1968 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001969 }
1970 // Now emit the final closing curly brace...
1971 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001972 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001973 return 0;
1974}
1975
Steve Naroffb29b4272008-04-14 22:03:09 +00001976Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001977 return 0;
1978}
1979
Steve Naroffb29b4272008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001981 return 0;
1982}
1983
Mike Stump1eb44332009-09-09 15:08:12 +00001984// This can't be done with ReplaceStmt(S, ThrowExpr), since
1985// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001986// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001987Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001988 // Get the start location and compute the semi location.
1989 SourceLocation startLoc = S->getLocStart();
1990 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Steve Naroff2bd03922007-11-07 15:32:26 +00001992 assert((*startBuf == '@') && "bogus @throw location");
1993
1994 std::string buf;
1995 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001996 if (S->getThrowExpr())
1997 buf = "objc_exception_throw(";
1998 else // add an implicit argument
1999 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002001 // handle "@ throw" correctly.
2002 const char *wBuf = strchr(startBuf, 'w');
2003 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Steve Naroff2bd03922007-11-07 15:32:26 +00002006 const char *semiBuf = strchr(startBuf, ';');
2007 assert((*semiBuf == ';') && "@throw: can't find ';'");
2008 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002009 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002010 return 0;
2011}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002012
Steve Naroffb29b4272008-04-14 22:03:09 +00002013Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002014 // Create a new string expression.
2015 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002016 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002017 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002018 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2019 StrEncoding.length(), false,StrType,
2020 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002021 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Chris Lattner07506182007-11-30 22:53:43 +00002023 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002024 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002025 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002026}
2027
Steve Naroffb29b4272008-04-14 22:03:09 +00002028Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002029 if (!SelGetUidFunctionDecl)
2030 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002031 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2032 // Create a call to sel_registerName("selName").
2033 llvm::SmallVector<Expr*, 8> SelExprs;
2034 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002035 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002036 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002037 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002038 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002039 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2040 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002041 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002042 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002043 return SelExp;
2044}
2045
Steve Naroffb29b4272008-04-14 22:03:09 +00002046CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002047 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2048 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002049 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002050 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Steve Naroffebf2b562007-10-23 23:50:29 +00002052 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002053 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002054
Steve Naroffebf2b562007-10-23 23:50:29 +00002055 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002056 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00002057 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002058 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002059 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002060 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
John McCall183700f2009-09-21 23:43:11 +00002062 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002064 CallExpr *Exp =
2065 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2066 EndLoc);
2067 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002068}
2069
Steve Naroffd5255f52007-11-01 13:24:47 +00002070static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2071 const char *&startRef, const char *&endRef) {
2072 while (startBuf < endBuf) {
2073 if (*startBuf == '<')
2074 startRef = startBuf; // mark the start.
2075 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002076 if (startRef && *startRef == '<') {
2077 endRef = startBuf; // mark the end.
2078 return true;
2079 }
2080 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002081 }
2082 startBuf++;
2083 }
2084 return false;
2085}
2086
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002087static void scanToNextArgument(const char *&argRef) {
2088 int angle = 0;
2089 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2090 if (*argRef == '<')
2091 angle++;
2092 else if (*argRef == '>')
2093 angle--;
2094 argRef++;
2095 }
2096 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2097}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002098
Steve Naroffb29b4272008-04-14 22:03:09 +00002099bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002100 if (T->isObjCQualifiedIdType())
2101 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002102 if (const PointerType *PT = T->getAs<PointerType>()) {
2103 if (PT->getPointeeType()->isObjCQualifiedIdType())
2104 return true;
2105 }
2106 if (T->isObjCObjectPointerType()) {
2107 T = T->getPointeeType();
2108 return T->isObjCQualifiedInterfaceType();
2109 }
2110 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002111}
2112
Steve Naroff4f95b752008-07-29 18:15:38 +00002113void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2114 QualType Type = E->getType();
2115 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Steve Naroffcda658e2008-11-19 21:15:47 +00002118 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2119 Loc = ECE->getLParenLoc();
2120 EndLoc = ECE->getRParenLoc();
2121 } else {
2122 Loc = E->getLocStart();
2123 EndLoc = E->getLocEnd();
2124 }
2125 // This will defend against trying to rewrite synthesized expressions.
2126 if (Loc.isInvalid() || EndLoc.isInvalid())
2127 return;
2128
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002130 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 const char *startRef = 0, *endRef = 0;
2132 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2133 // Get the locations of the startRef, endRef.
2134 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2135 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2136 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002137 InsertText(LessLoc, "/*");
2138 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002139 }
2140 }
2141}
2142
Steve Naroffb29b4272008-04-14 22:03:09 +00002143void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002144 SourceLocation Loc;
2145 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002146 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002147 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2148 Loc = VD->getLocation();
2149 Type = VD->getType();
2150 }
2151 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2152 Loc = FD->getLocation();
2153 // Check for ObjC 'id' and class types that have been adorned with protocol
2154 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002155 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002157 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 if (!proto)
2159 return;
2160 Type = proto->getResultType();
2161 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002162 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2163 Loc = FD->getLocation();
2164 Type = FD->getType();
2165 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002166 else
2167 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002169 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Steve Naroffd5255f52007-11-01 13:24:47 +00002172 const char *endBuf = SM->getCharacterData(Loc);
2173 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002174 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 startBuf--; // scan backward (from the decl location) for return type.
2176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
2179 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2180 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2181 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002184 }
2185 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002186 if (!proto)
2187 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002188 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 const char *startBuf = SM->getCharacterData(Loc);
2190 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002191 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2192 if (needToScanForQualifiers(proto->getArgType(i))) {
2193 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffd5255f52007-11-01 13:24:47 +00002195 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002196 // scan forward (from the decl location) for argument types.
2197 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002198 const char *startRef = 0, *endRef = 0;
2199 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2200 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002202 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002203 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002204 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002205 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002206 InsertText(LessLoc, "/*");
2207 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002209 startBuf = ++endBuf;
2210 }
2211 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002212 // If the function name is derived from a macro expansion, then the
2213 // argument buffer will not follow the name. Need to speak with Chris.
2214 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002215 startBuf++; // scan forward (from the decl location) for argument types.
2216 startBuf++;
2217 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002218 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002219}
2220
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002221void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2222 QualType QT = ND->getType();
2223 const Type* TypePtr = QT->getAs<Type>();
2224 if (!isa<TypeOfExprType>(TypePtr))
2225 return;
2226 while (isa<TypeOfExprType>(TypePtr)) {
2227 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2228 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2229 TypePtr = QT->getAs<Type>();
2230 }
2231 // FIXME. This will not work for multiple declarators; as in:
2232 // __typeof__(a) b,c,d;
2233 std::string TypeAsString(QT.getAsString());
2234 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2235 const char *startBuf = SM->getCharacterData(DeclLoc);
2236 if (ND->getInit()) {
2237 std::string Name(ND->getNameAsString());
2238 TypeAsString += " " + Name + " = ";
2239 Expr *E = ND->getInit();
2240 SourceLocation startLoc;
2241 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2242 startLoc = ECE->getLParenLoc();
2243 else
2244 startLoc = E->getLocStart();
2245 startLoc = SM->getInstantiationLoc(startLoc);
2246 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002247 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002248 }
2249 else {
2250 SourceLocation X = ND->getLocEnd();
2251 X = SM->getInstantiationLoc(X);
2252 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002254 }
2255}
2256
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002258void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002259 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2260 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002261 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002262 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002263 &ArgTys[0], ArgTys.size(),
2264 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002265 false, false, 0, 0,
2266 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002267 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002268 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002269 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002270 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002271}
2272
Steve Naroffb29b4272008-04-14 22:03:09 +00002273void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002274 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002275 if (FD->getIdentifier() &&
2276 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002277 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002278 return;
2279 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002280 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002281}
2282
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002283static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2284 std::string TypeString(Type.getAsString());
2285 const char *argPtr = TypeString.c_str();
2286 if (!strchr(argPtr, '^')) {
2287 Str += TypeString;
2288 return;
2289 }
2290 while (*argPtr) {
2291 Str += (*argPtr == '^' ? '*' : *argPtr);
2292 argPtr++;
2293 }
2294}
2295
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002296// FIXME. Consolidate this routine with RewriteBlockPointerType.
2297static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2298 QualType Type = VD->getType();
2299 std::string TypeString(Type.getAsString());
2300 const char *argPtr = TypeString.c_str();
2301 int paren = 0;
2302 while (*argPtr) {
2303 switch (*argPtr) {
2304 case '(':
2305 Str += *argPtr;
2306 paren++;
2307 break;
2308 case ')':
2309 Str += *argPtr;
2310 paren--;
2311 break;
2312 case '^':
2313 Str += '*';
2314 if (paren == 1)
2315 Str += VD->getNameAsString();
2316 break;
2317 default:
2318 Str += *argPtr;
2319 break;
2320 }
2321 argPtr++;
2322 }
2323}
2324
2325
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002326void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2327 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2328 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2329 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2330 if (!proto)
2331 return;
2332 QualType Type = proto->getResultType();
2333 std::string FdStr = Type.getAsString();
2334 FdStr += " ";
2335 FdStr += FD->getNameAsCString();
2336 FdStr += "(";
2337 unsigned numArgs = proto->getNumArgs();
2338 for (unsigned i = 0; i < numArgs; i++) {
2339 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002340 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002341 if (i+1 < numArgs)
2342 FdStr += ", ";
2343 }
2344 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002345 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002346 CurFunctionDeclToDeclareForBlock = 0;
2347}
2348
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002350void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351 if (SuperContructorFunctionDecl)
2352 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002353 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002354 llvm::SmallVector<QualType, 16> ArgTys;
2355 QualType argT = Context->getObjCIdType();
2356 assert(!argT.isNull() && "Can't find 'id' type");
2357 ArgTys.push_back(argT);
2358 ArgTys.push_back(argT);
2359 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002361 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002362 false, false, 0, 0,
2363 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002364 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002365 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002366 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002367 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002368}
2369
Steve Naroff09b266e2007-10-30 23:14:51 +00002370// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002371void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002372 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2373 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002375 assert(!argT.isNull() && "Can't find 'id' type");
2376 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002380 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002381 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002382 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002383 false, false, 0, 0,
2384 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002385 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002386 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002387 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002388 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002389}
2390
Steve Naroff874e2322007-11-15 10:28:18 +00002391// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002392void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002393 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2394 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002395 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002396 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002397 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002398 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2399 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2400 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002401 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002402 assert(!argT.isNull() && "Can't find 'SEL' type");
2403 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002405 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002406 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002407 false, false, 0, 0,
2408 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002409 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002410 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002411 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002412 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002413}
2414
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002416void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002417 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2418 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002420 assert(!argT.isNull() && "Can't find 'id' type");
2421 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002422 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002423 assert(!argT.isNull() && "Can't find 'SEL' type");
2424 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002425 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002426 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002427 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002428 false, false, 0, 0,
2429 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002430 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002431 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002432 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002433 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002434}
2435
Mike Stump1eb44332009-09-09 15:08:12 +00002436// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002437// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002438void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002439 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002440 &Context->Idents.get("objc_msgSendSuper_stret");
2441 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002442 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002443 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002444 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002445 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2446 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2447 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002448 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002449 assert(!argT.isNull() && "Can't find 'SEL' type");
2450 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002451 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002452 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002453 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002454 false, false, 0, 0,
2455 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002456 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002457 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002458 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002459 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002460}
2461
Steve Naroff1284db82008-05-08 22:02:18 +00002462// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002463void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002464 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2465 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002467 assert(!argT.isNull() && "Can't find 'id' type");
2468 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002469 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002470 assert(!argT.isNull() && "Can't find 'SEL' type");
2471 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002472 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002473 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002474 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002475 false, false, 0, 0,
2476 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002477 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002478 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002479 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002480 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002481}
2482
Steve Naroff09b266e2007-10-30 23:14:51 +00002483// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002484void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002485 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2486 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002487 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002488 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002489 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002490 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002491 false, false, 0, 0,
2492 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002493 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002494 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002495 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002496 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002497}
2498
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002499// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2500void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2501 IdentifierInfo *getSuperClassIdent =
2502 &Context->Idents.get("class_getSuperclass");
2503 llvm::SmallVector<QualType, 16> ArgTys;
2504 ArgTys.push_back(Context->getObjCClassType());
2505 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2506 &ArgTys[0], ArgTys.size(),
2507 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002508 false, false, 0, 0,
2509 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002510 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2511 SourceLocation(),
2512 getSuperClassIdent, getClassType, 0,
2513 FunctionDecl::Extern, false);
2514}
2515
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002516// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002517void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002518 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2519 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002520 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002521 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002522 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002523 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002524 false, false, 0, 0,
2525 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002526 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002527 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002528 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002529 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002530}
2531
Steve Naroffb29b4272008-04-14 22:03:09 +00002532Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002533 QualType strType = getConstantStringStructType();
2534
2535 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002536
2537 std::string tmpName = InFileName;
2538 unsigned i;
2539 for (i=0; i < tmpName.length(); i++) {
2540 char c = tmpName.at(i);
2541 // replace any non alphanumeric characters with '_'.
2542 if (!isalpha(c) && (c < '0' || c > '9'))
2543 tmpName[i] = '_';
2544 }
2545 S += tmpName;
2546 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002547 S += utostr(NumObjCStringLiterals++);
2548
Steve Naroffba92b2e2008-03-27 22:29:16 +00002549 Preamble += "static __NSConstantStringImpl " + S;
2550 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2551 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002552 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002553 std::string prettyBufS;
2554 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002555 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2556 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002557 Preamble += prettyBuf.str();
2558 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002559 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002560
2561 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002562 &Context->Idents.get(S), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002563 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002564 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2565 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002566 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002567 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002568 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002569 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2570 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002571 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002572 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002573 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002574}
2575
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002576bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002577 // check if we are sending a message to 'super'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002578 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2579 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002580}
2581
2582// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002583QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002584 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002585 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002586 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002587 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002588 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Steve Naroff874e2322007-11-15 10:28:18 +00002590 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002591 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002592 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002593 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002594
Steve Naroff874e2322007-11-15 10:28:18 +00002595 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002596 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002597 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2598 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002599 FieldTypes[i], 0,
2600 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002601 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002602 }
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Douglas Gregor838db382010-02-11 01:19:42 +00002604 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002605 }
2606 return Context->getTagDeclType(SuperStructDecl);
2607}
2608
Steve Naroffb29b4272008-04-14 22:03:09 +00002609QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002611 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002612 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002613 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002614 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002618 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002619 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002620 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002621 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002622 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002623 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002624
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002625 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002626 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002627 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2628 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002629 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002630 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002632 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002633 }
2634
Douglas Gregor838db382010-02-11 01:19:42 +00002635 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002636 }
2637 return Context->getTagDeclType(ConstantStringDecl);
2638}
2639
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002640Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2641 SourceLocation StartLoc,
2642 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002643 if (!SelGetUidFunctionDecl)
2644 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002645 if (!MsgSendFunctionDecl)
2646 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002647 if (!MsgSendSuperFunctionDecl)
2648 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002649 if (!MsgSendStretFunctionDecl)
2650 SynthMsgSendStretFunctionDecl();
2651 if (!MsgSendSuperStretFunctionDecl)
2652 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002653 if (!MsgSendFpretFunctionDecl)
2654 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002655 if (!GetClassFunctionDecl)
2656 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002657 if (!GetSuperClassFunctionDecl)
2658 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002659 if (!GetMetaClassFunctionDecl)
2660 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Steve Naroff874e2322007-11-15 10:28:18 +00002662 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002663 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2664 // May need to use objc_msgSend_stret() as well.
2665 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002666 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2667 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002668 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002669 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002670 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002671 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002672 }
Mike Stump1eb44332009-09-09 15:08:12 +00002673
Steve Naroff934f2762007-10-24 22:48:43 +00002674 // Synthesize a call to objc_msgSend().
2675 llvm::SmallVector<Expr*, 8> MsgExprs;
2676 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002677
Steve Naroff934f2762007-10-24 22:48:43 +00002678 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2679 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002680 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2681 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002682 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002683 MsgSendFlavor = MsgSendSuperFunctionDecl;
2684 if (MsgSendStretFlavor)
2685 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2686 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002688 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002689
2690 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002692 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002693 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002694 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2695 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002696 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002697 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002698 SourceLocation()))
2699 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002700
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002701 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002702 llvm::SmallVector<Expr*, 8> ClsExprs;
2703 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002704 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002705 ClassDecl->getIdentifier()->getNameStart(),
2706 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbare013d682009-10-18 20:26:12 +00002707 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002708 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002709 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002710 ClsExprs.size(),
2711 StartLoc,
2712 EndLoc);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002713 // (Class)objc_getClass("CurrentClass")
2714 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2715 Context->getObjCClassType(),
2716 CastExpr::CK_Unknown, Cls);
2717 ClsExprs.clear();
2718 ClsExprs.push_back(ArgExpr);
2719 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2720 &ClsExprs[0], ClsExprs.size(),
2721 StartLoc, EndLoc);
2722
2723 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002724 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002725 InitExprs.push_back( // set 'super class', using class_getSuperclass().
John McCall9d125032010-01-15 18:39:57 +00002726 NoTypeInfoCStyleCastExpr(Context,
2727 Context->getObjCIdType(),
2728 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002729 // struct objc_super
2730 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002731 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Steve Naroff23f41272008-03-11 18:14:26 +00002733 if (LangOpts.Microsoft) {
2734 SynthSuperContructorFunctionDecl();
2735 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002736 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002737 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002738 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002739 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002740 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002741 // The code for super is a little tricky to prevent collision with
2742 // the structure definition in the header. The rewriter has it's own
2743 // internal definition (__rw_objc_super) that is uses. This is why
2744 // we need the cast below. For example:
2745 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2746 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002747 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002748 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002749 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002750 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2751 Context->getPointerType(superType),
2752 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002753 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002754 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002755 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2756 &InitExprs[0], InitExprs.size(),
2757 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002758 TypeSourceInfo *superTInfo
2759 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002760 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2761 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002762 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002763 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002764 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002765 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002766 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002767 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002768 } else {
2769 llvm::SmallVector<Expr*, 8> ClsExprs;
2770 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002771 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002772 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002773 clsName->getLength(),
2774 false, argType,
2775 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002776 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002777 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002778 ClsExprs.size(),
2779 StartLoc, EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002780 MsgExprs.push_back(Cls);
2781 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002782 } else { // instance message.
2783 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002784
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002785 if (isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002786 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002787 if (MsgSendStretFlavor)
2788 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002789 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002790 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroff874e2322007-11-15 10:28:18 +00002791 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002792
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002793 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002794 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2795 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002796 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002797 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002798 SourceLocation()))
2799 ); // set the 'receiver'.
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002800
2801 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff874e2322007-11-15 10:28:18 +00002802 llvm::SmallVector<Expr*, 8> ClsExprs;
2803 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002804 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002805 ClassDecl->getIdentifier()->getNameStart(),
2806 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbare013d682009-10-18 20:26:12 +00002807 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002808 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002809 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002810 ClsExprs.size(),
2811 StartLoc, EndLoc);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002812 // (Class)objc_getClass("CurrentClass")
2813 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2814 Context->getObjCClassType(),
2815 CastExpr::CK_Unknown, Cls);
2816 ClsExprs.clear();
2817 ClsExprs.push_back(ArgExpr);
2818 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2819 &ClsExprs[0], ClsExprs.size(),
2820 StartLoc, EndLoc);
2821
2822 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Fariborz Jahanian71274312007-12-05 17:29:46 +00002823 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002824 InitExprs.push_back(
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002825 // set 'super class', using class_getSuperclass().
John McCall9d125032010-01-15 18:39:57 +00002826 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2827 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002828 // struct objc_super
2829 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002830 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002831
Steve Naroffc0a123c2008-03-11 17:37:02 +00002832 if (LangOpts.Microsoft) {
2833 SynthSuperContructorFunctionDecl();
2834 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002835 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002836 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002837 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002838 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002839 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002840 // The code for super is a little tricky to prevent collision with
2841 // the structure definition in the header. The rewriter has it's own
2842 // internal definition (__rw_objc_super) that is uses. This is why
2843 // we need the cast below. For example:
2844 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2845 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002846 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002847 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002848 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002849 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2850 Context->getPointerType(superType),
2851 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002852 } else {
2853 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002854 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2855 &InitExprs[0], InitExprs.size(),
2856 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002857 TypeSourceInfo *superTInfo
2858 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002859 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2860 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002861 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002862 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002863 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002864 // Remove all type-casts because it may contain objc-style types; e.g.
2865 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002866 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002867 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002868 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2869 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002870 MsgExprs.push_back(recExpr);
2871 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002872 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002873 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002874 llvm::SmallVector<Expr*, 8> SelExprs;
2875 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002876 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002877 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002878 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002879 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002880 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002881 &SelExprs[0], SelExprs.size(),
2882 StartLoc,
2883 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002884 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002885
Steve Naroff934f2762007-10-24 22:48:43 +00002886 // Now push any user supplied arguments.
2887 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002888 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002889 // Make all implicit casts explicit...ICE comes in handy:-)
2890 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2891 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002892 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002893 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002894 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002895 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2896 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002897 }
2898 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002899 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002901 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002902 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002903 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2904 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002905 }
Mike Stump1eb44332009-09-09 15:08:12 +00002906 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002907 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002908 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2909 // out the argument in the original expression (since we aren't deleting
2910 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2911 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002912 }
Steve Naroffab972d32007-11-04 22:37:50 +00002913 // Generate the funky cast.
2914 CastExpr *cast;
2915 llvm::SmallVector<QualType, 8> ArgTypes;
2916 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002917
Steve Naroffab972d32007-11-04 22:37:50 +00002918 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002919 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2920 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2921 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002922 ArgTypes.push_back(Context->getObjCIdType());
2923 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002924 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002925 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002926 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2927 E = OMD->param_end(); PI != E; ++PI) {
2928 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002929 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002930 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002931 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002932 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002933 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002934 t = Context->getPointerType(BPT->getPointeeType());
2935 }
Steve Naroff352336b2007-11-05 14:36:37 +00002936 ArgTypes.push_back(t);
2937 }
Chris Lattner89951a82009-02-20 18:43:26 +00002938 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2939 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002940 if (isTopLevelBlockPointerType(returnType)) {
2941 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2942 returnType = Context->getPointerType(BPT->getPointeeType());
2943 }
Steve Naroffab972d32007-11-04 22:37:50 +00002944 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002945 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002946 }
2947 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002948 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002949
Steve Naroffab972d32007-11-04 22:37:50 +00002950 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002951 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002952 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002953
Mike Stump1eb44332009-09-09 15:08:12 +00002954 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002955 // If we don't do this cast, we get the following bizarre warning/note:
2956 // xx.m:13: warning: function called through a non-compatible type
2957 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002958 cast = NoTypeInfoCStyleCastExpr(Context,
2959 Context->getPointerType(Context->VoidTy),
2960 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Steve Naroffab972d32007-11-04 22:37:50 +00002962 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002963 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002964 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002965 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002966 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002967 false, false, 0, 0,
2968 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00002969 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002970 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2971 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002972
2973 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002974 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002975
John McCall183700f2009-09-21 23:43:11 +00002976 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002977 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002978 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002979 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002980 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002981 if (MsgSendStretFlavor) {
2982 // We have the method which returns a struct/union. Must also generate
2983 // call to objc_msgSend_stret and hang both varieties on a conditional
2984 // expression which dictate which one to envoke depending on size of
2985 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002987 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002988 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002989 SourceLocation());
2990 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002991 cast = NoTypeInfoCStyleCastExpr(Context,
2992 Context->getPointerType(Context->VoidTy),
2993 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002994 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002995 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002996 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002997 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002998 false, false, 0, 0,
2999 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003000 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003001 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3002 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003004 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003005 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003006
John McCall183700f2009-09-21 23:43:11 +00003007 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003008 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003009 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003010 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003011
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003012 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003013 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003014 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003015 Context->getSizeType(),
3016 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003017 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3018 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3019 // For X86 it is more complicated and some kind of target specific routine
3020 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003021 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003022 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00003023 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003024 Context->IntTy,
3025 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003026 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3027 BinaryOperator::LE,
3028 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003029 SourceLocation());
3030 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003031 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003032 new (Context) ConditionalOperator(lessThanExpr,
3033 SourceLocation(), CE,
3034 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003035 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003036 }
Mike Stump1eb44332009-09-09 15:08:12 +00003037 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003038 return ReplacingStmt;
3039}
3040
Steve Naroffb29b4272008-04-14 22:03:09 +00003041Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003042 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3043 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Steve Naroff934f2762007-10-24 22:48:43 +00003045 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003046 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003047
3048 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003049 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003050}
3051
Steve Naroff621edce2009-04-29 16:37:50 +00003052// typedef struct objc_object Protocol;
3053QualType RewriteObjC::getProtocolType() {
3054 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003055 TypeSourceInfo *TInfo
3056 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003057 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003058 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003059 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003060 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003061 }
3062 return Context->getTypeDeclType(ProtocolTypeDecl);
3063}
3064
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003065/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003066/// a synthesized/forward data reference (to the protocol's metadata).
3067/// The forward references (and metadata) are generated in
3068/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003069Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003070 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3071 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003072 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00003073 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00003074 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3075 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3076 Context->getPointerType(DRE->getType()),
3077 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003078 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3079 CastExpr::CK_Unknown,
3080 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003081 ReplaceStmt(Exp, castExpr);
3082 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003083 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003084 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003086}
3087
Mike Stump1eb44332009-09-09 15:08:12 +00003088bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003089 const char *endBuf) {
3090 while (startBuf < endBuf) {
3091 if (*startBuf == '#') {
3092 // Skip whitespace.
3093 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3094 ;
3095 if (!strncmp(startBuf, "if", strlen("if")) ||
3096 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3097 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3098 !strncmp(startBuf, "define", strlen("define")) ||
3099 !strncmp(startBuf, "undef", strlen("undef")) ||
3100 !strncmp(startBuf, "else", strlen("else")) ||
3101 !strncmp(startBuf, "elif", strlen("elif")) ||
3102 !strncmp(startBuf, "endif", strlen("endif")) ||
3103 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3104 !strncmp(startBuf, "include", strlen("include")) ||
3105 !strncmp(startBuf, "import", strlen("import")) ||
3106 !strncmp(startBuf, "include_next", strlen("include_next")))
3107 return true;
3108 }
3109 startBuf++;
3110 }
3111 return false;
3112}
3113
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003114/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003115/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003116void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003117 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003119 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003120 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003121 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003122 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003123 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003124 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003125 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003126 SourceLocation LocStart = CDecl->getLocStart();
3127 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Steve Narofffea763e82007-11-14 19:25:57 +00003129 const char *startBuf = SM->getCharacterData(LocStart);
3130 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003132 // If no ivars and no root or if its root, directly or indirectly,
3133 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003134 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3135 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003136 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003137 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003138 return;
3139 }
Mike Stump1eb44332009-09-09 15:08:12 +00003140
3141 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003142 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003143 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003144 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003145 if (LangOpts.Microsoft)
3146 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003147
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003148 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003149 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003150 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003151 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003152 // If the buffer contains preprocessor directives, we do more fine-grained
3153 // rewrites. This is intended to fix code that looks like (which occurs in
3154 // NSURL.h, for example):
3155 //
3156 // #ifdef XYZ
3157 // @interface Foo : NSObject
3158 // #else
3159 // @interface FooBar : NSObject
3160 // #endif
3161 // {
3162 // int i;
3163 // }
3164 // @end
3165 //
3166 // This clause is segregated to avoid breaking the common case.
3167 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003168 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003169 CDecl->getClassLoc();
3170 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003171 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003172
Chris Lattnercafeb352009-02-20 18:18:36 +00003173 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003174 // advance to the end of the referenced protocols.
3175 while (endHeader < cursor && *endHeader != '>') endHeader++;
3176 endHeader++;
3177 }
3178 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003179 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003180 } else {
3181 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003182 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003183 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003184 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003185 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003186 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003187 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003188 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003189 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Steve Narofffea763e82007-11-14 19:25:57 +00003191 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003192 SourceLocation OnePastCurly =
3193 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003194 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003195 }
3196 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Steve Narofffea763e82007-11-14 19:25:57 +00003198 // Now comment out any visibility specifiers.
3199 while (cursor < endBuf) {
3200 if (*cursor == '@') {
3201 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003202 // Skip whitespace.
3203 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3204 /*scan*/;
3205
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003206 // FIXME: presence of @public, etc. inside comment results in
3207 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003208 if (!strncmp(cursor, "public", strlen("public")) ||
3209 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003210 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003211 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003212 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003213 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003214 // FIXME: If there are cases where '<' is used in ivar declaration part
3215 // of user code, then scan the ivar list and use needToScanForQualifiers
3216 // for type checking.
3217 else if (*cursor == '<') {
3218 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003219 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003220 cursor = strchr(cursor, '>');
3221 cursor++;
3222 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003223 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003224 } else if (*cursor == '^') { // rewrite block specifier.
3225 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003226 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003227 }
Steve Narofffea763e82007-11-14 19:25:57 +00003228 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003229 }
Steve Narofffea763e82007-11-14 19:25:57 +00003230 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003231 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003232 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003233 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003234 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003235 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003236 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003237 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003238 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003239 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003240 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003241 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003242 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003243 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003244}
3245
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003246// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003247/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003248template<typename MethodIterator>
3249void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3250 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003251 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003252 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003253 const char *ClassName,
3254 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003255 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003257 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003258 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003259 SEL _cmd;
3260 char *method_types;
3261 void *_imp;
3262 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003263 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003264 Result += "\nstruct _objc_method {\n";
3265 Result += "\tSEL _cmd;\n";
3266 Result += "\tchar *method_types;\n";
3267 Result += "\tvoid *_imp;\n";
3268 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003269
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003270 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003273 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003274
Steve Naroff946a6932008-03-11 00:12:29 +00003275 /* struct {
3276 struct _objc_method_list *next_method;
3277 int method_count;
3278 struct _objc_method method_list[];
3279 }
3280 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003281 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003282 Result += "\nstatic struct {\n";
3283 Result += "\tstruct _objc_method_list *next_method;\n";
3284 Result += "\tint method_count;\n";
3285 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003286 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003287 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003288 Result += prefix;
3289 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3290 Result += "_METHODS_";
3291 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003292 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003293 Result += IsInstanceMethod ? "inst" : "cls";
3294 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003295 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003296
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003297 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003298 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003299 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003301 Result += "\", \"";
3302 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003303 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003304 Result += MethodInternalNames[*MethodBegin];
3305 Result += "}\n";
3306 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3307 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003308 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003309 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003310 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003311 Result += "\", \"";
3312 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003313 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003314 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003315 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003316 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003317 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003318}
3319
Steve Naroff621edce2009-04-29 16:37:50 +00003320/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003321void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003322RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3323 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003324 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003325
3326 // Output struct protocol_methods holder of method selector and type.
3327 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3328 /* struct protocol_methods {
3329 SEL _cmd;
3330 char *method_types;
3331 }
3332 */
3333 Result += "\nstruct _protocol_methods {\n";
3334 Result += "\tstruct objc_selector *_cmd;\n";
3335 Result += "\tchar *method_types;\n";
3336 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Steve Naroff621edce2009-04-29 16:37:50 +00003338 objc_protocol_methods = true;
3339 }
3340 // Do not synthesize the protocol more than once.
3341 if (ObjCSynthesizedProtocols.count(PDecl))
3342 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003344 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3345 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3346 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003347 /* struct _objc_protocol_method_list {
3348 int protocol_method_count;
3349 struct protocol_methods protocols[];
3350 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003351 */
Steve Naroff621edce2009-04-29 16:37:50 +00003352 Result += "\nstatic struct {\n";
3353 Result += "\tint protocol_method_count;\n";
3354 Result += "\tstruct _protocol_methods protocol_methods[";
3355 Result += utostr(NumMethods);
3356 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3357 Result += PDecl->getNameAsString();
3358 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3359 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Steve Naroff621edce2009-04-29 16:37:50 +00003361 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003362 for (ObjCProtocolDecl::instmeth_iterator
3363 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003364 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003365 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003366 Result += "\t ,{{(struct objc_selector *)\"";
3367 else
3368 Result += "\t ,{(struct objc_selector *)\"";
3369 Result += (*I)->getSelector().getAsString().c_str();
3370 std::string MethodTypeString;
3371 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3372 Result += "\", \"";
3373 Result += MethodTypeString;
3374 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003375 }
Steve Naroff621edce2009-04-29 16:37:50 +00003376 Result += "\t }\n};\n";
3377 }
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Steve Naroff621edce2009-04-29 16:37:50 +00003379 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003380 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3381 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003382 if (NumMethods > 0) {
3383 /* struct _objc_protocol_method_list {
3384 int protocol_method_count;
3385 struct protocol_methods protocols[];
3386 }
3387 */
3388 Result += "\nstatic struct {\n";
3389 Result += "\tint protocol_method_count;\n";
3390 Result += "\tstruct _protocol_methods protocol_methods[";
3391 Result += utostr(NumMethods);
3392 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3393 Result += PDecl->getNameAsString();
3394 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3395 "{\n\t";
3396 Result += utostr(NumMethods);
3397 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003398
Steve Naroff621edce2009-04-29 16:37:50 +00003399 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003400 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003401 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003402 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003403 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003404 Result += "\t ,{{(struct objc_selector *)\"";
3405 else
3406 Result += "\t ,{(struct objc_selector *)\"";
3407 Result += (*I)->getSelector().getAsString().c_str();
3408 std::string MethodTypeString;
3409 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3410 Result += "\", \"";
3411 Result += MethodTypeString;
3412 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003413 }
Steve Naroff621edce2009-04-29 16:37:50 +00003414 Result += "\t }\n};\n";
3415 }
3416
3417 // Output:
3418 /* struct _objc_protocol {
3419 // Objective-C 1.0 extensions
3420 struct _objc_protocol_extension *isa;
3421 char *protocol_name;
3422 struct _objc_protocol **protocol_list;
3423 struct _objc_protocol_method_list *instance_methods;
3424 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003425 };
Steve Naroff621edce2009-04-29 16:37:50 +00003426 */
3427 static bool objc_protocol = false;
3428 if (!objc_protocol) {
3429 Result += "\nstruct _objc_protocol {\n";
3430 Result += "\tstruct _objc_protocol_extension *isa;\n";
3431 Result += "\tchar *protocol_name;\n";
3432 Result += "\tstruct _objc_protocol **protocol_list;\n";
3433 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3434 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003435 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Steve Naroff621edce2009-04-29 16:37:50 +00003437 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003438 }
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Steve Naroff621edce2009-04-29 16:37:50 +00003440 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3441 Result += PDecl->getNameAsString();
3442 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3443 "{\n\t0, \"";
3444 Result += PDecl->getNameAsString();
3445 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003446 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003447 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3448 Result += PDecl->getNameAsString();
3449 Result += ", ";
3450 }
3451 else
3452 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003453 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003454 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3455 Result += PDecl->getNameAsString();
3456 Result += "\n";
3457 }
3458 else
3459 Result += "0\n";
3460 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Steve Naroff621edce2009-04-29 16:37:50 +00003462 // Mark this protocol as having been generated.
3463 if (!ObjCSynthesizedProtocols.insert(PDecl))
3464 assert(false && "protocol already synthesized");
3465
3466}
3467
3468void RewriteObjC::
3469RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3470 const char *prefix, const char *ClassName,
3471 std::string &Result) {
3472 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Steve Naroff621edce2009-04-29 16:37:50 +00003474 for (unsigned i = 0; i != Protocols.size(); i++)
3475 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3476
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003477 // Output the top lovel protocol meta-data for the class.
3478 /* struct _objc_protocol_list {
3479 struct _objc_protocol_list *next;
3480 int protocol_count;
3481 struct _objc_protocol *class_protocols[];
3482 }
3483 */
3484 Result += "\nstatic struct {\n";
3485 Result += "\tstruct _objc_protocol_list *next;\n";
3486 Result += "\tint protocol_count;\n";
3487 Result += "\tstruct _objc_protocol *class_protocols[";
3488 Result += utostr(Protocols.size());
3489 Result += "];\n} _OBJC_";
3490 Result += prefix;
3491 Result += "_PROTOCOLS_";
3492 Result += ClassName;
3493 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3494 "{\n\t0, ";
3495 Result += utostr(Protocols.size());
3496 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003498 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003499 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003500 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003502 for (unsigned i = 1; i != Protocols.size(); i++) {
3503 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003504 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003505 Result += "\n";
3506 }
3507 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003508}
3509
Steve Naroff621edce2009-04-29 16:37:50 +00003510
Mike Stump1eb44332009-09-09 15:08:12 +00003511/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003512/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003513void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003514 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003515 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003516 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003517 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003518 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003519 CDecl = CDecl->getNextClassCategory())
3520 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3521 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003522
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003523 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003524 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003525 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003527 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003528 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003529 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003530
3531 // If any of our property implementations have associated getters or
3532 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003533 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3534 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003535 Prop != PropEnd; ++Prop) {
3536 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3537 continue;
3538 if (!(*Prop)->getPropertyIvarDecl())
3539 continue;
3540 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3541 if (!PD)
3542 continue;
3543 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3544 InstanceMethods.push_back(Getter);
3545 if (PD->isReadOnly())
3546 continue;
3547 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3548 InstanceMethods.push_back(Setter);
3549 }
3550 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003551 true, "CATEGORY_", FullCategoryName.c_str(),
3552 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003554 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003555 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003556 false, "CATEGORY_", FullCategoryName.c_str(),
3557 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003559 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003560 // Null CDecl is case of a category implementation with no category interface
3561 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003562 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3563 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003564 /* struct _objc_category {
3565 char *category_name;
3566 char *class_name;
3567 struct _objc_method_list *instance_methods;
3568 struct _objc_method_list *class_methods;
3569 struct _objc_protocol_list *protocols;
3570 // Objective-C 1.0 extensions
3571 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003572 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003573 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003574 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003575 */
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003577 static bool objc_category = false;
3578 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003579 Result += "\nstruct _objc_category {\n";
3580 Result += "\tchar *category_name;\n";
3581 Result += "\tchar *class_name;\n";
3582 Result += "\tstruct _objc_method_list *instance_methods;\n";
3583 Result += "\tstruct _objc_method_list *class_methods;\n";
3584 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003585 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003586 Result += "\tstruct _objc_property_list *instance_properties;\n";
3587 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003588 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003589 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003590 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3591 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003592 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003593 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003595 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003597
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003598 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003599 Result += "\t, (struct _objc_method_list *)"
3600 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3601 Result += FullCategoryName;
3602 Result += "\n";
3603 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003604 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003605 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003606 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003607 Result += "\t, (struct _objc_method_list *)"
3608 "&_OBJC_CATEGORY_CLASS_METHODS_";
3609 Result += FullCategoryName;
3610 Result += "\n";
3611 }
3612 else
3613 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003614
Chris Lattnercafeb352009-02-20 18:18:36 +00003615 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003616 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003617 Result += FullCategoryName;
3618 Result += "\n";
3619 }
3620 else
3621 Result += "\t, 0\n";
3622 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003623}
3624
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003625/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3626/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003627void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003628 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003629 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003630 if (ivar->isBitField()) {
3631 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3632 // place all bitfields at offset 0.
3633 Result += "0";
3634 } else {
3635 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003636 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003637 if (LangOpts.Microsoft)
3638 Result += "_IMPL";
3639 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003640 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003641 Result += ")";
3642 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003643}
3644
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003645//===----------------------------------------------------------------------===//
3646// Meta Data Emission
3647//===----------------------------------------------------------------------===//
3648
Steve Naroffb29b4272008-04-14 22:03:09 +00003649void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003650 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003651 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003653 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003654 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003655 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003656 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003657 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003658 }
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Chris Lattnerbe6df082007-12-12 07:56:42 +00003660 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003661 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003662 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003663 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003664 if (NumIvars > 0) {
3665 static bool objc_ivar = false;
3666 if (!objc_ivar) {
3667 /* struct _objc_ivar {
3668 char *ivar_name;
3669 char *ivar_type;
3670 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003671 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003672 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003673 Result += "\nstruct _objc_ivar {\n";
3674 Result += "\tchar *ivar_name;\n";
3675 Result += "\tchar *ivar_type;\n";
3676 Result += "\tint ivar_offset;\n";
3677 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003678
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003679 objc_ivar = true;
3680 }
3681
Steve Naroff946a6932008-03-11 00:12:29 +00003682 /* struct {
3683 int ivar_count;
3684 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003685 };
Steve Naroff946a6932008-03-11 00:12:29 +00003686 */
Mike Stump1eb44332009-09-09 15:08:12 +00003687 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003688 Result += "\tint ivar_count;\n";
3689 Result += "\tstruct _objc_ivar ivar_list[";
3690 Result += utostr(NumIvars);
3691 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003693 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003694 "{\n\t";
3695 Result += utostr(NumIvars);
3696 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003698 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003699 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003700 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003701 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003702 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003703 IV != IVEnd; ++IV)
3704 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003705 IVI = IDecl->ivar_begin();
3706 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003707 } else {
3708 IVI = CDecl->ivar_begin();
3709 IVE = CDecl->ivar_end();
3710 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003711 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003712 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003713 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003714 std::string TmpString, StrEncoding;
3715 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3716 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003717 Result += StrEncoding;
3718 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003719 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003720 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003721 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003722 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003723 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003724 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003725 std::string TmpString, StrEncoding;
3726 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3727 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003728 Result += StrEncoding;
3729 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003730 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003731 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003732 }
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003734 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003737 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003738 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003739 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003740
3741 // If any of our property implementations have associated getters or
3742 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003743 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3744 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003745 Prop != PropEnd; ++Prop) {
3746 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3747 continue;
3748 if (!(*Prop)->getPropertyIvarDecl())
3749 continue;
3750 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3751 if (!PD)
3752 continue;
3753 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3754 InstanceMethods.push_back(Getter);
3755 if (PD->isReadOnly())
3756 continue;
3757 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3758 InstanceMethods.push_back(Setter);
3759 }
3760 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003761 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003764 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003765 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003767 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003768 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3769 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003771 // Declaration of class/meta-class metadata
3772 /* struct _objc_class {
3773 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003774 const char *super_class_name;
3775 char *name;
3776 long version;
3777 long info;
3778 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003779 struct _objc_ivar_list *ivars;
3780 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003781 struct objc_cache *cache;
3782 struct objc_protocol_list *protocols;
3783 const char *ivar_layout;
3784 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003785 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003786 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003787 static bool objc_class = false;
3788 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003789 Result += "\nstruct _objc_class {\n";
3790 Result += "\tstruct _objc_class *isa;\n";
3791 Result += "\tconst char *super_class_name;\n";
3792 Result += "\tchar *name;\n";
3793 Result += "\tlong version;\n";
3794 Result += "\tlong info;\n";
3795 Result += "\tlong instance_size;\n";
3796 Result += "\tstruct _objc_ivar_list *ivars;\n";
3797 Result += "\tstruct _objc_method_list *methods;\n";
3798 Result += "\tstruct objc_cache *cache;\n";
3799 Result += "\tstruct _objc_protocol_list *protocols;\n";
3800 Result += "\tconst char *ivar_layout;\n";
3801 Result += "\tstruct _objc_class_ext *ext;\n";
3802 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003803 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003806 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003807 ObjCInterfaceDecl *RootClass = 0;
3808 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003809 while (SuperClass) {
3810 RootClass = SuperClass;
3811 SuperClass = SuperClass->getSuperClass();
3812 }
3813 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003814
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003815 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003816 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003817 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003818 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003819 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003820 Result += "\"";
3821
3822 if (SuperClass) {
3823 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003824 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003825 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003826 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003827 Result += "\"";
3828 }
3829 else {
3830 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003831 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003832 Result += "\"";
3833 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003834 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003835 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003836 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003837 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003838 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003839 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003840 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003841 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003842 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003843 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003844 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003845 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003846 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003847 Result += ",0,0\n";
3848 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003849 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003850 Result += "\t,0,0,0,0\n";
3851 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003853 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003854 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003855 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003856 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003857 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003858 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003859 if (SuperClass) {
3860 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003861 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003862 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003863 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003864 Result += "\"";
3865 }
3866 else {
3867 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003868 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003869 Result += "\"";
3870 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003871 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003872 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003873 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003874 Result += ",0";
3875 else {
3876 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003877 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003878 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003879 if (LangOpts.Microsoft)
3880 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003881 Result += ")";
3882 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003883 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003884 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003885 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003886 Result += "\n\t";
3887 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003888 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003889 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003890 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003891 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003892 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003893 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003894 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003895 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003896 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003897 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003898 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003899 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003900 Result += ", 0,0\n";
3901 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003902 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003903 Result += ",0,0,0\n";
3904 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003905}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003906
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003907/// RewriteImplementations - This routine rewrites all method implementations
3908/// and emits meta-data.
3909
Steve Narofface66252008-11-13 20:07:04 +00003910void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003911 int ClsDefCount = ClassImplementation.size();
3912 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003913
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003914 // Rewrite implemented methods
3915 for (int i = 0; i < ClsDefCount; i++)
3916 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003918 for (int i = 0; i < CatDefCount; i++)
3919 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003920}
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Steve Narofface66252008-11-13 20:07:04 +00003922void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3923 int ClsDefCount = ClassImplementation.size();
3924 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003925
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003926 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003927 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003928 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003930 // For each implemented category, write out all its meta data.
3931 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003932 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003933
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003934 // Write objc_symtab metadata
3935 /*
3936 struct _objc_symtab
3937 {
3938 long sel_ref_cnt;
3939 SEL *refs;
3940 short cls_def_cnt;
3941 short cat_def_cnt;
3942 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003943 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003944 */
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003946 Result += "\nstruct _objc_symtab {\n";
3947 Result += "\tlong sel_ref_cnt;\n";
3948 Result += "\tSEL *refs;\n";
3949 Result += "\tshort cls_def_cnt;\n";
3950 Result += "\tshort cat_def_cnt;\n";
3951 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3952 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003954 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003955 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003956 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 + ", " + utostr(CatDefCount) + "\n";
3958 for (int i = 0; i < ClsDefCount; i++) {
3959 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003960 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 Result += "\n";
3962 }
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003964 for (int i = 0; i < CatDefCount; i++) {
3965 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003966 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003967 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003968 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003969 Result += "\n";
3970 }
Mike Stump1eb44332009-09-09 15:08:12 +00003971
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003972 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003974 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003976 /*
3977 struct _objc_module {
3978 long version;
3979 long size;
3980 const char *name;
3981 struct _objc_symtab *symtab;
3982 }
3983 */
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003985 Result += "\nstruct _objc_module {\n";
3986 Result += "\tlong version;\n";
3987 Result += "\tlong size;\n";
3988 Result += "\tconst char *name;\n";
3989 Result += "\tstruct _objc_symtab *symtab;\n";
3990 Result += "};\n\n";
3991 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003992 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003993 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003994 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003996
3997 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003998 if (ProtocolExprDecls.size()) {
3999 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4000 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004001 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004002 E = ProtocolExprDecls.end(); I != E; ++I) {
4003 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4004 Result += (*I)->getNameAsString();
4005 Result += " = &_OBJC_PROTOCOL_";
4006 Result += (*I)->getNameAsString();
4007 Result += ";\n";
4008 }
4009 Result += "#pragma data_seg(pop)\n\n";
4010 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004011 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004012 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004013 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4014 Result += "&_OBJC_MODULES;\n";
4015 Result += "#pragma data_seg(pop)\n\n";
4016 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004017}
Chris Lattner311ff022007-10-16 22:36:42 +00004018
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004019void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4020 const std::string &Name,
4021 ValueDecl *VD) {
4022 assert(BlockByRefDeclNo.count(VD) &&
4023 "RewriteByRefString: ByRef decl missing");
4024 ResultStr += "struct __Block_byref_" + Name +
4025 "_" + utostr(BlockByRefDeclNo[VD]) ;
4026}
4027
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004028static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4029 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4030 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4031 return false;
4032}
4033
Steve Naroff54055232008-10-27 17:20:55 +00004034std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4035 const char *funcName,
4036 std::string Tag) {
4037 const FunctionType *AFT = CE->getFunctionType();
4038 QualType RT = AFT->getResultType();
4039 std::string StructRef = "struct " + Tag;
4040 std::string S = "static " + RT.getAsString() + " __" +
4041 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004042
Steve Naroff54055232008-10-27 17:20:55 +00004043 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Douglas Gregor72564e72009-02-26 23:50:07 +00004045 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004046 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004047 // block (to reference imported block decl refs).
4048 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004049 } else if (BD->param_empty()) {
4050 S += "(" + StructRef + " *__cself)";
4051 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004052 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004053 assert(FT && "SynthesizeBlockFunc: No function proto");
4054 S += '(';
4055 // first add the implicit argument.
4056 S += StructRef + " *__cself, ";
4057 std::string ParamStr;
4058 for (BlockDecl::param_iterator AI = BD->param_begin(),
4059 E = BD->param_end(); AI != E; ++AI) {
4060 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004061 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004062 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004063 S += ParamStr;
4064 }
4065 if (FT->isVariadic()) {
4066 if (!BD->param_empty()) S += ", ";
4067 S += "...";
4068 }
4069 S += ')';
4070 }
4071 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004072
Steve Naroff54055232008-10-27 17:20:55 +00004073 // Create local declarations to avoid rewriting all closure decl ref exprs.
4074 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004075 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004076 E = BlockByRefDecls.end(); I != E; ++I) {
4077 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004078 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004079 std::string TypeString;
4080 RewriteByRefString(TypeString, Name, (*I));
4081 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004082 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004083 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004084 }
Steve Naroff54055232008-10-27 17:20:55 +00004085 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004086 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004087 E = BlockByCopyDecls.end(); I != E; ++I) {
4088 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004089 // Handle nested closure invocation. For example:
4090 //
4091 // void (^myImportedClosure)(void);
4092 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004093 //
Steve Naroff54055232008-10-27 17:20:55 +00004094 // void (^anotherClosure)(void);
4095 // anotherClosure = ^(void) {
4096 // myImportedClosure(); // import and invoke the closure
4097 // };
4098 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004099 if (isTopLevelBlockPointerType((*I)->getType())) {
4100 RewriteBlockPointerTypeVariable(S, (*I));
4101 S += " = (";
4102 RewriteBlockPointerType(S, (*I)->getType());
4103 S += ")";
4104 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4105 }
4106 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004107 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004108 QualType QT = (*I)->getType();
4109 if (HasLocalVariableExternalStorage(*I))
4110 QT = Context->getPointerType(QT);
4111 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004112 S += Name + " = __cself->" +
4113 (*I)->getNameAsString() + "; // bound by copy\n";
4114 }
Steve Naroff54055232008-10-27 17:20:55 +00004115 }
4116 std::string RewrittenStr = RewrittenBlockExprs[CE];
4117 const char *cstr = RewrittenStr.c_str();
4118 while (*cstr++ != '{') ;
4119 S += cstr;
4120 S += "\n";
4121 return S;
4122}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004123
Steve Naroff54055232008-10-27 17:20:55 +00004124std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4125 const char *funcName,
4126 std::string Tag) {
4127 std::string StructRef = "struct " + Tag;
4128 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Steve Naroff54055232008-10-27 17:20:55 +00004130 S += funcName;
4131 S += "_block_copy_" + utostr(i);
4132 S += "(" + StructRef;
4133 S += "*dst, " + StructRef;
4134 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004135 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004136 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004137 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004138 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004139 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004140 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004141 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004142 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004143 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004144 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004145 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004146 S += "}\n";
4147
Steve Naroff54055232008-10-27 17:20:55 +00004148 S += "\nstatic void __";
4149 S += funcName;
4150 S += "_block_dispose_" + utostr(i);
4151 S += "(" + StructRef;
4152 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004153 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004154 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004155 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004156 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004157 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004158 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004159 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004160 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004163 return S;
4164}
4165
Steve Naroff01aec112009-12-06 21:14:13 +00004166std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4167 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004168 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004169 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Steve Naroff54055232008-10-27 17:20:55 +00004171 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004172 S += " struct " + Desc;
4173 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Steve Naroff01aec112009-12-06 21:14:13 +00004175 Constructor += "(void *fp, "; // Invoke function pointer.
4176 Constructor += "struct " + Desc; // Descriptor pointer.
4177 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Steve Naroff54055232008-10-27 17:20:55 +00004179 if (BlockDeclRefs.size()) {
4180 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004181 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004182 E = BlockByCopyDecls.end(); I != E; ++I) {
4183 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004184 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004185 std::string ArgName = "_" + FieldName;
4186 // Handle nested closure invocation. For example:
4187 //
4188 // void (^myImportedBlock)(void);
4189 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004190 //
Steve Naroff54055232008-10-27 17:20:55 +00004191 // void (^anotherBlock)(void);
4192 // anotherBlock = ^(void) {
4193 // myImportedBlock(); // import and invoke the closure
4194 // };
4195 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004196 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004197 S += "struct __block_impl *";
4198 Constructor += ", void *" + ArgName;
4199 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004200 QualType QT = (*I)->getType();
4201 if (HasLocalVariableExternalStorage(*I))
4202 QT = Context->getPointerType(QT);
4203 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4204 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004205 Constructor += ", " + ArgName;
4206 }
4207 S += FieldName + ";\n";
4208 }
4209 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004210 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004211 E = BlockByRefDecls.end(); I != E; ++I) {
4212 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004213 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004214 std::string ArgName = "_" + FieldName;
4215 // Handle nested closure invocation. For example:
4216 //
4217 // void (^myImportedBlock)(void);
4218 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004219 //
Steve Naroff54055232008-10-27 17:20:55 +00004220 // void (^anotherBlock)(void);
4221 // anotherBlock = ^(void) {
4222 // myImportedBlock(); // import and invoke the closure
4223 // };
4224 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004225 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004226 S += "struct __block_impl *";
4227 Constructor += ", void *" + ArgName;
4228 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004229 std::string TypeString;
4230 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004231 TypeString += " *";
4232 FieldName = TypeString + FieldName;
4233 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004234 Constructor += ", " + ArgName;
4235 }
4236 S += FieldName + "; // by ref\n";
4237 }
4238 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004239 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004240 if (GlobalVarDecl)
4241 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4242 else
4243 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004244 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Steve Naroff01aec112009-12-06 21:14:13 +00004246 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004247
Steve Naroff54055232008-10-27 17:20:55 +00004248 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004249 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004250 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004251 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004252 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004253 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004254 Constructor += Name + " = (struct __block_impl *)_";
4255 else
4256 Constructor += Name + " = _";
4257 Constructor += Name + ";\n";
4258 }
4259 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004260 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004261 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004262 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004263 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004264 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004265 Constructor += Name + " = (struct __block_impl *)_";
4266 else
4267 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004268 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004269 }
4270 } else {
4271 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004272 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004273 if (GlobalVarDecl)
4274 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4275 else
4276 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004277 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4278 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004279 }
4280 Constructor += " ";
4281 Constructor += "}\n";
4282 S += Constructor;
4283 S += "};\n";
4284 return S;
4285}
4286
Steve Naroff01aec112009-12-06 21:14:13 +00004287std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4288 std::string ImplTag, int i,
4289 const char *FunName,
4290 unsigned hasCopy) {
4291 std::string S = "\nstatic struct " + DescTag;
4292
4293 S += " {\n unsigned long reserved;\n";
4294 S += " unsigned long Block_size;\n";
4295 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004296 S += " void (*copy)(struct ";
4297 S += ImplTag; S += "*, struct ";
4298 S += ImplTag; S += "*);\n";
4299
4300 S += " void (*dispose)(struct ";
4301 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004302 }
4303 S += "} ";
4304
4305 S += DescTag + "_DATA = { 0, sizeof(struct ";
4306 S += ImplTag + ")";
4307 if (hasCopy) {
4308 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4309 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4310 }
4311 S += "};\n";
4312 return S;
4313}
4314
Steve Naroff54055232008-10-27 17:20:55 +00004315void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004316 const char *FunName) {
4317 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004318 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004319 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004320 bool RewriteSC = (GlobalVarDecl &&
4321 !Blocks.empty() &&
4322 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4323 GlobalVarDecl->getType().getCVRQualifiers());
4324 if (RewriteSC) {
4325 std::string SC(" void __");
4326 SC += GlobalVarDecl->getNameAsString();
4327 SC += "() {}";
4328 InsertText(FunLocStart, SC);
4329 }
4330
Steve Naroff54055232008-10-27 17:20:55 +00004331 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004332 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4333 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004334 // Need to copy-in the inner copied-in variables not actually used in this
4335 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004336 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4337 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4338 ValueDecl *VD = Exp->getDecl();
4339 BlockDeclRefs.push_back(Exp);
4340 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4341 BlockByCopyDeclsPtrSet.insert(VD);
4342 BlockByCopyDecls.push_back(VD);
4343 }
4344 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4345 BlockByRefDeclsPtrSet.insert(VD);
4346 BlockByRefDecls.push_back(VD);
4347 }
4348 }
Steve Naroff54055232008-10-27 17:20:55 +00004349
Steve Naroff01aec112009-12-06 21:14:13 +00004350 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4351 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004352
Steve Naroff01aec112009-12-06 21:14:13 +00004353 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004354
Benjamin Kramerd999b372010-02-14 14:14:16 +00004355 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004356
Steve Naroff01aec112009-12-06 21:14:13 +00004357 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Benjamin Kramerd999b372010-02-14 14:14:16 +00004359 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004360
4361 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004362 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004363 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004364 }
Steve Naroff01aec112009-12-06 21:14:13 +00004365 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4366 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004367 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Steve Naroff54055232008-10-27 17:20:55 +00004369 BlockDeclRefs.clear();
4370 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004371 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004372 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004373 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004374 ImportedBlockDecls.clear();
4375 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004376 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004377 // Must insert any 'const/volatile/static here. Since it has been
4378 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004379 std::string SC;
4380 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4381 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004382 if (GlobalVarDecl->getType().isConstQualified())
4383 SC += "const ";
4384 if (GlobalVarDecl->getType().isVolatileQualified())
4385 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004386 if (GlobalVarDecl->getType().isRestrictQualified())
4387 SC += "restrict ";
4388 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004389 }
4390
Steve Naroff54055232008-10-27 17:20:55 +00004391 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004392 InnerDeclRefsCount.clear();
4393 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004394 RewrittenBlockExprs.clear();
4395}
4396
4397void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4398 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004399 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004400
Steve Naroff54055232008-10-27 17:20:55 +00004401 SynthesizeBlockLiterals(FunLocStart, FuncName);
4402}
4403
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004404static void BuildUniqueMethodName(std::string &Name,
4405 ObjCMethodDecl *MD) {
4406 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4407 Name = IFace->getNameAsCString();
4408 Name += "__" + MD->getSelector().getAsString();
4409 // Convert colons to underscores.
4410 std::string::size_type loc = 0;
4411 while ((loc = Name.find(":", loc)) != std::string::npos)
4412 Name.replace(loc, 1, "_");
4413}
4414
Steve Naroff54055232008-10-27 17:20:55 +00004415void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004416 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4417 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004418 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004419 std::string FuncName;
4420 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004421 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4422}
4423
4424void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4425 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4426 CI != E; ++CI)
4427 if (*CI) {
4428 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4429 GetBlockDeclRefExprs(CBE->getBody());
4430 else
4431 GetBlockDeclRefExprs(*CI);
4432 }
4433 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004434 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004435 // FIXME: Handle enums.
4436 if (!isa<FunctionDecl>(CDRE->getDecl()))
4437 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004438 }
4439 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4440 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4441 BlockDeclRefExpr *BDRE =
4442 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4443 DRE->getLocation(), false);
4444 BlockDeclRefs.push_back(BDRE);
4445 }
4446
Steve Naroff54055232008-10-27 17:20:55 +00004447 return;
4448}
4449
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004450void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4451 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004452 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4454 CI != E; ++CI)
4455 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004456 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4457 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004458 GetInnerBlockDeclRefExprs(CBE->getBody(),
4459 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004460 InnerContexts);
4461 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004462 else
4463 GetInnerBlockDeclRefExprs(*CI,
4464 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004465 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004466
4467 }
4468 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004469 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004470 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004471 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004472 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004473 }
4474 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4475 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4476 if (Var->isFunctionOrMethodVarDecl())
4477 ImportedLocalExternalDecls.insert(Var);
4478 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004479
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004480 return;
4481}
4482
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004483Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004484 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004485 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004486
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004487 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004488 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004489 } else if (const BlockDeclRefExpr *CDRE =
4490 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004491 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004492 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004493 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004494 }
4495 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4496 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4497 }
4498 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4499 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4500 else if (const ConditionalOperator *CEXPR =
4501 dyn_cast<ConditionalOperator>(BlockExp)) {
4502 Expr *LHSExp = CEXPR->getLHS();
4503 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4504 Expr *RHSExp = CEXPR->getRHS();
4505 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4506 Expr *CONDExp = CEXPR->getCond();
4507 ConditionalOperator *CondExpr =
4508 new (Context) ConditionalOperator(CONDExp,
4509 SourceLocation(), cast<Expr>(LHSStmt),
4510 SourceLocation(), cast<Expr>(RHSStmt),
4511 Exp->getType());
4512 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004513 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4514 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004515 } else {
4516 assert(1 && "RewriteBlockClass: Bad type");
4517 }
4518 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004519 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004520 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004521 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004522 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004524 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4525 SourceLocation(),
4526 &Context->Idents.get("__block_impl"));
4527 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004528
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004529 // Generate a funky cast.
4530 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004531
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004532 // Push the block argument type.
4533 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004534 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004535 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004536 E = FTP->arg_type_end(); I && (I != E); ++I) {
4537 QualType t = *I;
4538 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004539 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004540 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004541 t = Context->getPointerType(BPT->getPointeeType());
4542 }
4543 ArgTypes.push_back(t);
4544 }
Steve Naroff54055232008-10-27 17:20:55 +00004545 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004546 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004547 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004548 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4549 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004550 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004552 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004553
John McCall9d125032010-01-15 18:39:57 +00004554 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4555 CastExpr::CK_Unknown,
4556 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004557 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004558 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4559 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004560 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004561
Douglas Gregor44b43212008-12-11 16:49:14 +00004562 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004563 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004564 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004565 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4566 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004567
John McCall9d125032010-01-15 18:39:57 +00004568 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4569 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004570 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004572 llvm::SmallVector<Expr*, 8> BlkExprs;
4573 // Add the implicit argument.
4574 BlkExprs.push_back(BlkCast);
4575 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004576 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004577 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004578 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004579 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004580 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4581 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004582 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004583 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004584}
4585
4586void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004587 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004588 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004589}
4590
Steve Naroff621edce2009-04-29 16:37:50 +00004591// We need to return the rewritten expression to handle cases where the
4592// BlockDeclRefExpr is embedded in another expression being rewritten.
4593// For example:
4594//
4595// int main() {
4596// __block Foo *f;
4597// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004598//
Steve Naroff621edce2009-04-29 16:37:50 +00004599// void (^myblock)() = ^() {
4600// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4601// i = 77;
4602// };
4603//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004604Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004605 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004606 // for each DeclRefExp where BYREFVAR is name of the variable.
4607 ValueDecl *VD;
4608 bool isArrow = true;
4609 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4610 VD = BDRE->getDecl();
4611 else {
4612 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4613 isArrow = false;
4614 }
4615
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004616 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4617 &Context->Idents.get("__forwarding"),
4618 Context->VoidPtrTy, 0,
4619 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004620 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4621 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004622 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004623
4624 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004625 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4626 &Context->Idents.get(Name),
4627 Context->VoidPtrTy, 0,
4628 /*BitWidth=*/0, /*Mutable=*/true);
4629 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004630 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004631
4632
4633
Steve Naroffdf8570d2009-02-02 17:19:26 +00004634 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004635 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4636 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004637 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004638 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004639}
4640
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004641// Rewrites the imported local variable V with external storage
4642// (static, extern, etc.) as *V
4643//
4644Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4645 ValueDecl *VD = DRE->getDecl();
4646 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4647 if (!ImportedLocalExternalDecls.count(Var))
4648 return DRE;
4649 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4650 DRE->getType(), DRE->getLocation());
4651 // Need parens to enforce precedence.
4652 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4653 Exp);
4654 ReplaceStmt(DRE, PE);
4655 return PE;
4656}
4657
Steve Naroffb2f9e512008-11-03 23:29:32 +00004658void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4659 SourceLocation LocStart = CE->getLParenLoc();
4660 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004661
4662 // Need to avoid trying to rewrite synthesized casts.
4663 if (LocStart.isInvalid())
4664 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004665 // Need to avoid trying to rewrite casts contained in macros.
4666 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4667 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Steve Naroff54055232008-10-27 17:20:55 +00004669 const char *startBuf = SM->getCharacterData(LocStart);
4670 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004671 QualType QT = CE->getType();
4672 const Type* TypePtr = QT->getAs<Type>();
4673 if (isa<TypeOfExprType>(TypePtr)) {
4674 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4675 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4676 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004677 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004678 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004679 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004680 return;
4681 }
Steve Naroff54055232008-10-27 17:20:55 +00004682 // advance the location to startArgList.
4683 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Steve Naroff54055232008-10-27 17:20:55 +00004685 while (*argPtr++ && (argPtr < endBuf)) {
4686 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004687 case '^':
4688 // Replace the '^' with '*'.
4689 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004690 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004691 break;
Steve Naroff54055232008-10-27 17:20:55 +00004692 }
4693 }
4694 return;
4695}
4696
4697void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4698 SourceLocation DeclLoc = FD->getLocation();
4699 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Steve Naroff54055232008-10-27 17:20:55 +00004701 // We have 1 or more arguments that have closure pointers.
4702 const char *startBuf = SM->getCharacterData(DeclLoc);
4703 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Steve Naroff54055232008-10-27 17:20:55 +00004705 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004706
Steve Naroff54055232008-10-27 17:20:55 +00004707 parenCount++;
4708 // advance the location to startArgList.
4709 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4710 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Steve Naroff54055232008-10-27 17:20:55 +00004712 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004713
Steve Naroff54055232008-10-27 17:20:55 +00004714 while (*argPtr++ && parenCount) {
4715 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004716 case '^':
4717 // Replace the '^' with '*'.
4718 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004719 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004720 break;
4721 case '(':
4722 parenCount++;
4723 break;
4724 case ')':
4725 parenCount--;
4726 break;
Steve Naroff54055232008-10-27 17:20:55 +00004727 }
4728 }
4729 return;
4730}
4731
4732bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004733 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004734 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004735 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004736 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004737 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004738 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004739 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004740 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004741 }
4742 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004743 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004744 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004745 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004746 return true;
4747 }
4748 return false;
4749}
4750
Ted Kremenek8189cde2009-02-07 01:47:29 +00004751void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4752 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004753 const char *argPtr = strchr(Name, '(');
4754 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Steve Naroff54055232008-10-27 17:20:55 +00004756 LParen = argPtr; // output the start.
4757 argPtr++; // skip past the left paren.
4758 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Naroff54055232008-10-27 17:20:55 +00004760 while (*argPtr && parenCount) {
4761 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004762 case '(': parenCount++; break;
4763 case ')': parenCount--; break;
4764 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004765 }
4766 if (parenCount) argPtr++;
4767 }
4768 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4769 RParen = argPtr; // output the end
4770}
4771
4772void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4773 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4774 RewriteBlockPointerFunctionArgs(FD);
4775 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004776 }
Steve Naroff54055232008-10-27 17:20:55 +00004777 // Handle Variables and Typedefs.
4778 SourceLocation DeclLoc = ND->getLocation();
4779 QualType DeclT;
4780 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4781 DeclT = VD->getType();
4782 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4783 DeclT = TDD->getUnderlyingType();
4784 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4785 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004786 else
Steve Naroff54055232008-10-27 17:20:55 +00004787 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Steve Naroff54055232008-10-27 17:20:55 +00004789 const char *startBuf = SM->getCharacterData(DeclLoc);
4790 const char *endBuf = startBuf;
4791 // scan backward (from the decl location) for the end of the previous decl.
4792 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4793 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Steve Naroff54055232008-10-27 17:20:55 +00004795 // *startBuf != '^' if we are dealing with a pointer to function that
4796 // may take block argument types (which will be handled below).
4797 if (*startBuf == '^') {
4798 // Replace the '^' with '*', computing a negative offset.
4799 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004800 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004801 }
4802 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4803 // Replace the '^' with '*' for arguments.
4804 DeclLoc = ND->getLocation();
4805 startBuf = SM->getCharacterData(DeclLoc);
4806 const char *argListBegin, *argListEnd;
4807 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4808 while (argListBegin < argListEnd) {
4809 if (*argListBegin == '^') {
4810 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004811 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004812 }
4813 argListBegin++;
4814 }
4815 }
4816 return;
4817}
4818
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004819
4820/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4821/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4822/// struct Block_byref_id_object *src) {
4823/// _Block_object_assign (&_dest->object, _src->object,
4824/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4825/// [|BLOCK_FIELD_IS_WEAK]) // object
4826/// _Block_object_assign(&_dest->object, _src->object,
4827/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4828/// [|BLOCK_FIELD_IS_WEAK]) // block
4829/// }
4830/// And:
4831/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4832/// _Block_object_dispose(_src->object,
4833/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4834/// [|BLOCK_FIELD_IS_WEAK]) // object
4835/// _Block_object_dispose(_src->object,
4836/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4837/// [|BLOCK_FIELD_IS_WEAK]) // block
4838/// }
4839
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004840std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4841 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004842 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004843 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004844 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004845 CopyDestroyCache.insert(flag);
4846 S = "static void __Block_byref_id_object_copy_";
4847 S += utostr(flag);
4848 S += "(void *dst, void *src) {\n";
4849
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004850 // offset into the object pointer is computed as:
4851 // void * + void* + int + int + void* + void *
4852 unsigned IntSize =
4853 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4854 unsigned VoidPtrSize =
4855 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4856
4857 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4858 S += " _Block_object_assign((char*)dst + ";
4859 S += utostr(offset);
4860 S += ", *(void * *) ((char*)src + ";
4861 S += utostr(offset);
4862 S += "), ";
4863 S += utostr(flag);
4864 S += ");\n}\n";
4865
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004866 S += "static void __Block_byref_id_object_dispose_";
4867 S += utostr(flag);
4868 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004869 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4870 S += utostr(offset);
4871 S += "), ";
4872 S += utostr(flag);
4873 S += ");\n}\n";
4874 return S;
4875}
4876
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004877/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4878/// the declaration into:
4879/// struct __Block_byref_ND {
4880/// void *__isa; // NULL for everything except __weak pointers
4881/// struct __Block_byref_ND *__forwarding;
4882/// int32_t __flags;
4883/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004884/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4885/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004886/// typex ND;
4887/// };
4888///
4889/// It then replaces declaration of ND variable with:
4890/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4891/// __size=sizeof(struct __Block_byref_ND),
4892/// ND=initializer-if-any};
4893///
4894///
4895void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004896 // Insert declaration for the function in which block literal is
4897 // used.
4898 if (CurFunctionDeclToDeclareForBlock)
4899 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004900 int flag = 0;
4901 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004902 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004903 if (DeclLoc.isInvalid())
4904 // If type location is missing, it is because of missing type (a warning).
4905 // Use variable's location which is good for this case.
4906 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004907 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004908 SourceLocation X = ND->getLocEnd();
4909 X = SM->getInstantiationLoc(X);
4910 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004911 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004912 std::string ByrefType;
4913 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004914 ByrefType += " {\n";
4915 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004916 RewriteByRefString(ByrefType, Name, ND);
4917 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004918 ByrefType += " int __flags;\n";
4919 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004920 // Add void *__Block_byref_id_object_copy;
4921 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004922 QualType Ty = ND->getType();
4923 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4924 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004925 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4926 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004927 }
4928
4929 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004930 ByrefType += " " + Name + ";\n";
4931 ByrefType += "};\n";
4932 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004933 SourceLocation FunLocStart;
4934 if (CurFunctionDef)
4935 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4936 else {
4937 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4938 FunLocStart = CurMethodDef->getLocStart();
4939 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004940 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004941 if (Ty.isObjCGCWeak()) {
4942 flag |= BLOCK_FIELD_IS_WEAK;
4943 isa = 1;
4944 }
4945
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004946 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004947 flag = BLOCK_BYREF_CALLER;
4948 QualType Ty = ND->getType();
4949 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4950 if (Ty->isBlockPointerType())
4951 flag |= BLOCK_FIELD_IS_BLOCK;
4952 else
4953 flag |= BLOCK_FIELD_IS_OBJECT;
4954 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004955 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004956 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004957 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004958
4959 // struct __Block_byref_ND ND =
4960 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4961 // initializer-if-any};
4962 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004963 unsigned flags = 0;
4964 if (HasCopyAndDispose)
4965 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004966 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004967 ByrefType.clear();
4968 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004969 std::string ForwardingCastType("(");
4970 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004971 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004972 ByrefType += " " + Name + " = {(void*)";
4973 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004974 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004975 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004976 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004977 ByrefType += "sizeof(";
4978 RewriteByRefString(ByrefType, Name, ND);
4979 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004980 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004981 ByrefType += ", __Block_byref_id_object_copy_";
4982 ByrefType += utostr(flag);
4983 ByrefType += ", __Block_byref_id_object_dispose_";
4984 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004985 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004986 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004987 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004988 }
4989 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004990 SourceLocation startLoc;
4991 Expr *E = ND->getInit();
4992 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4993 startLoc = ECE->getLParenLoc();
4994 else
4995 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004996 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004997 endBuf = SM->getCharacterData(startLoc);
4998
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004999 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005000 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005001 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005002 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005003 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005004 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005005 ByrefType += "sizeof(";
5006 RewriteByRefString(ByrefType, Name, ND);
5007 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005008 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005009 ByrefType += "__Block_byref_id_object_copy_";
5010 ByrefType += utostr(flag);
5011 ByrefType += ", __Block_byref_id_object_dispose_";
5012 ByrefType += utostr(flag);
5013 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005014 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005015 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005016
5017 // Complete the newly synthesized compound expression by inserting a right
5018 // curly brace before the end of the declaration.
5019 // FIXME: This approach avoids rewriting the initializer expression. It
5020 // also assumes there is only one declarator. For example, the following
5021 // isn't currently supported by this routine (in general):
5022 //
5023 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5024 //
5025 const char *startBuf = SM->getCharacterData(startLoc);
5026 const char *semiBuf = strchr(startBuf, ';');
5027 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5028 SourceLocation semiLoc =
5029 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5030
Benjamin Kramerd999b372010-02-14 14:14:16 +00005031 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005032 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005033 return;
5034}
5035
Mike Stump1eb44332009-09-09 15:08:12 +00005036void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005037 // Add initializers for any closure decl refs.
5038 GetBlockDeclRefExprs(Exp->getBody());
5039 if (BlockDeclRefs.size()) {
5040 // Unique all "by copy" declarations.
5041 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005042 if (!BlockDeclRefs[i]->isByRef()) {
5043 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5044 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5045 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5046 }
5047 }
Steve Naroff54055232008-10-27 17:20:55 +00005048 // Unique all "by ref" declarations.
5049 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5050 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005051 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5052 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5053 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5054 }
Steve Naroff54055232008-10-27 17:20:55 +00005055 }
5056 // Find any imported blocks...they will need special attention.
5057 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005058 if (BlockDeclRefs[i]->isByRef() ||
5059 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005060 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005061 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005062 }
5063}
5064
Steve Narofffa15fd92008-10-28 20:29:00 +00005065FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5066 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005067 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005068 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005069 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00005070 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005071}
5072
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005073Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5074 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005075 Blocks.push_back(Exp);
5076
5077 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005078
5079 // Add inner imported variables now used in current block.
5080 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005081 if (!InnerBlockDeclRefs.empty()) {
5082 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5083 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5084 ValueDecl *VD = Exp->getDecl();
5085 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005086 // We need to save the copied-in variables in nested
5087 // blocks because it is needed at the end for some of the API generations.
5088 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005089 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5090 BlockDeclRefs.push_back(Exp);
5091 BlockByCopyDeclsPtrSet.insert(VD);
5092 BlockByCopyDecls.push_back(VD);
5093 }
5094 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5095 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5096 BlockDeclRefs.push_back(Exp);
5097 BlockByRefDeclsPtrSet.insert(VD);
5098 BlockByRefDecls.push_back(VD);
5099 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005100 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005101 // Find any imported blocks...they will need special attention.
5102 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5103 if (InnerBlockDeclRefs[i]->isByRef() ||
5104 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5105 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5106 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005107 }
5108 InnerDeclRefsCount.push_back(countOfInnerDecls);
5109
Steve Narofffa15fd92008-10-28 20:29:00 +00005110 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005111
Steve Narofffa15fd92008-10-28 20:29:00 +00005112 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005113 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005114 else if (CurMethodDef)
5115 BuildUniqueMethodName(FuncName, CurMethodDef);
5116 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005117 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005118
Steve Narofffa15fd92008-10-28 20:29:00 +00005119 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005120
Steve Narofffa15fd92008-10-28 20:29:00 +00005121 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5122 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005123
Steve Narofffa15fd92008-10-28 20:29:00 +00005124 // Get a pointer to the function type so we can cast appropriately.
5125 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5126
5127 FunctionDecl *FD;
5128 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005129
Steve Narofffa15fd92008-10-28 20:29:00 +00005130 // Simulate a contructor call...
5131 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005132 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005133
Steve Narofffa15fd92008-10-28 20:29:00 +00005134 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005135
Steve Narofffdc03722008-10-29 21:23:59 +00005136 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005137 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005138 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5139 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005140 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5141 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005142 InitExprs.push_back(castExpr);
5143
Steve Naroff01aec112009-12-06 21:14:13 +00005144 // Initialize the block descriptor.
5145 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005146
Steve Naroff01aec112009-12-06 21:14:13 +00005147 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5148 &Context->Idents.get(DescData.c_str()),
5149 Context->VoidPtrTy, 0,
5150 VarDecl::Static);
5151 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5152 new (Context) DeclRefExpr(NewVD,
5153 Context->VoidPtrTy, SourceLocation()),
5154 UnaryOperator::AddrOf,
5155 Context->getPointerType(Context->VoidPtrTy),
5156 SourceLocation());
5157 InitExprs.push_back(DescRefExpr);
5158
Steve Narofffa15fd92008-10-28 20:29:00 +00005159 // Add initializers for any closure decl refs.
5160 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005161 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005162 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005163 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005164 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005165 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005166 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005167 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005168 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005169 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005170 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005171 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005172 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5173 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005174 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005175 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005176 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005177 if (HasLocalVariableExternalStorage(*I)) {
5178 QualType QT = (*I)->getType();
5179 QT = Context->getPointerType(QT);
5180 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5181 SourceLocation());
5182 }
5183
Steve Narofffa15fd92008-10-28 20:29:00 +00005184 }
Mike Stump1eb44332009-09-09 15:08:12 +00005185 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005186 }
5187 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005188 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005189 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005190 ValueDecl *ND = (*I);
5191 std::string Name(ND->getNameAsString());
5192 std::string RecName;
5193 RewriteByRefString(RecName, Name, ND);
5194 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5195 + sizeof("struct"));
5196 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5197 SourceLocation(), II);
5198 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5199 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5200
Chris Lattner8ec03f52008-11-24 03:54:41 +00005201 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005202 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5203 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005204 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005205 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005206 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005207 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005208 }
5209 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005210 if (ImportedBlockDecls.size()) {
5211 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5212 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005213 unsigned IntSize =
5214 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005215 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5216 Context->IntTy, SourceLocation());
5217 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005218 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005219 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5220 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005221 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005222 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005223 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005224 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5225 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005226 BlockDeclRefs.clear();
5227 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005228 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005229 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005230 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005231 ImportedBlockDecls.clear();
5232 return NewRep;
5233}
5234
5235//===----------------------------------------------------------------------===//
5236// Function Body / Expression rewriting
5237//===----------------------------------------------------------------------===//
5238
Steve Naroffc77a6362008-12-04 16:24:46 +00005239// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5240// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5241// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5242// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5243// Since the rewriter isn't capable of rewriting rewritten code, it's important
5244// we get this right.
5245void RewriteObjC::CollectPropertySetters(Stmt *S) {
5246 // Perform a bottom up traversal of all children.
5247 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5248 CI != E; ++CI)
5249 if (*CI)
5250 CollectPropertySetters(*CI);
5251
5252 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5253 if (BinOp->isAssignmentOp()) {
5254 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5255 PropSetters[PRE] = BinOp;
5256 }
5257 }
5258}
5259
Steve Narofffa15fd92008-10-28 20:29:00 +00005260Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005261 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005262 isa<DoStmt>(S) || isa<ForStmt>(S))
5263 Stmts.push_back(S);
5264 else if (isa<ObjCForCollectionStmt>(S)) {
5265 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005266 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005267 }
Mike Stump1eb44332009-09-09 15:08:12 +00005268
Steve Narofffa15fd92008-10-28 20:29:00 +00005269 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005270
Steve Narofffa15fd92008-10-28 20:29:00 +00005271 // Perform a bottom up rewrite of all children.
5272 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5273 CI != E; ++CI)
5274 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005275 Stmt *newStmt;
5276 Stmt *S = (*CI);
5277 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5278 Expr *OldBase = IvarRefExpr->getBase();
5279 bool replaced = false;
5280 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5281 if (replaced) {
5282 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5283 ReplaceStmt(OldBase, IRE->getBase());
5284 else
5285 ReplaceStmt(S, newStmt);
5286 }
5287 }
5288 else
5289 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005290 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005291 *CI = newStmt;
5292 }
Mike Stump1eb44332009-09-09 15:08:12 +00005293
Steve Narofffa15fd92008-10-28 20:29:00 +00005294 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005295 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005296 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5297 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005298 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005299 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005300 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005301 // Rewrite the block body in place.
5302 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005303 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005304 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005305 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005306 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005307
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005308 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5309
Steve Narofffa15fd92008-10-28 20:29:00 +00005310 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005311 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005312 return blockTranscribed;
5313 }
5314 // Handle specific things.
5315 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5316 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005317
Steve Naroffc77a6362008-12-04 16:24:46 +00005318 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5319 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5320 if (BinOp) {
5321 // Because the rewriter doesn't allow us to rewrite rewritten code,
5322 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005323 DisableReplaceStmt = true;
5324 // Save the source range. Even if we disable the replacement, the
5325 // rewritten node will have been inserted into the tree. If the synthesized
5326 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005327 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005328 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5329 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005330 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005331 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005332 //
5333 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5334 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5335 // to see the original expression). Consider this example:
5336 //
5337 // Foo *obj1, *obj2;
5338 //
5339 // obj1.i = [obj2 rrrr];
5340 //
5341 // 'BinOp' for the previous expression looks like:
5342 //
5343 // (BinaryOperator 0x231ccf0 'int' '='
5344 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5345 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5346 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5347 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5348 //
5349 // 'newStmt' represents the rewritten message expression. For example:
5350 //
5351 // (CallExpr 0x231d300 'id':'struct objc_object *'
5352 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5353 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5354 // (CStyleCastExpr 0x231d220 'void *'
5355 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5356 //
5357 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5358 // can be used as the setter argument. ReplaceStmt() will still 'see'
5359 // the original RHS (since we haven't altered BinOp).
5360 //
Mike Stump1eb44332009-09-09 15:08:12 +00005361 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005362 // node. As a result, we now leak the original AST nodes.
5363 //
Steve Naroffb619d952008-12-09 12:56:34 +00005364 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005365 } else {
5366 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005367 }
5368 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005369 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5370 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005371
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5373 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Steve Narofffa15fd92008-10-28 20:29:00 +00005375 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005376#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 // Before we rewrite it, put the original message expression in a comment.
5378 SourceLocation startLoc = MessExpr->getLocStart();
5379 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Steve Narofffa15fd92008-10-28 20:29:00 +00005381 const char *startBuf = SM->getCharacterData(startLoc);
5382 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005383
Steve Narofffa15fd92008-10-28 20:29:00 +00005384 std::string messString;
5385 messString += "// ";
5386 messString.append(startBuf, endBuf-startBuf+1);
5387 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005388
5389 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005390 // InsertText(clang::SourceLocation, char const*, unsigned int).
5391 // InsertText(startLoc, messString.c_str(), messString.size());
5392 // Tried this, but it didn't work either...
5393 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005394#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005395 return RewriteMessageExpr(MessExpr);
5396 }
Mike Stump1eb44332009-09-09 15:08:12 +00005397
Steve Narofffa15fd92008-10-28 20:29:00 +00005398 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5399 return RewriteObjCTryStmt(StmtTry);
5400
5401 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5402 return RewriteObjCSynchronizedStmt(StmtTry);
5403
5404 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5405 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Steve Narofffa15fd92008-10-28 20:29:00 +00005407 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5408 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005409
5410 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005412 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005413 OrigStmtRange.getEnd());
5414 if (BreakStmt *StmtBreakStmt =
5415 dyn_cast<BreakStmt>(S))
5416 return RewriteBreakStmt(StmtBreakStmt);
5417 if (ContinueStmt *StmtContinueStmt =
5418 dyn_cast<ContinueStmt>(S))
5419 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005420
5421 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005422 // and cast exprs.
5423 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5424 // FIXME: What we're doing here is modifying the type-specifier that
5425 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005426 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005427 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5428 // the context of an ObjCForCollectionStmt. For example:
5429 // NSArray *someArray;
5430 // for (id <FooProtocol> index in someArray) ;
5431 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5432 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005433 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005434 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Steve Narofffa15fd92008-10-28 20:29:00 +00005436 // Blocks rewrite rules.
5437 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5438 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005439 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005440 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005441 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005442 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005443 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005445 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005446 if (VD->hasAttr<BlocksAttr>()) {
5447 static unsigned uniqueByrefDeclCount = 0;
5448 assert(!BlockByRefDeclNo.count(ND) &&
5449 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5450 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005451 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005452 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005453 else
5454 RewriteTypeOfDecl(VD);
5455 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005456 }
5457 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005458 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005459 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005460 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005461 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5462 }
5463 }
5464 }
Mike Stump1eb44332009-09-09 15:08:12 +00005465
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5467 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005468
5469 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5471 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005472 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5473 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005474 && "Statement stack mismatch");
5475 Stmts.pop_back();
5476 }
5477 // Handle blocks rewriting.
5478 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5479 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005480 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005481 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005482 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5483 ValueDecl *VD = DRE->getDecl();
5484 if (VD->hasAttr<BlocksAttr>())
5485 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005486 if (HasLocalVariableExternalStorage(VD))
5487 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005488 }
5489
Steve Narofffa15fd92008-10-28 20:29:00 +00005490 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005491 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005492 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005493 ReplaceStmt(S, BlockCall);
5494 return BlockCall;
5495 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005496 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005497 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005498 RewriteCastExpr(CE);
5499 }
5500#if 0
5501 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005502 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005503 // Get the new text.
5504 std::string SStr;
5505 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005506 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005507 const std::string &Str = Buf.str();
5508
5509 printf("CAST = %s\n", &Str[0]);
5510 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5511 delete S;
5512 return Replacement;
5513 }
5514#endif
5515 // Return this stmt unmodified.
5516 return S;
5517}
5518
Steve Naroff3d7e7862009-12-05 15:55:59 +00005519void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5520 for (RecordDecl::field_iterator i = RD->field_begin(),
5521 e = RD->field_end(); i != e; ++i) {
5522 FieldDecl *FD = *i;
5523 if (isTopLevelBlockPointerType(FD->getType()))
5524 RewriteBlockPointerDecl(FD);
5525 if (FD->getType()->isObjCQualifiedIdType() ||
5526 FD->getType()->isObjCQualifiedInterfaceType())
5527 RewriteObjCQualifiedInterfaceTypes(FD);
5528 }
5529}
5530
Steve Narofffa15fd92008-10-28 20:29:00 +00005531/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5532/// main file of the input.
5533void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5534 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005535 if (FD->isOverloadedOperator())
5536 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005537
Steve Narofffa15fd92008-10-28 20:29:00 +00005538 // Since function prototypes don't have ParmDecl's, we check the function
5539 // prototype. This enables us to rewrite function declarations and
5540 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005541 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005542
Sebastian Redld3a413d2009-04-26 20:35:05 +00005543 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005544 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005545 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005546 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005547 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005548 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005549 Body =
5550 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5551 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005552 CurrentBody = 0;
5553 if (PropParentMap) {
5554 delete PropParentMap;
5555 PropParentMap = 0;
5556 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005557 // This synthesizes and inserts the block "impl" struct, invoke function,
5558 // and any copy/dispose helper functions.
5559 InsertBlockLiteralsWithinFunction(FD);
5560 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005561 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005562 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005563 return;
5564 }
5565 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005566 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005567 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005568 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005569 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005570 Body =
5571 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5572 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005573 CurrentBody = 0;
5574 if (PropParentMap) {
5575 delete PropParentMap;
5576 PropParentMap = 0;
5577 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005578 InsertBlockLiteralsWithinMethod(MD);
5579 CurMethodDef = 0;
5580 }
5581 }
5582 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5583 ClassImplementation.push_back(CI);
5584 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5585 CategoryImplementation.push_back(CI);
5586 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5587 RewriteForwardClassDecl(CD);
5588 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5589 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005590 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005591 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005592 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005593 CheckFunctionPointerDecl(VD->getType(), VD);
5594 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005595 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005596 RewriteCastExpr(CE);
5597 }
5598 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005599 } else if (VD->getType()->isRecordType()) {
5600 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5601 if (RD->isDefinition())
5602 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005603 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005604 if (VD->getInit()) {
5605 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005606 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005607 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005608 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005609 CurrentBody = 0;
5610 if (PropParentMap) {
5611 delete PropParentMap;
5612 PropParentMap = 0;
5613 }
Mike Stump1eb44332009-09-09 15:08:12 +00005614 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005615 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005616 GlobalVarDecl = 0;
5617
5618 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005619 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005620 RewriteCastExpr(CE);
5621 }
5622 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005623 return;
5624 }
5625 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005626 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005627 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005628 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005629 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5630 return;
5631 }
5632 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005633 if (RD->isDefinition())
5634 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005635 return;
5636 }
5637 // Nothing yet.
5638}
5639
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005640void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005641 if (Diags.hasErrorOccurred())
5642 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005643
Steve Narofffa15fd92008-10-28 20:29:00 +00005644 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005645
Steve Naroff621edce2009-04-29 16:37:50 +00005646 // Here's a great place to add any extra declarations that may be needed.
5647 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005648 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005649 E = ProtocolExprDecls.end(); I != E; ++I)
5650 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5651
Benjamin Kramerd999b372010-02-14 14:14:16 +00005652 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005653 if (ClassImplementation.size() || CategoryImplementation.size())
5654 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005655
Steve Narofffa15fd92008-10-28 20:29:00 +00005656 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5657 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005658 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005659 Rewrite.getRewriteBufferFor(MainFileID)) {
5660 //printf("Changed:\n");
5661 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5662 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005663 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005664 }
Steve Narofface66252008-11-13 20:07:04 +00005665
Steve Naroff621edce2009-04-29 16:37:50 +00005666 if (ClassImplementation.size() || CategoryImplementation.size() ||
5667 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005668 // Rewrite Objective-c meta data*
5669 std::string ResultStr;
5670 SynthesizeMetaDataIntoBuffer(ResultStr);
5671 // Emit metadata.
5672 *OutFile << ResultStr;
5673 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 OutFile->flush();
5675}