blob: 3c415c79d95cc420f500a62fb87b44ecf9b88d2b [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());
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000447 return new (Ctx) CStyleCastExpr(Ty, Kind, E, CXXBaseSpecifierArray(), TInfo,
John McCall9d125032010-01-15 18:39:57 +0000448 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";
Chris Lattner553e5832010-04-13 17:33:56 +0000643 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000644 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000645 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000646 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000647 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000648 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000649 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000650 Preamble += "#define __weak\n";
651 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000652 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
653 // as this avoids warning in any 64bit/32bit compilation model.
654 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000655}
656
657
Chris Lattnerf04da132007-10-24 17:06:59 +0000658//===----------------------------------------------------------------------===//
659// Top Level Driver Code
660//===----------------------------------------------------------------------===//
661
Chris Lattner682bf922009-03-29 16:50:03 +0000662void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000663 if (Diags.hasErrorOccurred())
664 return;
665
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000666 // Two cases: either the decl could be in the main file, or it could be in a
667 // #included file. If the former, rewrite it now. If the later, check to see
668 // if we rewrote the #include/#import.
669 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000670 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000672 // If this is for a builtin, ignore it.
673 if (Loc.isInvalid()) return;
674
Steve Naroffebf2b562007-10-23 23:50:29 +0000675 // Look for built-in declarations that we need to refer during the rewrite.
676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000677 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000678 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000679 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000680 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000681 ConstantStringClassReference = FVD;
682 return;
683 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000685 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000687 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000689 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000690 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000692 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000693 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
694 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000695 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
696 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000697 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000698 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000699 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000701 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000702 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703}
704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Syntactic (non-AST) Rewriting Code
707//===----------------------------------------------------------------------===//
708
Steve Naroffb29b4272008-04-14 22:03:09 +0000709void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000710 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000711 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.begin();
713 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000714 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000716 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000717 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
718 if (*BufPtr == '#') {
719 if (++BufPtr == MainBufEnd)
720 return;
721 while (*BufPtr == ' ' || *BufPtr == '\t')
722 if (++BufPtr == MainBufEnd)
723 return;
724 if (!strncmp(BufPtr, "import", ImportLen)) {
725 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000726 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000727 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000728 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 BufPtr += ImportLen;
730 }
731 }
732 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteTabs() {
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000736 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
737 const char *MainBufStart = MainBuf.begin();
738 const char *MainBufEnd = MainBuf.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattnerf04da132007-10-24 17:06:59 +0000740 // Loop over the whole file, looking for tabs.
741 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
742 if (*BufPtr != '\t')
743 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Chris Lattnerf04da132007-10-24 17:06:59 +0000745 // Okay, we found a tab. This tab will turn into at least one character,
746 // but it depends on which 'virtual column' it is in. Compute that now.
747 unsigned VCol = 0;
748 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
749 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
750 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnerf04da132007-10-24 17:06:59 +0000752 // Okay, now that we know the virtual column, we know how many spaces to
753 // insert. We assume 8-character tab-stops.
754 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000757 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
758 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattnerf04da132007-10-24 17:06:59 +0000760 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000761 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000762 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000763}
764
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
766 ObjCIvarDecl *OID) {
767 std::string S;
768 S = "((struct ";
769 S += ClassDecl->getIdentifier()->getName();
770 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000771 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772 return S;
773}
774
Steve Naroffa0876e82008-12-02 17:36:43 +0000775void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
776 ObjCImplementationDecl *IMD,
777 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000778 static bool objcGetPropertyDefined = false;
779 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000780 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000781 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000782 const char *startBuf = SM->getCharacterData(startLoc);
783 assert((*startBuf == '@') && "bogus @synthesize location");
784 const char *semiBuf = strchr(startBuf, ';');
785 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000786 SourceLocation onePastSemiLoc =
787 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000788
789 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
790 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000795 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000797 if (!OID)
798 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000799 unsigned Attributes = PD->getPropertyAttributes();
800 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
801 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
802 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000803 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 if (GenGetProperty && !objcGetPropertyDefined) {
805 objcGetPropertyDefined = true;
806 // FIXME. Is this attribute correct in all cases?
807 Getr = "\nextern \"C\" __declspec(dllimport) "
808 "id objc_getProperty(id, SEL, long, bool);\n";
809 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000810 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000813 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
826 Getr += "(";
827 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
828 if (i) Getr += ", ";
829 std::string ParamStr = FT->getArgType(i).getAsString();
830 Getr += ParamStr;
831 }
832 if (FT->isVariadic()) {
833 if (FT->getNumArgs()) Getr += ", ";
834 Getr += "...";
835 }
836 Getr += ")";
837 } else
838 Getr += "()";
839 }
840 Getr += ";\n";
841 Getr += "return (_TYPE)";
842 Getr += "objc_getProperty(self, _cmd, ";
843 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
844 Getr += ", 1)";
845 }
846 else
847 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000848 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000849 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 if (PD->isReadOnly())
851 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroffeb0646c2008-12-02 15:48:25 +0000853 // Generate the 'setter' function.
854 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000855 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
856 ObjCPropertyDecl::OBJC_PR_copy);
857 if (GenSetProperty && !objcSetPropertyDefined) {
858 objcSetPropertyDefined = true;
859 // FIXME. Is this attribute correct in all cases?
860 Setr = "\nextern \"C\" __declspec(dllimport) "
861 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
862 }
863
Steve Naroffeb0646c2008-12-02 15:48:25 +0000864 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000865 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000866 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000867 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 if (GenSetProperty) {
869 Setr += "objc_setProperty (self, _cmd, ";
870 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
871 Setr += ", (id)";
872 Setr += PD->getNameAsCString();
873 Setr += ", ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 Setr += "0, ";
876 else
877 Setr += "1, ";
878 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
879 Setr += "1)";
880 else
881 Setr += "0)";
882 }
883 else {
884 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
885 Setr += PD->getNameAsCString();
886 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000887 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000888 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000889}
Chris Lattner8a12c272007-10-11 18:38:32 +0000890
Steve Naroffb29b4272008-04-14 22:03:09 +0000891void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000892 // Get the start location and compute the semi location.
893 SourceLocation startLoc = ClassDecl->getLocation();
894 const char *startBuf = SM->getCharacterData(startLoc);
895 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattnerf04da132007-10-24 17:06:59 +0000897 // Translate to typedef's that forward reference structs with the same name
898 // as the class. As a convenience, we include the original declaration
899 // as a comment.
900 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000901 typedefString += "// @class ";
902 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
903 I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
905 typedefString += ForwardDecl->getNameAsString();
906 if (I+1 != E)
907 typedefString += ", ";
908 else
909 typedefString += ";\n";
910 }
911
Chris Lattner67956052009-02-20 18:04:31 +0000912 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
913 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000914 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000915 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000920 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000921 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000922 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000923 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Steve Naroff934f2762007-10-24 22:48:43 +0000926 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000928}
929
Steve Naroffb29b4272008-04-14 22:03:09 +0000930void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000931 // When method is a synthesized one, such as a getter/setter there is
932 // nothing to rewrite.
933 if (Method->isSynthesized())
934 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000935 SourceLocation LocStart = Method->getLocStart();
936 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner30fc9332009-02-04 01:06:56 +0000938 if (SM->getInstantiationLineNumber(LocEnd) >
939 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 InsertText(LocStart, "#if 0\n");
941 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000942 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000943 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000944 }
945}
946
Mike Stump1eb44332009-09-09 15:08:12 +0000947void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000948 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Benjamin Kramerd999b372010-02-14 14:14:16 +0000950 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000951 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000952}
953
Steve Naroffb29b4272008-04-14 22:03:09 +0000954void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000955 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff423cb562007-10-30 13:30:57 +0000957 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000960 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
961 E = CatDecl->prop_end(); I != E; ++I)
962 RewriteProperty(*I);
963
Mike Stump1eb44332009-09-09 15:08:12 +0000964 for (ObjCCategoryDecl::instmeth_iterator
965 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000968 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000969 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000970 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000971 RewriteMethodDeclaration(*I);
972
Steve Naroff423cb562007-10-30 13:30:57 +0000973 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000974 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000975}
976
Steve Naroffb29b4272008-04-14 22:03:09 +0000977void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000978 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Steve Naroff752d6ef2007-10-30 16:42:30 +0000980 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000982
983 for (ObjCProtocolDecl::instmeth_iterator
984 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000985 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000988 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000989 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000990 RewriteMethodDeclaration(*I);
991
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000993 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 // Must comment out @optional/@required
997 const char *startBuf = SM->getCharacterData(LocStart);
998 const char *endBuf = SM->getCharacterData(LocEnd);
999 for (const char *p = startBuf; p < endBuf; p++) {
1000 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001001 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001002 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001004 }
1005 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001006 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001009 }
1010 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001011}
1012
Steve Naroffb29b4272008-04-14 22:03:09 +00001013void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001014 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001015 if (LocStart.isInvalid())
1016 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001018 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001019}
1020
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1022 const FunctionType *&FPRetType) {
1023 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001024 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001025 else if (T->isFunctionPointerType() ||
1026 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001027 // needs special handling, since pointer-to-functions have special
1028 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001029 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001032 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001034 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001035 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +00001036 ResultStr += FPRetType->getResultType().getAsString();
1037 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001038 }
1039 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001040 ResultStr += T.getAsString();
1041}
1042
1043void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1044 std::string &ResultStr) {
1045 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1046 const FunctionType *FPRetType = 0;
1047 ResultStr += "\nstatic ";
1048 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001049 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001051 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001052 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001054 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001055 NameStr += "_I_";
1056 else
1057 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001059 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001061
1062 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001063 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001064 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001065 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001068 {
1069 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 int len = selString.size();
1071 for (int i = 0; i < len; i++)
1072 if (selString[i] == ':')
1073 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001074 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001076 // Remember this name for metadata emission
1077 MethodInternalNames[OMD] = NameStr;
1078 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 // Rewrite arguments
1081 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001085 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001087 if (!LangOpts.Microsoft) {
1088 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1089 ResultStr += "struct ";
1090 }
1091 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001092 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001093 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001094 }
1095 else
Steve Naroff621edce2009-04-29 16:37:50 +00001096 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001099 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001103 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1104 E = OMD->param_end(); PI != E; ++PI) {
1105 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001107 if (PDecl->getType()->isObjCQualifiedIdType()) {
1108 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001110 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001112 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001113 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001114 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001115 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1116 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001117 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001118 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001119 ResultStr += Name;
1120 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001122 if (OMD->isVariadic())
1123 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001124 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Steve Naroff76e429d2008-07-16 14:40:40 +00001126 if (FPRetType) {
1127 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Steve Naroff76e429d2008-07-16 14:40:40 +00001129 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001130 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001131 ResultStr += "(";
1132 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1133 if (i) ResultStr += ", ";
1134 std::string ParamStr = FT->getArgType(i).getAsString();
1135 ResultStr += ParamStr;
1136 }
1137 if (FT->isVariadic()) {
1138 if (FT->getNumArgs()) ResultStr += ", ";
1139 ResultStr += "...";
1140 }
1141 ResultStr += ")";
1142 } else {
1143 ResultStr += "()";
1144 }
1145 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001147void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1149 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001151 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001154 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1155 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001156 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 ObjCMethodDecl *OMD = *I;
1159 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001161 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001162
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 const char *startBuf = SM->getCharacterData(LocStart);
1164 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001165 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001169 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1170 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001171 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001173 ObjCMethodDecl *OMD = *I;
1174 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001176 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001180 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001184 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001185 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001186 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001187 }
1188
Benjamin Kramerd999b372010-02-14 14:14:16 +00001189 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190}
1191
Steve Naroffb29b4272008-04-14 22:03:09 +00001192void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001193 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001195 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001196 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001197 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001198 ResultStr += "\n";
1199 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001201 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001202 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001205 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001207 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
1210 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001212 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001213 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001215 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001216 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001217 for (ObjCInterfaceDecl::classmeth_iterator
1218 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001219 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001220 RewriteMethodDeclaration(*I);
1221
Steve Naroff2feac5e2007-10-30 03:43:13 +00001222 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001224}
1225
Steve Naroffb619d952008-12-09 12:56:34 +00001226Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1227 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001228 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1229 // This allows us to reuse all the fun and games in SynthMessageExpr().
1230 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1231 ObjCMessageExpr *MsgExpr;
1232 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1233 llvm::SmallVector<Expr *, 1> ExprVec;
1234 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Steve Naroff8599e7a2008-12-08 16:43:47 +00001236 Stmt *Receiver = PropRefExpr->getBase();
1237 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1238 if (PRE && PropGetters[PRE]) {
1239 // This allows us to handle chain/nested property getters.
1240 Receiver = PropGetters[PRE];
1241 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001242 if (isa<ObjCSuperExpr>(Receiver))
1243 MsgExpr = ObjCMessageExpr::Create(*Context,
1244 PDecl->getType().getNonReferenceType(),
1245 /*FIXME?*/SourceLocation(),
1246 Receiver->getLocStart(),
1247 /*IsInstanceSuper=*/true,
1248 cast<Expr>(Receiver)->getType(),
1249 PDecl->getSetterName(),
1250 PDecl->getSetterMethodDecl(),
1251 &ExprVec[0], 1,
1252 /*FIXME:*/SourceLocation());
1253 else
1254 MsgExpr = ObjCMessageExpr::Create(*Context,
1255 PDecl->getType().getNonReferenceType(),
1256 /*FIXME: */SourceLocation(),
1257 cast<Expr>(Receiver),
1258 PDecl->getSetterName(),
1259 PDecl->getSetterMethodDecl(),
1260 &ExprVec[0], 1,
1261 /*FIXME:*/SourceLocation());
Steve Naroffc77a6362008-12-04 16:24:46 +00001262 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Steve Naroffc77a6362008-12-04 16:24:46 +00001264 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001265 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001266 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001267 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1268 // to things that stay around.
1269 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001270 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001271}
1272
Steve Naroffc77a6362008-12-04 16:24:46 +00001273Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001274 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1275 // This allows us to reuse all the fun and games in SynthMessageExpr().
1276 ObjCMessageExpr *MsgExpr;
1277 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Steve Naroff8599e7a2008-12-08 16:43:47 +00001279 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Steve Naroff8599e7a2008-12-08 16:43:47 +00001281 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1282 if (PRE && PropGetters[PRE]) {
1283 // This allows us to handle chain/nested property getters.
1284 Receiver = PropGetters[PRE];
1285 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001286
1287 if (isa<ObjCSuperExpr>(Receiver))
1288 MsgExpr = ObjCMessageExpr::Create(*Context,
1289 PDecl->getType().getNonReferenceType(),
1290 /*FIXME:*/SourceLocation(),
1291 Receiver->getLocStart(),
1292 /*IsInstanceSuper=*/true,
1293 cast<Expr>(Receiver)->getType(),
1294 PDecl->getGetterName(),
1295 PDecl->getGetterMethodDecl(),
1296 0, 0,
1297 /*FIXME:*/SourceLocation());
1298 else
1299 MsgExpr = ObjCMessageExpr::Create(*Context,
1300 PDecl->getType().getNonReferenceType(),
1301 /*FIXME:*/SourceLocation(),
1302 cast<Expr>(Receiver),
1303 PDecl->getGetterName(),
1304 PDecl->getGetterMethodDecl(),
1305 0, 0,
1306 /*FIXME:*/SourceLocation());
Steve Naroff15f081d2008-12-03 00:56:33 +00001307
Steve Naroff4c3580e2008-12-04 23:50:32 +00001308 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001309
1310 if (!PropParentMap)
1311 PropParentMap = new ParentMap(CurrentBody);
1312
1313 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1314 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1315 // We stash away the ReplacingStmt since actually doing the
1316 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1317 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001318 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1319 // to things that stay around.
1320 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001321 return PropRefExpr; // return the original...
1322 } else {
1323 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001324 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001325 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1326 // to things that stay around.
1327 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001328 return ReplacingStmt;
1329 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001330}
1331
Mike Stump1eb44332009-09-09 15:08:12 +00001332Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001333 SourceLocation OrigStart,
1334 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001335 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001336 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001337 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001338 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001339 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001340 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001341 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001342 // lookup which class implements the instance variable.
1343 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001344 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001345 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001346 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Steve Narofff0757612008-05-08 17:52:16 +00001348 // Synthesize an explicit cast to gain access to the ivar.
1349 std::string RecName = clsDeclared->getIdentifier()->getName();
1350 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001351 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001352 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001353 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001354 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1355 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001356 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1357 CastExpr::CK_Unknown,
1358 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001359 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001360 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1361 IV->getBase()->getLocEnd(),
1362 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001363 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001364 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001365 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001366 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1367 IV->getLocation(),
1368 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001369 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001370 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001371 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001372 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001373 // Cannot delete IV->getBase(), since PE points to it.
1374 // Replace the old base with the cast. This is important when doing
1375 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001376 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001377 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001378 }
Steve Naroff84472a82008-04-18 21:55:08 +00001379 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001380 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Steve Naroff9f525972008-05-06 23:20:07 +00001382 // Explicit ivar refs need to have a cast inserted.
1383 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001384 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001385 ObjCInterfaceType *iFaceDecl =
1386 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001387 // lookup which class implements the instance variable.
1388 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001389 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001390 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001391 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Steve Naroff9f525972008-05-06 23:20:07 +00001393 // Synthesize an explicit cast to gain access to the ivar.
1394 std::string RecName = clsDeclared->getIdentifier()->getName();
1395 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001396 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001397 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001398 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001399 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1400 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001401 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1402 CastExpr::CK_Unknown,
1403 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001404 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001405 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001406 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001407 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001408 // Cannot delete IV->getBase(), since PE points to it.
1409 // Replace the old base with the cast. This is important when doing
1410 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001411 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001412 return IV;
1413 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001414 }
Steve Naroff84472a82008-04-18 21:55:08 +00001415 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001416}
1417
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001418Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1419 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1420 CI != E; ++CI) {
1421 if (*CI) {
1422 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1423 if (newStmt)
1424 *CI = newStmt;
1425 }
1426 }
1427 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1428 SourceRange OrigStmtRange = S->getSourceRange();
1429 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1430 replaced);
1431 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001432 }
1433 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1434 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1435 return newStmt;
1436 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001437 return S;
1438}
1439
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440/// SynthCountByEnumWithState - To print:
1441/// ((unsigned int (*)
1442/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001443/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001444/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001445/// "countByEnumeratingWithState:objects:count:"),
1446/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447/// (id *)items, (unsigned int)16)
1448///
Steve Naroffb29b4272008-04-14 22:03:09 +00001449void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001450 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1451 "id *, unsigned int))(void *)objc_msgSend)";
1452 buf += "\n\t\t";
1453 buf += "((id)l_collection,\n\t\t";
1454 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1455 buf += "\n\t\t";
1456 buf += "&enumState, "
1457 "(id *)items, (unsigned int)16)";
1458}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001459
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1461/// statement to exit to its outer synthesized loop.
1462///
Steve Naroffb29b4272008-04-14 22:03:09 +00001463Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001464 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1465 return S;
1466 // replace break with goto __break_label
1467 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001469 SourceLocation startLoc = S->getLocStart();
1470 buf = "goto __break_label_";
1471 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001472 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001473
1474 return 0;
1475}
1476
1477/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1478/// statement to continue with its inner synthesized loop.
1479///
Steve Naroffb29b4272008-04-14 22:03:09 +00001480Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001481 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1482 return S;
1483 // replace continue with goto __continue_label
1484 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001486 SourceLocation startLoc = S->getLocStart();
1487 buf = "goto __continue_label_";
1488 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001489 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491 return 0;
1492}
1493
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001494/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001495/// It rewrites:
1496/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001498/// Into:
1499/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001500/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001502/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001504/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001506/// if (limit) {
1507/// unsigned long startMutations = *enumState.mutationsPtr;
1508/// do {
1509/// unsigned long counter = 0;
1510/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001511/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001513/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001514/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001515/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001516/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001517/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518/// objects:items count:16]);
1519/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001520/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001521/// }
1522/// else
1523/// elem = nil;
1524/// }
1525///
Steve Naroffb29b4272008-04-14 22:03:09 +00001526Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001527 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001528 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001529 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001530 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001531 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001532 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001534 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001536 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001537 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001538 std::string buf;
1539 buf = "\n{\n\t";
1540 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1541 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001542 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001543 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001544 if (ElementType->isObjCQualifiedIdType() ||
1545 ElementType->isObjCQualifiedInterfaceType())
1546 // Simply use 'id' for all qualified types.
1547 elementTypeAsString = "id";
1548 else
1549 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001550 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001551 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001552 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001553 buf += elementName;
1554 buf += ";\n\t";
1555 }
Chris Lattner06767512008-04-08 05:52:18 +00001556 else {
1557 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001558 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001559 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1560 if (VD->getType()->isObjCQualifiedIdType() ||
1561 VD->getType()->isObjCQualifiedInterfaceType())
1562 // Simply use 'id' for all qualified types.
1563 elementTypeAsString = "id";
1564 else
1565 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001566 }
Mike Stump1eb44332009-09-09 15:08:12 +00001567
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 // struct __objcFastEnumerationState enumState = { 0 };
1569 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1570 // id items[16];
1571 buf += "id items[16];\n\t";
1572 // id l_collection = (id)
1573 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001574 // Find start location of 'collection' the hard way!
1575 const char *startCollectionBuf = startBuf;
1576 startCollectionBuf += 3; // skip 'for'
1577 startCollectionBuf = strchr(startCollectionBuf, '(');
1578 startCollectionBuf++; // skip '('
1579 // find 'in' and skip it.
1580 while (*startCollectionBuf != ' ' ||
1581 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1582 (*(startCollectionBuf+3) != ' ' &&
1583 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1584 startCollectionBuf++;
1585 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001586
1587 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001588 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001590 SourceLocation rightParenLoc = S->getRParenLoc();
1591 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1592 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001594
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001595 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1596 // objects:items count:16];
1597 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001598 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 // ((unsigned int (*)
1600 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001601 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001603 // "countByEnumeratingWithState:objects:count:"),
1604 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001605 // (id *)items, (unsigned int)16);
1606 buf += "unsigned long limit =\n\t\t";
1607 SynthCountByEnumWithState(buf);
1608 buf += ";\n\t";
1609 /// if (limit) {
1610 /// unsigned long startMutations = *enumState.mutationsPtr;
1611 /// do {
1612 /// unsigned long counter = 0;
1613 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001614 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001616 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "if (limit) {\n\t";
1618 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1619 buf += "do {\n\t\t";
1620 buf += "unsigned long counter = 0;\n\t\t";
1621 buf += "do {\n\t\t\t";
1622 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1623 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1624 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001625 buf += " = (";
1626 buf += elementTypeAsString;
1627 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001629 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001631 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001633 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 /// objects:items count:16]);
1635 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001636 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001637 /// }
1638 /// else
1639 /// elem = nil;
1640 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001641 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001642 buf = ";\n\t";
1643 buf += "__continue_label_";
1644 buf += utostr(ObjCBcLabelNo.back());
1645 buf += ": ;";
1646 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001647 buf += "} while (counter < limit);\n\t";
1648 buf += "} while (limit = ";
1649 SynthCountByEnumWithState(buf);
1650 buf += ");\n\t";
1651 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001652 buf += " = ((";
1653 buf += elementTypeAsString;
1654 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 buf += "__break_label_";
1656 buf += utostr(ObjCBcLabelNo.back());
1657 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001658 buf += "}\n\t";
1659 buf += "else\n\t\t";
1660 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001661 buf += " = ((";
1662 buf += elementTypeAsString;
1663 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001666 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001667 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001668 if (isa<CompoundStmt>(S->getBody())) {
1669 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001670 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001671 } else {
1672 /* Need to treat single statements specially. For example:
1673 *
1674 * for (A *a in b) if (stuff()) break;
1675 * for (A *a in b) xxxyy;
1676 *
1677 * The following code simply scans ahead to the semi to find the actual end.
1678 */
1679 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1680 const char *semiBuf = strchr(stmtBuf, ';');
1681 assert(semiBuf && "Can't find ';'");
1682 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001683 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001684 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001685 Stmts.pop_back();
1686 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001687 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001688}
1689
Mike Stump1eb44332009-09-09 15:08:12 +00001690/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001691/// This routine rewrites @synchronized(expr) stmt;
1692/// into:
1693/// objc_sync_enter(expr);
1694/// @try stmt @finally { objc_sync_exit(expr); }
1695///
Steve Naroffb29b4272008-04-14 22:03:09 +00001696Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001697 // Get the start location and compute the semi location.
1698 SourceLocation startLoc = S->getLocStart();
1699 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001700
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001701 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001702
1703 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001704 buf = "objc_sync_enter((id)";
1705 const char *lparenBuf = startBuf;
1706 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001707 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001708 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1709 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001710 // been rewritten! (which implies the SourceLocation's are invalid).
1711 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001712 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001713 while (*endBuf != ')') endBuf--;
1714 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001715 buf = ");\n";
1716 // declare a new scope with two variables, _stack and _rethrow.
1717 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1718 buf += "int buf[18/*32-bit i386*/];\n";
1719 buf += "char *pointers[4];} _stack;\n";
1720 buf += "id volatile _rethrow = 0;\n";
1721 buf += "objc_exception_try_enter(&_stack);\n";
1722 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001723 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001724 startLoc = S->getSynchBody()->getLocEnd();
1725 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Steve Naroffc7089f12008-08-19 13:04:19 +00001727 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001728 SourceLocation lastCurlyLoc = startLoc;
1729 buf = "}\nelse {\n";
1730 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001731 buf += "}\n";
1732 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001733 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001734
1735 std::string syncBuf;
1736 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001737 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1738 CastExpr::CK_Unknown,
1739 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001740 std::string syncExprBufS;
1741 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001742 syncExpr->printPretty(syncExprBuf, *Context, 0,
1743 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001744 syncBuf += syncExprBuf.str();
1745 syncBuf += ");";
1746
1747 buf += syncBuf;
1748 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001749 buf += "}\n";
1750 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Benjamin Kramerd999b372010-02-14 14:14:16 +00001752 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001753
1754 bool hasReturns = false;
1755 HasReturnStmts(S->getSynchBody(), hasReturns);
1756 if (hasReturns)
1757 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1758
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001759 return 0;
1760}
1761
Steve Naroffb85e77a2009-12-05 21:43:12 +00001762void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1763{
Steve Naroff8c565152008-12-05 17:03:39 +00001764 // Perform a bottom up traversal of all children.
1765 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1766 CI != E; ++CI)
1767 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001768 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001769
Steve Naroffb85e77a2009-12-05 21:43:12 +00001770 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001771 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001772 TryFinallyContainsReturnDiag);
1773 }
1774 return;
1775}
1776
Steve Naroffb85e77a2009-12-05 21:43:12 +00001777void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1778{
1779 // Perform a bottom up traversal of all children.
1780 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1781 CI != E; ++CI)
1782 if (*CI)
1783 HasReturnStmts(*CI, hasReturns);
1784
1785 if (isa<ReturnStmt>(S))
1786 hasReturns = true;
1787 return;
1788}
1789
1790void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1791 // Perform a bottom up traversal of all children.
1792 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1793 CI != E; ++CI)
1794 if (*CI) {
1795 RewriteTryReturnStmts(*CI);
1796 }
1797 if (isa<ReturnStmt>(S)) {
1798 SourceLocation startLoc = S->getLocStart();
1799 const char *startBuf = SM->getCharacterData(startLoc);
1800
1801 const char *semiBuf = strchr(startBuf, ';');
1802 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1803 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1804
1805 std::string buf;
1806 buf = "{ objc_exception_try_exit(&_stack); return";
1807
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(startLoc, 6, buf);
1809 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001810 }
1811 return;
1812}
1813
1814void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1815 // Perform a bottom up traversal of all children.
1816 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1817 CI != E; ++CI)
1818 if (*CI) {
1819 RewriteSyncReturnStmts(*CI, syncExitBuf);
1820 }
1821 if (isa<ReturnStmt>(S)) {
1822 SourceLocation startLoc = S->getLocStart();
1823 const char *startBuf = SM->getCharacterData(startLoc);
1824
1825 const char *semiBuf = strchr(startBuf, ';');
1826 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1827 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1828
1829 std::string buf;
1830 buf = "{ objc_exception_try_exit(&_stack);";
1831 buf += syncExitBuf;
1832 buf += " return";
1833
Benjamin Kramerd999b372010-02-14 14:14:16 +00001834 ReplaceText(startLoc, 6, buf);
1835 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001836 }
1837 return;
1838}
1839
Steve Naroffb29b4272008-04-14 22:03:09 +00001840Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001841 // Get the start location and compute the semi location.
1842 SourceLocation startLoc = S->getLocStart();
1843 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroff75730982007-11-07 04:08:17 +00001845 assert((*startBuf == '@') && "bogus @try location");
1846
1847 std::string buf;
1848 // declare a new scope with two variables, _stack and _rethrow.
1849 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1850 buf += "int buf[18/*32-bit i386*/];\n";
1851 buf += "char *pointers[4];} _stack;\n";
1852 buf += "id volatile _rethrow = 0;\n";
1853 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001854 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001855
Benjamin Kramerd999b372010-02-14 14:14:16 +00001856 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001857
Steve Naroff75730982007-11-07 04:08:17 +00001858 startLoc = S->getTryBody()->getLocEnd();
1859 startBuf = SM->getCharacterData(startLoc);
1860
1861 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Steve Naroff75730982007-11-07 04:08:17 +00001863 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001864 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001865 startLoc = startLoc.getFileLocWithOffset(1);
1866 buf = " /* @catch begin */ else {\n";
1867 buf += " id _caught = objc_exception_extract(&_stack);\n";
1868 buf += " objc_exception_try_enter (&_stack);\n";
1869 buf += " if (_setjmp(_stack.buf))\n";
1870 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1871 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001872
Benjamin Kramerd999b372010-02-14 14:14:16 +00001873 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001874 } else { /* no catch list */
1875 buf = "}\nelse {\n";
1876 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1877 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001878 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001879 }
Steve Naroff75730982007-11-07 04:08:17 +00001880 bool sawIdTypedCatch = false;
1881 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001882 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1883 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001884 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001885
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001886 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001887 buf = "if ("; // we are generating code for the first catch clause
1888 else
1889 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001890 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001891 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Steve Naroff75730982007-11-07 04:08:17 +00001893 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001894
Steve Naroff75730982007-11-07 04:08:17 +00001895 const char *lParenLoc = strchr(startBuf, '(');
1896
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001897 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001898 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001899 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001900 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1901 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001902 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001903 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001904 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Steve Naroffe12e6922008-02-01 20:02:07 +00001906 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001907 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001908 } else if (catchDecl) {
1909 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001910 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001911 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001912 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001913 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001914 } else if (t->isObjCObjectPointerType()) {
1915 QualType InterfaceTy = t->getPointeeType();
1916 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1917 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001918 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001919 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001920 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001921 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001922 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001923 }
1924 }
1925 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001926 lastCatchBody = Catch->getCatchBody();
1927 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001928 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1929 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1930 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1931 assert((*rParenBuf == ')') && "bogus @catch paren location");
1932 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Mike Stump1eb44332009-09-09 15:08:12 +00001934 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001935 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001936 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001937 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001938 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001939 }
Steve Naroff75730982007-11-07 04:08:17 +00001940 }
1941 // Complete the catch list...
1942 if (lastCatchBody) {
1943 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001944 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1945 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Steve Naroff378f47a2008-09-11 15:29:03 +00001947 // Insert the last (implicit) else clause *before* the right curly brace.
1948 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1949 buf = "} /* last catch end */\n";
1950 buf += "else {\n";
1951 buf += " _rethrow = _caught;\n";
1952 buf += " objc_exception_try_exit(&_stack);\n";
1953 buf += "} } /* @catch end */\n";
1954 if (!S->getFinallyStmt())
1955 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001956 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001957
Steve Naroff75730982007-11-07 04:08:17 +00001958 // Set lastCurlyLoc
1959 lastCurlyLoc = lastCatchBody->getLocEnd();
1960 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001961 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001962 startLoc = finalStmt->getLocStart();
1963 startBuf = SM->getCharacterData(startLoc);
1964 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Benjamin Kramerd999b372010-02-14 14:14:16 +00001966 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroff75730982007-11-07 04:08:17 +00001968 Stmt *body = finalStmt->getFinallyBody();
1969 SourceLocation startLoc = body->getLocStart();
1970 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001971 assert(*SM->getCharacterData(startLoc) == '{' &&
1972 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001973 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001974 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Steve Naroff75730982007-11-07 04:08:17 +00001976 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001977 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001978 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001979 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Steve Naroff75730982007-11-07 04:08:17 +00001981 // Set lastCurlyLoc
1982 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Steve Naroff8c565152008-12-05 17:03:39 +00001984 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001985 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001986 } else { /* no finally clause - make sure we synthesize an implicit one */
1987 buf = "{ /* implicit finally clause */\n";
1988 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1989 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1990 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001991 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001992
1993 // Now check for any return/continue/go statements within the @try.
1994 // The implicit finally clause won't called if the @try contains any
1995 // jump statements.
1996 bool hasReturns = false;
1997 HasReturnStmts(S->getTryBody(), hasReturns);
1998 if (hasReturns)
1999 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002000 }
2001 // Now emit the final closing curly brace...
2002 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002003 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002004 return 0;
2005}
2006
Steve Naroffb29b4272008-04-14 22:03:09 +00002007Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002008 return 0;
2009}
2010
Steve Naroffb29b4272008-04-14 22:03:09 +00002011Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002012 return 0;
2013}
2014
Mike Stump1eb44332009-09-09 15:08:12 +00002015// This can't be done with ReplaceStmt(S, ThrowExpr), since
2016// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002017// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002018Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002019 // Get the start location and compute the semi location.
2020 SourceLocation startLoc = S->getLocStart();
2021 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroff2bd03922007-11-07 15:32:26 +00002023 assert((*startBuf == '@') && "bogus @throw location");
2024
2025 std::string buf;
2026 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002027 if (S->getThrowExpr())
2028 buf = "objc_exception_throw(";
2029 else // add an implicit argument
2030 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002031
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002032 // handle "@ throw" correctly.
2033 const char *wBuf = strchr(startBuf, 'w');
2034 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002035 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Steve Naroff2bd03922007-11-07 15:32:26 +00002037 const char *semiBuf = strchr(startBuf, ';');
2038 assert((*semiBuf == ';') && "@throw: can't find ';'");
2039 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002040 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002041 return 0;
2042}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002043
Steve Naroffb29b4272008-04-14 22:03:09 +00002044Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002045 // Create a new string expression.
2046 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002047 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002048 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002049 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2050 StrEncoding.length(), false,StrType,
2051 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002052 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Chris Lattner07506182007-11-30 22:53:43 +00002054 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002055 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002056 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002057}
2058
Steve Naroffb29b4272008-04-14 22:03:09 +00002059Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002060 if (!SelGetUidFunctionDecl)
2061 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002062 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2063 // Create a call to sel_registerName("selName").
2064 llvm::SmallVector<Expr*, 8> SelExprs;
2065 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002066 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002067 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002068 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002069 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002070 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2071 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002072 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002073 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002074 return SelExp;
2075}
2076
Steve Naroffb29b4272008-04-14 22:03:09 +00002077CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002078 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2079 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002080 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002081 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Steve Naroffebf2b562007-10-23 23:50:29 +00002083 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002084 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Steve Naroffebf2b562007-10-23 23:50:29 +00002086 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002087 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002088 ImplicitCastExpr *ICE =
2089 new (Context) ImplicitCastExpr(pToFunc, CastExpr::CK_Unknown,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002090 DRE, CXXBaseSpecifierArray(),
Anders Carlsson88465d32010-04-23 22:18:37 +00002091 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002092
John McCall183700f2009-09-21 23:43:11 +00002093 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002095 CallExpr *Exp =
2096 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2097 EndLoc);
2098 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002099}
2100
Steve Naroffd5255f52007-11-01 13:24:47 +00002101static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2102 const char *&startRef, const char *&endRef) {
2103 while (startBuf < endBuf) {
2104 if (*startBuf == '<')
2105 startRef = startBuf; // mark the start.
2106 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002107 if (startRef && *startRef == '<') {
2108 endRef = startBuf; // mark the end.
2109 return true;
2110 }
2111 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002112 }
2113 startBuf++;
2114 }
2115 return false;
2116}
2117
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002118static void scanToNextArgument(const char *&argRef) {
2119 int angle = 0;
2120 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2121 if (*argRef == '<')
2122 angle++;
2123 else if (*argRef == '>')
2124 angle--;
2125 argRef++;
2126 }
2127 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2128}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002129
Steve Naroffb29b4272008-04-14 22:03:09 +00002130bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002131 if (T->isObjCQualifiedIdType())
2132 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002133 if (const PointerType *PT = T->getAs<PointerType>()) {
2134 if (PT->getPointeeType()->isObjCQualifiedIdType())
2135 return true;
2136 }
2137 if (T->isObjCObjectPointerType()) {
2138 T = T->getPointeeType();
2139 return T->isObjCQualifiedInterfaceType();
2140 }
2141 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002142}
2143
Steve Naroff4f95b752008-07-29 18:15:38 +00002144void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2145 QualType Type = E->getType();
2146 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002147 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Steve Naroffcda658e2008-11-19 21:15:47 +00002149 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2150 Loc = ECE->getLParenLoc();
2151 EndLoc = ECE->getRParenLoc();
2152 } else {
2153 Loc = E->getLocStart();
2154 EndLoc = E->getLocEnd();
2155 }
2156 // This will defend against trying to rewrite synthesized expressions.
2157 if (Loc.isInvalid() || EndLoc.isInvalid())
2158 return;
2159
Steve Naroff4f95b752008-07-29 18:15:38 +00002160 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002161 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002162 const char *startRef = 0, *endRef = 0;
2163 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2164 // Get the locations of the startRef, endRef.
2165 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2166 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2167 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002168 InsertText(LessLoc, "/*");
2169 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002170 }
2171 }
2172}
2173
Steve Naroffb29b4272008-04-14 22:03:09 +00002174void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002175 SourceLocation Loc;
2176 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002177 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002178 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2179 Loc = VD->getLocation();
2180 Type = VD->getType();
2181 }
2182 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2183 Loc = FD->getLocation();
2184 // Check for ObjC 'id' and class types that have been adorned with protocol
2185 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002186 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002187 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002188 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 if (!proto)
2190 return;
2191 Type = proto->getResultType();
2192 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002193 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2194 Loc = FD->getLocation();
2195 Type = FD->getType();
2196 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002197 else
2198 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002200 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002201 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Steve Naroffd5255f52007-11-01 13:24:47 +00002203 const char *endBuf = SM->getCharacterData(Loc);
2204 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002205 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002206 startBuf--; // scan backward (from the decl location) for return type.
2207 const char *startRef = 0, *endRef = 0;
2208 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2209 // Get the locations of the startRef, endRef.
2210 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2211 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2212 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002213 InsertText(LessLoc, "/*");
2214 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002215 }
2216 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002217 if (!proto)
2218 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002219 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002220 const char *startBuf = SM->getCharacterData(Loc);
2221 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002222 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2223 if (needToScanForQualifiers(proto->getArgType(i))) {
2224 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Steve Naroffd5255f52007-11-01 13:24:47 +00002226 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002227 // scan forward (from the decl location) for argument types.
2228 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002229 const char *startRef = 0, *endRef = 0;
2230 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2231 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002232 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002233 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002234 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002235 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002236 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002237 InsertText(LessLoc, "/*");
2238 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002239 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002240 startBuf = ++endBuf;
2241 }
2242 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002243 // If the function name is derived from a macro expansion, then the
2244 // argument buffer will not follow the name. Need to speak with Chris.
2245 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002246 startBuf++; // scan forward (from the decl location) for argument types.
2247 startBuf++;
2248 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002249 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002250}
2251
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2253 QualType QT = ND->getType();
2254 const Type* TypePtr = QT->getAs<Type>();
2255 if (!isa<TypeOfExprType>(TypePtr))
2256 return;
2257 while (isa<TypeOfExprType>(TypePtr)) {
2258 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2259 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2260 TypePtr = QT->getAs<Type>();
2261 }
2262 // FIXME. This will not work for multiple declarators; as in:
2263 // __typeof__(a) b,c,d;
2264 std::string TypeAsString(QT.getAsString());
2265 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2266 const char *startBuf = SM->getCharacterData(DeclLoc);
2267 if (ND->getInit()) {
2268 std::string Name(ND->getNameAsString());
2269 TypeAsString += " " + Name + " = ";
2270 Expr *E = ND->getInit();
2271 SourceLocation startLoc;
2272 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2273 startLoc = ECE->getLParenLoc();
2274 else
2275 startLoc = E->getLocStart();
2276 startLoc = SM->getInstantiationLoc(startLoc);
2277 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002278 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002279 }
2280 else {
2281 SourceLocation X = ND->getLocEnd();
2282 X = SM->getInstantiationLoc(X);
2283 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002284 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002285 }
2286}
2287
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002288// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002289void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002290 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2291 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002292 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002293 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002294 &ArgTys[0], ArgTys.size(),
2295 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002296 false, false, 0, 0,
2297 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002298 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002299 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002300 SelGetUidIdent, getFuncType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002301 FunctionDecl::Extern,
2302 FunctionDecl::None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002303}
2304
Steve Naroffb29b4272008-04-14 22:03:09 +00002305void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002306 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002307 if (FD->getIdentifier() &&
2308 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002309 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002310 return;
2311 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002312 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002313}
2314
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002315static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2316 std::string TypeString(Type.getAsString());
2317 const char *argPtr = TypeString.c_str();
2318 if (!strchr(argPtr, '^')) {
2319 Str += TypeString;
2320 return;
2321 }
2322 while (*argPtr) {
2323 Str += (*argPtr == '^' ? '*' : *argPtr);
2324 argPtr++;
2325 }
2326}
2327
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002328// FIXME. Consolidate this routine with RewriteBlockPointerType.
2329static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2330 QualType Type = VD->getType();
2331 std::string TypeString(Type.getAsString());
2332 const char *argPtr = TypeString.c_str();
2333 int paren = 0;
2334 while (*argPtr) {
2335 switch (*argPtr) {
2336 case '(':
2337 Str += *argPtr;
2338 paren++;
2339 break;
2340 case ')':
2341 Str += *argPtr;
2342 paren--;
2343 break;
2344 case '^':
2345 Str += '*';
2346 if (paren == 1)
2347 Str += VD->getNameAsString();
2348 break;
2349 default:
2350 Str += *argPtr;
2351 break;
2352 }
2353 argPtr++;
2354 }
2355}
2356
2357
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002358void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2359 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2360 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2361 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2362 if (!proto)
2363 return;
2364 QualType Type = proto->getResultType();
2365 std::string FdStr = Type.getAsString();
2366 FdStr += " ";
2367 FdStr += FD->getNameAsCString();
2368 FdStr += "(";
2369 unsigned numArgs = proto->getNumArgs();
2370 for (unsigned i = 0; i < numArgs; i++) {
2371 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002372 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002373 if (i+1 < numArgs)
2374 FdStr += ", ";
2375 }
2376 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002377 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002378 CurFunctionDeclToDeclareForBlock = 0;
2379}
2380
Steve Naroffc0a123c2008-03-11 17:37:02 +00002381// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002382void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002383 if (SuperContructorFunctionDecl)
2384 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002385 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002386 llvm::SmallVector<QualType, 16> ArgTys;
2387 QualType argT = Context->getObjCIdType();
2388 assert(!argT.isNull() && "Can't find 'id' type");
2389 ArgTys.push_back(argT);
2390 ArgTys.push_back(argT);
2391 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2392 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002393 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002394 false, false, 0, 0,
2395 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002396 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002397 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002398 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002399 FunctionDecl::Extern,
2400 FunctionDecl::None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002401}
2402
Steve Naroff09b266e2007-10-30 23:14:51 +00002403// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002404void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002405 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2406 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002408 assert(!argT.isNull() && "Can't find 'id' type");
2409 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002411 assert(!argT.isNull() && "Can't find 'SEL' type");
2412 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002414 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002415 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002416 false, false, 0, 0,
2417 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002418 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002419 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002420 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002421 FunctionDecl::Extern,
2422 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002423}
2424
Steve Naroff874e2322007-11-15 10:28:18 +00002425// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002426void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002427 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2428 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002429 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002430 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002431 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002432 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2433 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2434 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002436 assert(!argT.isNull() && "Can't find 'SEL' type");
2437 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002438 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002439 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002440 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002441 false, false, 0, 0,
2442 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002443 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002444 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002445 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002446 FunctionDecl::Extern,
2447 FunctionDecl::None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002448}
2449
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002450// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002451void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002452 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2453 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002454 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002455 assert(!argT.isNull() && "Can't find 'id' type");
2456 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002457 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002458 assert(!argT.isNull() && "Can't find 'SEL' type");
2459 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002460 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002461 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002462 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002463 false, false, 0, 0,
2464 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002465 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002466 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002467 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002468 FunctionDecl::Extern,
2469 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002470}
2471
Mike Stump1eb44332009-09-09 15:08:12 +00002472// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002473// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002474void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002475 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002476 &Context->Idents.get("objc_msgSendSuper_stret");
2477 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002478 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002479 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002480 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002481 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2482 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2483 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002484 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002485 assert(!argT.isNull() && "Can't find 'SEL' type");
2486 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002487 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002488 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002489 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002490 false, false, 0, 0,
2491 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002492 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002493 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002494 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002495 FunctionDecl::Extern,
2496 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002497}
2498
Steve Naroff1284db82008-05-08 22:02:18 +00002499// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002500void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002501 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2502 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002504 assert(!argT.isNull() && "Can't find 'id' type");
2505 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002506 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002507 assert(!argT.isNull() && "Can't find 'SEL' type");
2508 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002509 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002510 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002511 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002512 false, false, 0, 0,
2513 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002514 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002515 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002516 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002517 FunctionDecl::Extern,
2518 FunctionDecl::None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002519}
2520
Steve Naroff09b266e2007-10-30 23:14:51 +00002521// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002522void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002523 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2524 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002525 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002527 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002528 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002529 false, false, 0, 0,
2530 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002531 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002532 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002533 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002534 FunctionDecl::Extern,
2535 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002536}
2537
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002538// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2539void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2540 IdentifierInfo *getSuperClassIdent =
2541 &Context->Idents.get("class_getSuperclass");
2542 llvm::SmallVector<QualType, 16> ArgTys;
2543 ArgTys.push_back(Context->getObjCClassType());
2544 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2545 &ArgTys[0], ArgTys.size(),
2546 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002547 false, false, 0, 0,
2548 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002549 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002550 SourceLocation(),
2551 getSuperClassIdent,
2552 getClassType, 0,
2553 FunctionDecl::Extern,
2554 FunctionDecl::None,
2555 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002556}
2557
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002558// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002559void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002560 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2561 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002562 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002564 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002565 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002566 false, false, 0, 0,
2567 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002568 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002569 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002570 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002571 FunctionDecl::Extern,
2572 FunctionDecl::None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002573}
2574
Steve Naroffb29b4272008-04-14 22:03:09 +00002575Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002576 QualType strType = getConstantStringStructType();
2577
2578 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002579
2580 std::string tmpName = InFileName;
2581 unsigned i;
2582 for (i=0; i < tmpName.length(); i++) {
2583 char c = tmpName.at(i);
2584 // replace any non alphanumeric characters with '_'.
2585 if (!isalpha(c) && (c < '0' || c > '9'))
2586 tmpName[i] = '_';
2587 }
2588 S += tmpName;
2589 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002590 S += utostr(NumObjCStringLiterals++);
2591
Steve Naroffba92b2e2008-03-27 22:29:16 +00002592 Preamble += "static __NSConstantStringImpl " + S;
2593 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2594 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002595 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002596 std::string prettyBufS;
2597 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002598 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2599 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002600 Preamble += prettyBuf.str();
2601 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002602 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002603
2604 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002605 &Context->Idents.get(S), strType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002606 VarDecl::Static, VarDecl::None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002607 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2608 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002609 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002611 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002612 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2613 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002614 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002615 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002616 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002617}
2618
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002619bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002620 // check if we are sending a message to 'super'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002621 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2622 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002623}
2624
2625// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002626QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002627 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002628 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002629 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002630 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002631 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Steve Naroff874e2322007-11-15 10:28:18 +00002633 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002634 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002635 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002636 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002637
Steve Naroff874e2322007-11-15 10:28:18 +00002638 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002639 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002640 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2641 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002642 FieldTypes[i], 0,
2643 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002644 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002645 }
Mike Stump1eb44332009-09-09 15:08:12 +00002646
Douglas Gregor838db382010-02-11 01:19:42 +00002647 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002648 }
2649 return Context->getTagDeclType(SuperStructDecl);
2650}
2651
Steve Naroffb29b4272008-04-14 22:03:09 +00002652QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002653 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002654 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002655 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002656 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002657 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002659 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002660 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002661 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002662 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002663 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002664 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002665 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002666 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002667
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002668 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002669 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002670 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2671 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002672 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002673 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002674 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002675 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002676 }
2677
Douglas Gregor838db382010-02-11 01:19:42 +00002678 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002679 }
2680 return Context->getTagDeclType(ConstantStringDecl);
2681}
2682
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002683Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2684 SourceLocation StartLoc,
2685 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002686 if (!SelGetUidFunctionDecl)
2687 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002688 if (!MsgSendFunctionDecl)
2689 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002690 if (!MsgSendSuperFunctionDecl)
2691 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002692 if (!MsgSendStretFunctionDecl)
2693 SynthMsgSendStretFunctionDecl();
2694 if (!MsgSendSuperStretFunctionDecl)
2695 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002696 if (!MsgSendFpretFunctionDecl)
2697 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002698 if (!GetClassFunctionDecl)
2699 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002700 if (!GetSuperClassFunctionDecl)
2701 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002702 if (!GetMetaClassFunctionDecl)
2703 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002704
Steve Naroff874e2322007-11-15 10:28:18 +00002705 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002706 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2707 // May need to use objc_msgSend_stret() as well.
2708 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002709 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2710 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002711 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002712 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002713 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002714 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002715 }
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Steve Naroff934f2762007-10-24 22:48:43 +00002717 // Synthesize a call to objc_msgSend().
2718 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002719 switch (Exp->getReceiverKind()) {
2720 case ObjCMessageExpr::SuperClass: {
2721 MsgSendFlavor = MsgSendSuperFunctionDecl;
2722 if (MsgSendStretFlavor)
2723 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2724 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002727
Douglas Gregor04badcf2010-04-21 00:45:42 +00002728 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002729
Douglas Gregor04badcf2010-04-21 00:45:42 +00002730 // set the receiver to self, the first argument to all methods.
2731 InitExprs.push_back(
2732 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2733 CastExpr::CK_Unknown,
2734 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2735 Context->getObjCIdType(),
2736 SourceLocation()))
2737 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2740 llvm::SmallVector<Expr*, 8> ClsExprs;
2741 QualType argType = Context->getPointerType(Context->CharTy);
2742 ClsExprs.push_back(StringLiteral::Create(*Context,
2743 ClassDecl->getIdentifier()->getNameStart(),
2744 ClassDecl->getIdentifier()->getLength(),
2745 false, argType, SourceLocation()));
2746 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2747 &ClsExprs[0],
2748 ClsExprs.size(),
2749 StartLoc,
2750 EndLoc);
2751 // (Class)objc_getClass("CurrentClass")
2752 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2753 Context->getObjCClassType(),
2754 CastExpr::CK_Unknown, Cls);
2755 ClsExprs.clear();
2756 ClsExprs.push_back(ArgExpr);
2757 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2758 &ClsExprs[0], ClsExprs.size(),
2759 StartLoc, EndLoc);
2760
2761 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2762 // To turn off a warning, type-cast to 'id'
2763 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2764 NoTypeInfoCStyleCastExpr(Context,
2765 Context->getObjCIdType(),
2766 CastExpr::CK_Unknown, Cls));
2767 // struct objc_super
2768 QualType superType = getSuperStructType();
2769 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002770
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 if (LangOpts.Microsoft) {
2772 SynthSuperContructorFunctionDecl();
2773 // Simulate a contructor call...
2774 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2775 superType, SourceLocation());
2776 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2777 InitExprs.size(),
2778 superType, SourceLocation());
2779 // The code for super is a little tricky to prevent collision with
2780 // the structure definition in the header. The rewriter has it's own
2781 // internal definition (__rw_objc_super) that is uses. This is why
2782 // we need the cast below. For example:
2783 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2784 //
2785 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2786 Context->getPointerType(SuperRep->getType()),
2787 SourceLocation());
2788 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2789 Context->getPointerType(superType),
2790 CastExpr::CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002791 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002792 // (struct objc_super) { <exprs from above> }
2793 InitListExpr *ILE =
2794 new (Context) InitListExpr(*Context, SourceLocation(),
2795 &InitExprs[0], InitExprs.size(),
2796 SourceLocation());
2797 TypeSourceInfo *superTInfo
2798 = Context->getTrivialTypeSourceInfo(superType);
2799 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2800 superType, ILE, false);
2801 // struct objc_super *
2802 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2803 Context->getPointerType(SuperRep->getType()),
2804 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002805 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002806 MsgExprs.push_back(SuperRep);
2807 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002808 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809
2810 case ObjCMessageExpr::Class: {
2811 llvm::SmallVector<Expr*, 8> ClsExprs;
2812 QualType argType = Context->getPointerType(Context->CharTy);
2813 ObjCInterfaceDecl *Class
2814 = Exp->getClassReceiver()->getAs<ObjCInterfaceType>()->getDecl();
2815 IdentifierInfo *clsName = Class->getIdentifier();
2816 ClsExprs.push_back(StringLiteral::Create(*Context,
2817 clsName->getNameStart(),
2818 clsName->getLength(),
2819 false, argType,
2820 SourceLocation()));
2821 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2822 &ClsExprs[0],
2823 ClsExprs.size(),
2824 StartLoc, EndLoc);
2825 MsgExprs.push_back(Cls);
2826 break;
2827 }
2828
2829 case ObjCMessageExpr::SuperInstance:{
2830 MsgSendFlavor = MsgSendSuperFunctionDecl;
2831 if (MsgSendStretFlavor)
2832 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2833 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2834 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2835 llvm::SmallVector<Expr*, 4> InitExprs;
2836
2837 InitExprs.push_back(
2838 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2839 CastExpr::CK_Unknown,
2840 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2841 Context->getObjCIdType(),
2842 SourceLocation()))
2843 ); // set the 'receiver'.
2844
2845 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2846 llvm::SmallVector<Expr*, 8> ClsExprs;
2847 QualType argType = Context->getPointerType(Context->CharTy);
2848 ClsExprs.push_back(StringLiteral::Create(*Context,
2849 ClassDecl->getIdentifier()->getNameStart(),
2850 ClassDecl->getIdentifier()->getLength(),
2851 false, argType, SourceLocation()));
2852 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2853 &ClsExprs[0],
2854 ClsExprs.size(),
2855 StartLoc, EndLoc);
2856 // (Class)objc_getClass("CurrentClass")
2857 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2858 Context->getObjCClassType(),
2859 CastExpr::CK_Unknown, Cls);
2860 ClsExprs.clear();
2861 ClsExprs.push_back(ArgExpr);
2862 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2863 &ClsExprs[0], ClsExprs.size(),
2864 StartLoc, EndLoc);
2865
2866 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2867 // To turn off a warning, type-cast to 'id'
2868 InitExprs.push_back(
2869 // set 'super class', using class_getSuperclass().
2870 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2871 CastExpr::CK_Unknown, Cls));
2872 // struct objc_super
2873 QualType superType = getSuperStructType();
2874 Expr *SuperRep;
2875
2876 if (LangOpts.Microsoft) {
2877 SynthSuperContructorFunctionDecl();
2878 // Simulate a contructor call...
2879 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2880 superType, SourceLocation());
2881 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2882 InitExprs.size(),
2883 superType, SourceLocation());
2884 // The code for super is a little tricky to prevent collision with
2885 // the structure definition in the header. The rewriter has it's own
2886 // internal definition (__rw_objc_super) that is uses. This is why
2887 // we need the cast below. For example:
2888 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2889 //
2890 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2891 Context->getPointerType(SuperRep->getType()),
2892 SourceLocation());
2893 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2894 Context->getPointerType(superType),
2895 CastExpr::CK_Unknown, SuperRep);
2896 } else {
2897 // (struct objc_super) { <exprs from above> }
2898 InitListExpr *ILE =
2899 new (Context) InitListExpr(*Context, SourceLocation(),
2900 &InitExprs[0], InitExprs.size(),
2901 SourceLocation());
2902 TypeSourceInfo *superTInfo
2903 = Context->getTrivialTypeSourceInfo(superType);
2904 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2905 superType, ILE, false);
2906 }
2907 MsgExprs.push_back(SuperRep);
2908 break;
2909 }
2910
2911 case ObjCMessageExpr::Instance: {
2912 // Remove all type-casts because it may contain objc-style types; e.g.
2913 // Foo<Proto> *.
2914 Expr *recExpr = Exp->getInstanceReceiver();
2915 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2916 recExpr = CE->getSubExpr();
2917 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2918 CastExpr::CK_Unknown, recExpr);
2919 MsgExprs.push_back(recExpr);
2920 break;
2921 }
2922 }
2923
Steve Naroffbeaf2992007-11-03 11:27:19 +00002924 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002925 llvm::SmallVector<Expr*, 8> SelExprs;
2926 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002927 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002928 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002929 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002930 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002931 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002932 &SelExprs[0], SelExprs.size(),
2933 StartLoc,
2934 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002935 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002936
Steve Naroff934f2762007-10-24 22:48:43 +00002937 // Now push any user supplied arguments.
2938 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002939 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002940 // Make all implicit casts explicit...ICE comes in handy:-)
2941 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2942 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002943 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002944 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002945 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002946 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2947 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002948 }
2949 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002950 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002951 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002952 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002953 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002954 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2955 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002956 }
Mike Stump1eb44332009-09-09 15:08:12 +00002957 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002958 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002959 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2960 // out the argument in the original expression (since we aren't deleting
2961 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2962 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002963 }
Steve Naroffab972d32007-11-04 22:37:50 +00002964 // Generate the funky cast.
2965 CastExpr *cast;
2966 llvm::SmallVector<QualType, 8> ArgTypes;
2967 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Steve Naroffab972d32007-11-04 22:37:50 +00002969 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002970 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2971 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2972 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002973 ArgTypes.push_back(Context->getObjCIdType());
2974 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002975 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002976 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002977 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2978 E = OMD->param_end(); PI != E; ++PI) {
2979 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002980 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002981 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002982 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002983 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002984 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002985 t = Context->getPointerType(BPT->getPointeeType());
2986 }
Steve Naroff352336b2007-11-05 14:36:37 +00002987 ArgTypes.push_back(t);
2988 }
Chris Lattner89951a82009-02-20 18:43:26 +00002989 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2990 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002991 if (isTopLevelBlockPointerType(returnType)) {
2992 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2993 returnType = Context->getPointerType(BPT->getPointeeType());
2994 }
Steve Naroffab972d32007-11-04 22:37:50 +00002995 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002996 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002997 }
2998 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002999 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003000
Steve Naroffab972d32007-11-04 22:37:50 +00003001 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003002 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003003 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003004
Mike Stump1eb44332009-09-09 15:08:12 +00003005 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003006 // If we don't do this cast, we get the following bizarre warning/note:
3007 // xx.m:13: warning: function called through a non-compatible type
3008 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003009 cast = NoTypeInfoCStyleCastExpr(Context,
3010 Context->getPointerType(Context->VoidTy),
3011 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Steve Naroffab972d32007-11-04 22:37:50 +00003013 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003014 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003015 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003016 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003017 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003018 false, false, 0, 0,
3019 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003020 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003021 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3022 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003023
3024 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003025 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003026
John McCall183700f2009-09-21 23:43:11 +00003027 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003028 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003029 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003030 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003031 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003032 if (MsgSendStretFlavor) {
3033 // We have the method which returns a struct/union. Must also generate
3034 // call to objc_msgSend_stret and hang both varieties on a conditional
3035 // expression which dictate which one to envoke depending on size of
3036 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003037
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003038 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003039 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 SourceLocation());
3041 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003042 cast = NoTypeInfoCStyleCastExpr(Context,
3043 Context->getPointerType(Context->VoidTy),
3044 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003045 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003046 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003047 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003048 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003049 false, false, 0, 0,
3050 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003051 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003052 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3053 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003055 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003056 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003057
John McCall183700f2009-09-21 23:43:11 +00003058 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003059 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003060 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003061 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003062
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003063 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003064 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003065 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003066 Context->getSizeType(),
3067 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003068 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3069 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3070 // For X86 it is more complicated and some kind of target specific routine
3071 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003072 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003073 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00003074 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003075 Context->IntTy,
3076 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003077 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3078 BinaryOperator::LE,
3079 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003080 SourceLocation());
3081 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003082 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003083 new (Context) ConditionalOperator(lessThanExpr,
3084 SourceLocation(), CE,
3085 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003086 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003087 }
Mike Stump1eb44332009-09-09 15:08:12 +00003088 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003089 return ReplacingStmt;
3090}
3091
Steve Naroffb29b4272008-04-14 22:03:09 +00003092Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003093 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3094 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003095
Steve Naroff934f2762007-10-24 22:48:43 +00003096 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003097 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003098
3099 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003100 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003101}
3102
Steve Naroff621edce2009-04-29 16:37:50 +00003103// typedef struct objc_object Protocol;
3104QualType RewriteObjC::getProtocolType() {
3105 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003106 TypeSourceInfo *TInfo
3107 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003108 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003109 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003110 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003111 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003112 }
3113 return Context->getTypeDeclType(ProtocolTypeDecl);
3114}
3115
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003116/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003117/// a synthesized/forward data reference (to the protocol's metadata).
3118/// The forward references (and metadata) are generated in
3119/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003120Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003121 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3122 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003123 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003124 ID, getProtocolType(), 0,
3125 VarDecl::Extern, VarDecl::None);
Steve Naroff621edce2009-04-29 16:37:50 +00003126 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3127 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3128 Context->getPointerType(DRE->getType()),
3129 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003130 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3131 CastExpr::CK_Unknown,
3132 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003133 ReplaceStmt(Exp, castExpr);
3134 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003135 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003136 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003138}
3139
Mike Stump1eb44332009-09-09 15:08:12 +00003140bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003141 const char *endBuf) {
3142 while (startBuf < endBuf) {
3143 if (*startBuf == '#') {
3144 // Skip whitespace.
3145 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3146 ;
3147 if (!strncmp(startBuf, "if", strlen("if")) ||
3148 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3149 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3150 !strncmp(startBuf, "define", strlen("define")) ||
3151 !strncmp(startBuf, "undef", strlen("undef")) ||
3152 !strncmp(startBuf, "else", strlen("else")) ||
3153 !strncmp(startBuf, "elif", strlen("elif")) ||
3154 !strncmp(startBuf, "endif", strlen("endif")) ||
3155 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3156 !strncmp(startBuf, "include", strlen("include")) ||
3157 !strncmp(startBuf, "import", strlen("import")) ||
3158 !strncmp(startBuf, "include_next", strlen("include_next")))
3159 return true;
3160 }
3161 startBuf++;
3162 }
3163 return false;
3164}
3165
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003167/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003168void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003169 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003171 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003172 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003173 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003174 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003175 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003176 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003177 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003178 SourceLocation LocStart = CDecl->getLocStart();
3179 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Steve Narofffea763e82007-11-14 19:25:57 +00003181 const char *startBuf = SM->getCharacterData(LocStart);
3182 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003184 // If no ivars and no root or if its root, directly or indirectly,
3185 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003186 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3187 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003188 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003189 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003190 return;
3191 }
Mike Stump1eb44332009-09-09 15:08:12 +00003192
3193 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003194 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003195 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003196 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003197 if (LangOpts.Microsoft)
3198 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003199
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003200 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003201 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003202 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003203 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003204 // If the buffer contains preprocessor directives, we do more fine-grained
3205 // rewrites. This is intended to fix code that looks like (which occurs in
3206 // NSURL.h, for example):
3207 //
3208 // #ifdef XYZ
3209 // @interface Foo : NSObject
3210 // #else
3211 // @interface FooBar : NSObject
3212 // #endif
3213 // {
3214 // int i;
3215 // }
3216 // @end
3217 //
3218 // This clause is segregated to avoid breaking the common case.
3219 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003220 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003221 CDecl->getClassLoc();
3222 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003223 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003224
Chris Lattnercafeb352009-02-20 18:18:36 +00003225 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003226 // advance to the end of the referenced protocols.
3227 while (endHeader < cursor && *endHeader != '>') endHeader++;
3228 endHeader++;
3229 }
3230 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003231 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003232 } else {
3233 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003234 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003235 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003236 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003237 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003239 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003240 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003241 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003242
Steve Narofffea763e82007-11-14 19:25:57 +00003243 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003244 SourceLocation OnePastCurly =
3245 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003246 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003247 }
3248 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003249
Steve Narofffea763e82007-11-14 19:25:57 +00003250 // Now comment out any visibility specifiers.
3251 while (cursor < endBuf) {
3252 if (*cursor == '@') {
3253 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003254 // Skip whitespace.
3255 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3256 /*scan*/;
3257
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003258 // FIXME: presence of @public, etc. inside comment results in
3259 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003260 if (!strncmp(cursor, "public", strlen("public")) ||
3261 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003262 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003263 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003264 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003265 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003266 // FIXME: If there are cases where '<' is used in ivar declaration part
3267 // of user code, then scan the ivar list and use needToScanForQualifiers
3268 // for type checking.
3269 else if (*cursor == '<') {
3270 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003271 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003272 cursor = strchr(cursor, '>');
3273 cursor++;
3274 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003275 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003276 } else if (*cursor == '^') { // rewrite block specifier.
3277 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003278 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003279 }
Steve Narofffea763e82007-11-14 19:25:57 +00003280 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003281 }
Steve Narofffea763e82007-11-14 19:25:57 +00003282 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003283 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003284 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003285 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003286 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003287 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003288 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003289 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003290 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003291 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003292 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003293 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003294 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003295 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003296}
3297
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003298// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003299/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003300template<typename MethodIterator>
3301void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3302 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003303 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003304 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003305 const char *ClassName,
3306 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003307 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003309 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003310 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003311 SEL _cmd;
3312 char *method_types;
3313 void *_imp;
3314 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003315 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003316 Result += "\nstruct _objc_method {\n";
3317 Result += "\tSEL _cmd;\n";
3318 Result += "\tchar *method_types;\n";
3319 Result += "\tvoid *_imp;\n";
3320 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003322 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003323 }
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003325 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Steve Naroff946a6932008-03-11 00:12:29 +00003327 /* struct {
3328 struct _objc_method_list *next_method;
3329 int method_count;
3330 struct _objc_method method_list[];
3331 }
3332 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003333 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003334 Result += "\nstatic struct {\n";
3335 Result += "\tstruct _objc_method_list *next_method;\n";
3336 Result += "\tint method_count;\n";
3337 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003338 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003339 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003340 Result += prefix;
3341 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3342 Result += "_METHODS_";
3343 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003344 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003345 Result += IsInstanceMethod ? "inst" : "cls";
3346 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003347 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003348
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003349 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003350 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003351 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003352 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003353 Result += "\", \"";
3354 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003355 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003356 Result += MethodInternalNames[*MethodBegin];
3357 Result += "}\n";
3358 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3359 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003360 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003361 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003362 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003363 Result += "\", \"";
3364 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003365 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003366 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003367 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003368 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003369 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003370}
3371
Steve Naroff621edce2009-04-29 16:37:50 +00003372/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003373void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003374RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3375 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003376 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003377
3378 // Output struct protocol_methods holder of method selector and type.
3379 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3380 /* struct protocol_methods {
3381 SEL _cmd;
3382 char *method_types;
3383 }
3384 */
3385 Result += "\nstruct _protocol_methods {\n";
3386 Result += "\tstruct objc_selector *_cmd;\n";
3387 Result += "\tchar *method_types;\n";
3388 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Steve Naroff621edce2009-04-29 16:37:50 +00003390 objc_protocol_methods = true;
3391 }
3392 // Do not synthesize the protocol more than once.
3393 if (ObjCSynthesizedProtocols.count(PDecl))
3394 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003396 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3397 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3398 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003399 /* struct _objc_protocol_method_list {
3400 int protocol_method_count;
3401 struct protocol_methods protocols[];
3402 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003403 */
Steve Naroff621edce2009-04-29 16:37:50 +00003404 Result += "\nstatic struct {\n";
3405 Result += "\tint protocol_method_count;\n";
3406 Result += "\tstruct _protocol_methods protocol_methods[";
3407 Result += utostr(NumMethods);
3408 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3409 Result += PDecl->getNameAsString();
3410 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3411 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Steve Naroff621edce2009-04-29 16:37:50 +00003413 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003414 for (ObjCProtocolDecl::instmeth_iterator
3415 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003416 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003417 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003418 Result += "\t ,{{(struct objc_selector *)\"";
3419 else
3420 Result += "\t ,{(struct objc_selector *)\"";
3421 Result += (*I)->getSelector().getAsString().c_str();
3422 std::string MethodTypeString;
3423 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3424 Result += "\", \"";
3425 Result += MethodTypeString;
3426 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003427 }
Steve Naroff621edce2009-04-29 16:37:50 +00003428 Result += "\t }\n};\n";
3429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Steve Naroff621edce2009-04-29 16:37:50 +00003431 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003432 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3433 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003434 if (NumMethods > 0) {
3435 /* struct _objc_protocol_method_list {
3436 int protocol_method_count;
3437 struct protocol_methods protocols[];
3438 }
3439 */
3440 Result += "\nstatic struct {\n";
3441 Result += "\tint protocol_method_count;\n";
3442 Result += "\tstruct _protocol_methods protocol_methods[";
3443 Result += utostr(NumMethods);
3444 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3445 Result += PDecl->getNameAsString();
3446 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3447 "{\n\t";
3448 Result += utostr(NumMethods);
3449 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Steve Naroff621edce2009-04-29 16:37:50 +00003451 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003452 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003453 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003454 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003455 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003456 Result += "\t ,{{(struct objc_selector *)\"";
3457 else
3458 Result += "\t ,{(struct objc_selector *)\"";
3459 Result += (*I)->getSelector().getAsString().c_str();
3460 std::string MethodTypeString;
3461 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3462 Result += "\", \"";
3463 Result += MethodTypeString;
3464 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003465 }
Steve Naroff621edce2009-04-29 16:37:50 +00003466 Result += "\t }\n};\n";
3467 }
3468
3469 // Output:
3470 /* struct _objc_protocol {
3471 // Objective-C 1.0 extensions
3472 struct _objc_protocol_extension *isa;
3473 char *protocol_name;
3474 struct _objc_protocol **protocol_list;
3475 struct _objc_protocol_method_list *instance_methods;
3476 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003477 };
Steve Naroff621edce2009-04-29 16:37:50 +00003478 */
3479 static bool objc_protocol = false;
3480 if (!objc_protocol) {
3481 Result += "\nstruct _objc_protocol {\n";
3482 Result += "\tstruct _objc_protocol_extension *isa;\n";
3483 Result += "\tchar *protocol_name;\n";
3484 Result += "\tstruct _objc_protocol **protocol_list;\n";
3485 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3486 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003487 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Steve Naroff621edce2009-04-29 16:37:50 +00003489 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003490 }
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Steve Naroff621edce2009-04-29 16:37:50 +00003492 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3493 Result += PDecl->getNameAsString();
3494 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3495 "{\n\t0, \"";
3496 Result += PDecl->getNameAsString();
3497 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003498 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003499 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3500 Result += PDecl->getNameAsString();
3501 Result += ", ";
3502 }
3503 else
3504 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003505 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003506 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3507 Result += PDecl->getNameAsString();
3508 Result += "\n";
3509 }
3510 else
3511 Result += "0\n";
3512 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003513
Steve Naroff621edce2009-04-29 16:37:50 +00003514 // Mark this protocol as having been generated.
3515 if (!ObjCSynthesizedProtocols.insert(PDecl))
3516 assert(false && "protocol already synthesized");
3517
3518}
3519
3520void RewriteObjC::
3521RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3522 const char *prefix, const char *ClassName,
3523 std::string &Result) {
3524 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Steve Naroff621edce2009-04-29 16:37:50 +00003526 for (unsigned i = 0; i != Protocols.size(); i++)
3527 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3528
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003529 // Output the top lovel protocol meta-data for the class.
3530 /* struct _objc_protocol_list {
3531 struct _objc_protocol_list *next;
3532 int protocol_count;
3533 struct _objc_protocol *class_protocols[];
3534 }
3535 */
3536 Result += "\nstatic struct {\n";
3537 Result += "\tstruct _objc_protocol_list *next;\n";
3538 Result += "\tint protocol_count;\n";
3539 Result += "\tstruct _objc_protocol *class_protocols[";
3540 Result += utostr(Protocols.size());
3541 Result += "];\n} _OBJC_";
3542 Result += prefix;
3543 Result += "_PROTOCOLS_";
3544 Result += ClassName;
3545 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3546 "{\n\t0, ";
3547 Result += utostr(Protocols.size());
3548 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003549
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003550 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003551 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003552 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003553
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003554 for (unsigned i = 1; i != Protocols.size(); i++) {
3555 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003556 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003557 Result += "\n";
3558 }
3559 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003560}
3561
Steve Naroff621edce2009-04-29 16:37:50 +00003562
Mike Stump1eb44332009-09-09 15:08:12 +00003563/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003564/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003565void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003566 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003567 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003568 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003569 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003570 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003571 CDecl = CDecl->getNextClassCategory())
3572 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3573 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003574
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003575 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003576 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003578
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003579 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003580 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003581 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003582
3583 // If any of our property implementations have associated getters or
3584 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003585 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3586 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003587 Prop != PropEnd; ++Prop) {
3588 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3589 continue;
3590 if (!(*Prop)->getPropertyIvarDecl())
3591 continue;
3592 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3593 if (!PD)
3594 continue;
3595 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3596 InstanceMethods.push_back(Getter);
3597 if (PD->isReadOnly())
3598 continue;
3599 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3600 InstanceMethods.push_back(Setter);
3601 }
3602 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003603 true, "CATEGORY_", FullCategoryName.c_str(),
3604 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003605
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003606 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003607 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003608 false, "CATEGORY_", FullCategoryName.c_str(),
3609 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003611 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003612 // Null CDecl is case of a category implementation with no category interface
3613 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003614 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3615 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003616 /* struct _objc_category {
3617 char *category_name;
3618 char *class_name;
3619 struct _objc_method_list *instance_methods;
3620 struct _objc_method_list *class_methods;
3621 struct _objc_protocol_list *protocols;
3622 // Objective-C 1.0 extensions
3623 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003624 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003625 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003626 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003627 */
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003629 static bool objc_category = false;
3630 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003631 Result += "\nstruct _objc_category {\n";
3632 Result += "\tchar *category_name;\n";
3633 Result += "\tchar *class_name;\n";
3634 Result += "\tstruct _objc_method_list *instance_methods;\n";
3635 Result += "\tstruct _objc_method_list *class_methods;\n";
3636 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003637 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003638 Result += "\tstruct _objc_property_list *instance_properties;\n";
3639 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003640 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003641 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003642 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3643 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003644 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003645 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003646 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003647 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003648 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003650 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003651 Result += "\t, (struct _objc_method_list *)"
3652 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3653 Result += FullCategoryName;
3654 Result += "\n";
3655 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003656 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003657 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003658 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003659 Result += "\t, (struct _objc_method_list *)"
3660 "&_OBJC_CATEGORY_CLASS_METHODS_";
3661 Result += FullCategoryName;
3662 Result += "\n";
3663 }
3664 else
3665 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Chris Lattnercafeb352009-02-20 18:18:36 +00003667 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003668 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003669 Result += FullCategoryName;
3670 Result += "\n";
3671 }
3672 else
3673 Result += "\t, 0\n";
3674 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003675}
3676
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003677/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3678/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003679void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003680 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003681 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003682 if (ivar->isBitField()) {
3683 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3684 // place all bitfields at offset 0.
3685 Result += "0";
3686 } else {
3687 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003688 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003689 if (LangOpts.Microsoft)
3690 Result += "_IMPL";
3691 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003693 Result += ")";
3694 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003695}
3696
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003697//===----------------------------------------------------------------------===//
3698// Meta Data Emission
3699//===----------------------------------------------------------------------===//
3700
Steve Naroffb29b4272008-04-14 22:03:09 +00003701void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003702 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003703 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003704
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003705 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003706 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003707 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003708 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003709 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003710 }
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Chris Lattnerbe6df082007-12-12 07:56:42 +00003712 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003713 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003714 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003715 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003716 if (NumIvars > 0) {
3717 static bool objc_ivar = false;
3718 if (!objc_ivar) {
3719 /* struct _objc_ivar {
3720 char *ivar_name;
3721 char *ivar_type;
3722 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003723 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003724 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003725 Result += "\nstruct _objc_ivar {\n";
3726 Result += "\tchar *ivar_name;\n";
3727 Result += "\tchar *ivar_type;\n";
3728 Result += "\tint ivar_offset;\n";
3729 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003731 objc_ivar = true;
3732 }
3733
Steve Naroff946a6932008-03-11 00:12:29 +00003734 /* struct {
3735 int ivar_count;
3736 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003737 };
Steve Naroff946a6932008-03-11 00:12:29 +00003738 */
Mike Stump1eb44332009-09-09 15:08:12 +00003739 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003740 Result += "\tint ivar_count;\n";
3741 Result += "\tstruct _objc_ivar ivar_list[";
3742 Result += utostr(NumIvars);
3743 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003744 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003745 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003746 "{\n\t";
3747 Result += utostr(NumIvars);
3748 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003749
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003750 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003751 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003752 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003753 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003754 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003755 IV != IVEnd; ++IV)
3756 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003757 IVI = IDecl->ivar_begin();
3758 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003759 } else {
3760 IVI = CDecl->ivar_begin();
3761 IVE = CDecl->ivar_end();
3762 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003763 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003764 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003765 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003766 std::string TmpString, StrEncoding;
3767 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3768 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003769 Result += StrEncoding;
3770 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003771 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003772 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003773 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003775 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003776 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003777 std::string TmpString, StrEncoding;
3778 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3779 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003780 Result += StrEncoding;
3781 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003782 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003783 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 }
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003786 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003787 }
Mike Stump1eb44332009-09-09 15:08:12 +00003788
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003789 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003790 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003791 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003792
3793 // If any of our property implementations have associated getters or
3794 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003795 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3796 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003797 Prop != PropEnd; ++Prop) {
3798 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3799 continue;
3800 if (!(*Prop)->getPropertyIvarDecl())
3801 continue;
3802 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3803 if (!PD)
3804 continue;
3805 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3806 InstanceMethods.push_back(Getter);
3807 if (PD->isReadOnly())
3808 continue;
3809 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3810 InstanceMethods.push_back(Setter);
3811 }
3812 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003813 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003814
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003815 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003816 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003817 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003819 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003820 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3821 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003823 // Declaration of class/meta-class metadata
3824 /* struct _objc_class {
3825 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003826 const char *super_class_name;
3827 char *name;
3828 long version;
3829 long info;
3830 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003831 struct _objc_ivar_list *ivars;
3832 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003833 struct objc_cache *cache;
3834 struct objc_protocol_list *protocols;
3835 const char *ivar_layout;
3836 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003837 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003838 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003839 static bool objc_class = false;
3840 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003841 Result += "\nstruct _objc_class {\n";
3842 Result += "\tstruct _objc_class *isa;\n";
3843 Result += "\tconst char *super_class_name;\n";
3844 Result += "\tchar *name;\n";
3845 Result += "\tlong version;\n";
3846 Result += "\tlong info;\n";
3847 Result += "\tlong instance_size;\n";
3848 Result += "\tstruct _objc_ivar_list *ivars;\n";
3849 Result += "\tstruct _objc_method_list *methods;\n";
3850 Result += "\tstruct objc_cache *cache;\n";
3851 Result += "\tstruct _objc_protocol_list *protocols;\n";
3852 Result += "\tconst char *ivar_layout;\n";
3853 Result += "\tstruct _objc_class_ext *ext;\n";
3854 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003855 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003856 }
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003858 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003859 ObjCInterfaceDecl *RootClass = 0;
3860 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003861 while (SuperClass) {
3862 RootClass = SuperClass;
3863 SuperClass = SuperClass->getSuperClass();
3864 }
3865 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003867 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003868 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003869 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003870 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003871 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003872 Result += "\"";
3873
3874 if (SuperClass) {
3875 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003876 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003877 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003878 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003879 Result += "\"";
3880 }
3881 else {
3882 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003883 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003884 Result += "\"";
3885 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003886 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003887 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003888 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003889 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003890 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003891 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003892 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003893 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003894 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003895 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003896 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003897 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003898 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003899 Result += ",0,0\n";
3900 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003901 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003902 Result += "\t,0,0,0,0\n";
3903 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003905 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003906 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003907 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003908 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003909 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003910 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003911 if (SuperClass) {
3912 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003913 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003914 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003915 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += "\"";
3917 }
3918 else {
3919 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003921 Result += "\"";
3922 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003923 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003924 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003925 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003926 Result += ",0";
3927 else {
3928 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003929 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003930 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003931 if (LangOpts.Microsoft)
3932 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003933 Result += ")";
3934 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003935 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003936 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003937 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += "\n\t";
3939 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003940 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003941 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003942 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003943 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003944 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003945 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003946 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003947 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003948 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003949 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003950 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 Result += ", 0,0\n";
3953 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003954 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003955 Result += ",0,0,0\n";
3956 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003957}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003958
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003959/// RewriteImplementations - This routine rewrites all method implementations
3960/// and emits meta-data.
3961
Steve Narofface66252008-11-13 20:07:04 +00003962void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003963 int ClsDefCount = ClassImplementation.size();
3964 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003966 // Rewrite implemented methods
3967 for (int i = 0; i < ClsDefCount; i++)
3968 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003970 for (int i = 0; i < CatDefCount; i++)
3971 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003972}
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Steve Narofface66252008-11-13 20:07:04 +00003974void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3975 int ClsDefCount = ClassImplementation.size();
3976 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003977
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003978 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003979 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003980 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003982 // For each implemented category, write out all its meta data.
3983 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003984 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003985
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003986 // Write objc_symtab metadata
3987 /*
3988 struct _objc_symtab
3989 {
3990 long sel_ref_cnt;
3991 SEL *refs;
3992 short cls_def_cnt;
3993 short cat_def_cnt;
3994 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003995 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003996 */
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003998 Result += "\nstruct _objc_symtab {\n";
3999 Result += "\tlong sel_ref_cnt;\n";
4000 Result += "\tSEL *refs;\n";
4001 Result += "\tshort cls_def_cnt;\n";
4002 Result += "\tshort cat_def_cnt;\n";
4003 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4004 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004006 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004007 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004008 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 + ", " + utostr(CatDefCount) + "\n";
4010 for (int i = 0; i < ClsDefCount; i++) {
4011 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004012 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004013 Result += "\n";
4014 }
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 for (int i = 0; i < CatDefCount; i++) {
4017 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004019 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\n";
4022 }
Mike Stump1eb44332009-09-09 15:08:12 +00004023
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004024 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004026 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004027
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004028 /*
4029 struct _objc_module {
4030 long version;
4031 long size;
4032 const char *name;
4033 struct _objc_symtab *symtab;
4034 }
4035 */
Mike Stump1eb44332009-09-09 15:08:12 +00004036
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004037 Result += "\nstruct _objc_module {\n";
4038 Result += "\tlong version;\n";
4039 Result += "\tlong size;\n";
4040 Result += "\tconst char *name;\n";
4041 Result += "\tstruct _objc_symtab *symtab;\n";
4042 Result += "};\n\n";
4043 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004044 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004045 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004046 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004047 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004048
4049 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004050 if (ProtocolExprDecls.size()) {
4051 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4052 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004053 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004054 E = ProtocolExprDecls.end(); I != E; ++I) {
4055 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4056 Result += (*I)->getNameAsString();
4057 Result += " = &_OBJC_PROTOCOL_";
4058 Result += (*I)->getNameAsString();
4059 Result += ";\n";
4060 }
4061 Result += "#pragma data_seg(pop)\n\n";
4062 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004063 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004064 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004065 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4066 Result += "&_OBJC_MODULES;\n";
4067 Result += "#pragma data_seg(pop)\n\n";
4068 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004069}
Chris Lattner311ff022007-10-16 22:36:42 +00004070
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004071void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4072 const std::string &Name,
4073 ValueDecl *VD) {
4074 assert(BlockByRefDeclNo.count(VD) &&
4075 "RewriteByRefString: ByRef decl missing");
4076 ResultStr += "struct __Block_byref_" + Name +
4077 "_" + utostr(BlockByRefDeclNo[VD]) ;
4078}
4079
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004080static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4081 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4082 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4083 return false;
4084}
4085
Steve Naroff54055232008-10-27 17:20:55 +00004086std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4087 const char *funcName,
4088 std::string Tag) {
4089 const FunctionType *AFT = CE->getFunctionType();
4090 QualType RT = AFT->getResultType();
4091 std::string StructRef = "struct " + Tag;
4092 std::string S = "static " + RT.getAsString() + " __" +
4093 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004094
Steve Naroff54055232008-10-27 17:20:55 +00004095 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Douglas Gregor72564e72009-02-26 23:50:07 +00004097 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004098 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004099 // block (to reference imported block decl refs).
4100 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004101 } else if (BD->param_empty()) {
4102 S += "(" + StructRef + " *__cself)";
4103 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004104 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004105 assert(FT && "SynthesizeBlockFunc: No function proto");
4106 S += '(';
4107 // first add the implicit argument.
4108 S += StructRef + " *__cself, ";
4109 std::string ParamStr;
4110 for (BlockDecl::param_iterator AI = BD->param_begin(),
4111 E = BD->param_end(); AI != E; ++AI) {
4112 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004113 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004114 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004115 S += ParamStr;
4116 }
4117 if (FT->isVariadic()) {
4118 if (!BD->param_empty()) S += ", ";
4119 S += "...";
4120 }
4121 S += ')';
4122 }
4123 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Steve Naroff54055232008-10-27 17:20:55 +00004125 // Create local declarations to avoid rewriting all closure decl ref exprs.
4126 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004127 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004128 E = BlockByRefDecls.end(); I != E; ++I) {
4129 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004130 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004131 std::string TypeString;
4132 RewriteByRefString(TypeString, Name, (*I));
4133 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004134 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004135 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004136 }
Steve Naroff54055232008-10-27 17:20:55 +00004137 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004138 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004139 E = BlockByCopyDecls.end(); I != E; ++I) {
4140 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004141 // Handle nested closure invocation. For example:
4142 //
4143 // void (^myImportedClosure)(void);
4144 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004145 //
Steve Naroff54055232008-10-27 17:20:55 +00004146 // void (^anotherClosure)(void);
4147 // anotherClosure = ^(void) {
4148 // myImportedClosure(); // import and invoke the closure
4149 // };
4150 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004151 if (isTopLevelBlockPointerType((*I)->getType())) {
4152 RewriteBlockPointerTypeVariable(S, (*I));
4153 S += " = (";
4154 RewriteBlockPointerType(S, (*I)->getType());
4155 S += ")";
4156 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4157 }
4158 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004159 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004160 QualType QT = (*I)->getType();
4161 if (HasLocalVariableExternalStorage(*I))
4162 QT = Context->getPointerType(QT);
4163 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004164 S += Name + " = __cself->" +
4165 (*I)->getNameAsString() + "; // bound by copy\n";
4166 }
Steve Naroff54055232008-10-27 17:20:55 +00004167 }
4168 std::string RewrittenStr = RewrittenBlockExprs[CE];
4169 const char *cstr = RewrittenStr.c_str();
4170 while (*cstr++ != '{') ;
4171 S += cstr;
4172 S += "\n";
4173 return S;
4174}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004175
Steve Naroff54055232008-10-27 17:20:55 +00004176std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4177 const char *funcName,
4178 std::string Tag) {
4179 std::string StructRef = "struct " + Tag;
4180 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004181
Steve Naroff54055232008-10-27 17:20:55 +00004182 S += funcName;
4183 S += "_block_copy_" + utostr(i);
4184 S += "(" + StructRef;
4185 S += "*dst, " + StructRef;
4186 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004187 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004188 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004189 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004190 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004191 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004192 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004193 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004194 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004195 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004196 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004197 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004198 S += "}\n";
4199
Steve Naroff54055232008-10-27 17:20:55 +00004200 S += "\nstatic void __";
4201 S += funcName;
4202 S += "_block_dispose_" + utostr(i);
4203 S += "(" + StructRef;
4204 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004205 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004206 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004207 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004208 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004209 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004210 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004211 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004212 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004215 return S;
4216}
4217
Steve Naroff01aec112009-12-06 21:14:13 +00004218std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4219 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004220 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004221 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004222
Steve Naroff54055232008-10-27 17:20:55 +00004223 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004224 S += " struct " + Desc;
4225 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004226
Steve Naroff01aec112009-12-06 21:14:13 +00004227 Constructor += "(void *fp, "; // Invoke function pointer.
4228 Constructor += "struct " + Desc; // Descriptor pointer.
4229 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Steve Naroff54055232008-10-27 17:20:55 +00004231 if (BlockDeclRefs.size()) {
4232 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004233 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004234 E = BlockByCopyDecls.end(); I != E; ++I) {
4235 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004236 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004237 std::string ArgName = "_" + FieldName;
4238 // Handle nested closure invocation. For example:
4239 //
4240 // void (^myImportedBlock)(void);
4241 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004242 //
Steve Naroff54055232008-10-27 17:20:55 +00004243 // void (^anotherBlock)(void);
4244 // anotherBlock = ^(void) {
4245 // myImportedBlock(); // import and invoke the closure
4246 // };
4247 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004248 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004249 S += "struct __block_impl *";
4250 Constructor += ", void *" + ArgName;
4251 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004252 QualType QT = (*I)->getType();
4253 if (HasLocalVariableExternalStorage(*I))
4254 QT = Context->getPointerType(QT);
4255 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4256 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004257 Constructor += ", " + ArgName;
4258 }
4259 S += FieldName + ";\n";
4260 }
4261 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004262 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004263 E = BlockByRefDecls.end(); I != E; ++I) {
4264 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004265 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004266 std::string ArgName = "_" + FieldName;
4267 // Handle nested closure invocation. For example:
4268 //
4269 // void (^myImportedBlock)(void);
4270 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004271 //
Steve Naroff54055232008-10-27 17:20:55 +00004272 // void (^anotherBlock)(void);
4273 // anotherBlock = ^(void) {
4274 // myImportedBlock(); // import and invoke the closure
4275 // };
4276 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004277 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004278 S += "struct __block_impl *";
4279 Constructor += ", void *" + ArgName;
4280 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004281 std::string TypeString;
4282 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004283 TypeString += " *";
4284 FieldName = TypeString + FieldName;
4285 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004286 Constructor += ", " + ArgName;
4287 }
4288 S += FieldName + "; // by ref\n";
4289 }
4290 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004291 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004292 if (GlobalVarDecl)
4293 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4294 else
4295 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004296 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004297
Steve Naroff01aec112009-12-06 21:14:13 +00004298 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004299
Steve Naroff54055232008-10-27 17:20:55 +00004300 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004301 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004302 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004303 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004304 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004305 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004306 Constructor += Name + " = (struct __block_impl *)_";
4307 else
4308 Constructor += Name + " = _";
4309 Constructor += Name + ";\n";
4310 }
4311 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004312 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004313 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004314 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004315 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004316 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004317 Constructor += Name + " = (struct __block_impl *)_";
4318 else
4319 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004320 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004321 }
4322 } else {
4323 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004324 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004325 if (GlobalVarDecl)
4326 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4327 else
4328 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004329 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4330 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004331 }
4332 Constructor += " ";
4333 Constructor += "}\n";
4334 S += Constructor;
4335 S += "};\n";
4336 return S;
4337}
4338
Steve Naroff01aec112009-12-06 21:14:13 +00004339std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4340 std::string ImplTag, int i,
4341 const char *FunName,
4342 unsigned hasCopy) {
4343 std::string S = "\nstatic struct " + DescTag;
4344
4345 S += " {\n unsigned long reserved;\n";
4346 S += " unsigned long Block_size;\n";
4347 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004348 S += " void (*copy)(struct ";
4349 S += ImplTag; S += "*, struct ";
4350 S += ImplTag; S += "*);\n";
4351
4352 S += " void (*dispose)(struct ";
4353 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004354 }
4355 S += "} ";
4356
4357 S += DescTag + "_DATA = { 0, sizeof(struct ";
4358 S += ImplTag + ")";
4359 if (hasCopy) {
4360 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4361 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4362 }
4363 S += "};\n";
4364 return S;
4365}
4366
Steve Naroff54055232008-10-27 17:20:55 +00004367void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004368 const char *FunName) {
4369 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004370 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004371 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004372 bool RewriteSC = (GlobalVarDecl &&
4373 !Blocks.empty() &&
4374 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4375 GlobalVarDecl->getType().getCVRQualifiers());
4376 if (RewriteSC) {
4377 std::string SC(" void __");
4378 SC += GlobalVarDecl->getNameAsString();
4379 SC += "() {}";
4380 InsertText(FunLocStart, SC);
4381 }
4382
Steve Naroff54055232008-10-27 17:20:55 +00004383 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004384 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4385 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004386 // Need to copy-in the inner copied-in variables not actually used in this
4387 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004388 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4389 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4390 ValueDecl *VD = Exp->getDecl();
4391 BlockDeclRefs.push_back(Exp);
4392 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4393 BlockByCopyDeclsPtrSet.insert(VD);
4394 BlockByCopyDecls.push_back(VD);
4395 }
4396 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4397 BlockByRefDeclsPtrSet.insert(VD);
4398 BlockByRefDecls.push_back(VD);
4399 }
4400 }
Steve Naroff54055232008-10-27 17:20:55 +00004401
Steve Naroff01aec112009-12-06 21:14:13 +00004402 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4403 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Steve Naroff01aec112009-12-06 21:14:13 +00004405 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004406
Benjamin Kramerd999b372010-02-14 14:14:16 +00004407 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004408
Steve Naroff01aec112009-12-06 21:14:13 +00004409 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004410
Benjamin Kramerd999b372010-02-14 14:14:16 +00004411 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004412
4413 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004414 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004415 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004416 }
Steve Naroff01aec112009-12-06 21:14:13 +00004417 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4418 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004419 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004420
Steve Naroff54055232008-10-27 17:20:55 +00004421 BlockDeclRefs.clear();
4422 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004423 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004424 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004425 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004426 ImportedBlockDecls.clear();
4427 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004428 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004429 // Must insert any 'const/volatile/static here. Since it has been
4430 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004431 std::string SC;
4432 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4433 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004434 if (GlobalVarDecl->getType().isConstQualified())
4435 SC += "const ";
4436 if (GlobalVarDecl->getType().isVolatileQualified())
4437 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004438 if (GlobalVarDecl->getType().isRestrictQualified())
4439 SC += "restrict ";
4440 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004441 }
4442
Steve Naroff54055232008-10-27 17:20:55 +00004443 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004444 InnerDeclRefsCount.clear();
4445 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004446 RewrittenBlockExprs.clear();
4447}
4448
4449void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4450 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004451 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Steve Naroff54055232008-10-27 17:20:55 +00004453 SynthesizeBlockLiterals(FunLocStart, FuncName);
4454}
4455
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004456static void BuildUniqueMethodName(std::string &Name,
4457 ObjCMethodDecl *MD) {
4458 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4459 Name = IFace->getNameAsCString();
4460 Name += "__" + MD->getSelector().getAsString();
4461 // Convert colons to underscores.
4462 std::string::size_type loc = 0;
4463 while ((loc = Name.find(":", loc)) != std::string::npos)
4464 Name.replace(loc, 1, "_");
4465}
4466
Steve Naroff54055232008-10-27 17:20:55 +00004467void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004468 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4469 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004470 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004471 std::string FuncName;
4472 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004473 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4474}
4475
4476void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4477 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4478 CI != E; ++CI)
4479 if (*CI) {
4480 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4481 GetBlockDeclRefExprs(CBE->getBody());
4482 else
4483 GetBlockDeclRefExprs(*CI);
4484 }
4485 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004486 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004487 // FIXME: Handle enums.
4488 if (!isa<FunctionDecl>(CDRE->getDecl()))
4489 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004490 }
4491 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4492 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4493 BlockDeclRefExpr *BDRE =
4494 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4495 DRE->getLocation(), false);
4496 BlockDeclRefs.push_back(BDRE);
4497 }
4498
Steve Naroff54055232008-10-27 17:20:55 +00004499 return;
4500}
4501
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004502void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4503 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004504 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004505 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4506 CI != E; ++CI)
4507 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004508 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4509 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004510 GetInnerBlockDeclRefExprs(CBE->getBody(),
4511 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004512 InnerContexts);
4513 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004514 else
4515 GetInnerBlockDeclRefExprs(*CI,
4516 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004517 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004518
4519 }
4520 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004521 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004522 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004523 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004524 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004525 }
4526 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4527 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4528 if (Var->isFunctionOrMethodVarDecl())
4529 ImportedLocalExternalDecls.insert(Var);
4530 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004531
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004532 return;
4533}
4534
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004535Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004536 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004537 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004539 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004540 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004541 } else if (const BlockDeclRefExpr *CDRE =
4542 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004543 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004544 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004545 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004546 }
4547 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4548 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4549 }
4550 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4551 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4552 else if (const ConditionalOperator *CEXPR =
4553 dyn_cast<ConditionalOperator>(BlockExp)) {
4554 Expr *LHSExp = CEXPR->getLHS();
4555 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4556 Expr *RHSExp = CEXPR->getRHS();
4557 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4558 Expr *CONDExp = CEXPR->getCond();
4559 ConditionalOperator *CondExpr =
4560 new (Context) ConditionalOperator(CONDExp,
4561 SourceLocation(), cast<Expr>(LHSStmt),
4562 SourceLocation(), cast<Expr>(RHSStmt),
4563 Exp->getType());
4564 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004565 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4566 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004567 } else {
4568 assert(1 && "RewriteBlockClass: Bad type");
4569 }
4570 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004571 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004572 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004573 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004574 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004576 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004577 SourceLocation(),
4578 &Context->Idents.get("__block_impl"));
4579 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004580
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004581 // Generate a funky cast.
4582 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004583
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004584 // Push the block argument type.
4585 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004586 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004587 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004588 E = FTP->arg_type_end(); I && (I != E); ++I) {
4589 QualType t = *I;
4590 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004591 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004592 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004593 t = Context->getPointerType(BPT->getPointeeType());
4594 }
4595 ArgTypes.push_back(t);
4596 }
Steve Naroff54055232008-10-27 17:20:55 +00004597 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004598 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004599 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004600 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4601 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004602 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004603
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004604 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004605
John McCall9d125032010-01-15 18:39:57 +00004606 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4607 CastExpr::CK_Unknown,
4608 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004609 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004610 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4611 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004612 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004613
Douglas Gregor44b43212008-12-11 16:49:14 +00004614 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004615 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004616 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004617 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4618 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004619
John McCall9d125032010-01-15 18:39:57 +00004620 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4621 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004622 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004624 llvm::SmallVector<Expr*, 8> BlkExprs;
4625 // Add the implicit argument.
4626 BlkExprs.push_back(BlkCast);
4627 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004628 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004629 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004630 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004631 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004632 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4633 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004634 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004635 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004636}
4637
4638void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004639 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004640 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004641}
4642
Steve Naroff621edce2009-04-29 16:37:50 +00004643// We need to return the rewritten expression to handle cases where the
4644// BlockDeclRefExpr is embedded in another expression being rewritten.
4645// For example:
4646//
4647// int main() {
4648// __block Foo *f;
4649// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004650//
Steve Naroff621edce2009-04-29 16:37:50 +00004651// void (^myblock)() = ^() {
4652// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4653// i = 77;
4654// };
4655//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004656Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004657 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004658 // for each DeclRefExp where BYREFVAR is name of the variable.
4659 ValueDecl *VD;
4660 bool isArrow = true;
4661 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4662 VD = BDRE->getDecl();
4663 else {
4664 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4665 isArrow = false;
4666 }
4667
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004668 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4669 &Context->Idents.get("__forwarding"),
4670 Context->VoidPtrTy, 0,
4671 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004672 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4673 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004674 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004675
4676 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004677 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4678 &Context->Idents.get(Name),
4679 Context->VoidPtrTy, 0,
4680 /*BitWidth=*/0, /*Mutable=*/true);
4681 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004682 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004683
4684
4685
Steve Naroffdf8570d2009-02-02 17:19:26 +00004686 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004687 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4688 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004689 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004690 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004691}
4692
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004693// Rewrites the imported local variable V with external storage
4694// (static, extern, etc.) as *V
4695//
4696Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4697 ValueDecl *VD = DRE->getDecl();
4698 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4699 if (!ImportedLocalExternalDecls.count(Var))
4700 return DRE;
4701 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4702 DRE->getType(), DRE->getLocation());
4703 // Need parens to enforce precedence.
4704 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4705 Exp);
4706 ReplaceStmt(DRE, PE);
4707 return PE;
4708}
4709
Steve Naroffb2f9e512008-11-03 23:29:32 +00004710void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4711 SourceLocation LocStart = CE->getLParenLoc();
4712 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004713
4714 // Need to avoid trying to rewrite synthesized casts.
4715 if (LocStart.isInvalid())
4716 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004717 // Need to avoid trying to rewrite casts contained in macros.
4718 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4719 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004720
Steve Naroff54055232008-10-27 17:20:55 +00004721 const char *startBuf = SM->getCharacterData(LocStart);
4722 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004723 QualType QT = CE->getType();
4724 const Type* TypePtr = QT->getAs<Type>();
4725 if (isa<TypeOfExprType>(TypePtr)) {
4726 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4727 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4728 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004729 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004730 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004731 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004732 return;
4733 }
Steve Naroff54055232008-10-27 17:20:55 +00004734 // advance the location to startArgList.
4735 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Steve Naroff54055232008-10-27 17:20:55 +00004737 while (*argPtr++ && (argPtr < endBuf)) {
4738 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004739 case '^':
4740 // Replace the '^' with '*'.
4741 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004742 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004743 break;
Steve Naroff54055232008-10-27 17:20:55 +00004744 }
4745 }
4746 return;
4747}
4748
4749void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4750 SourceLocation DeclLoc = FD->getLocation();
4751 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Steve Naroff54055232008-10-27 17:20:55 +00004753 // We have 1 or more arguments that have closure pointers.
4754 const char *startBuf = SM->getCharacterData(DeclLoc);
4755 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004756
Steve Naroff54055232008-10-27 17:20:55 +00004757 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Naroff54055232008-10-27 17:20:55 +00004759 parenCount++;
4760 // advance the location to startArgList.
4761 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4762 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Steve Naroff54055232008-10-27 17:20:55 +00004764 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Steve Naroff54055232008-10-27 17:20:55 +00004766 while (*argPtr++ && parenCount) {
4767 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004768 case '^':
4769 // Replace the '^' with '*'.
4770 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004771 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004772 break;
4773 case '(':
4774 parenCount++;
4775 break;
4776 case ')':
4777 parenCount--;
4778 break;
Steve Naroff54055232008-10-27 17:20:55 +00004779 }
4780 }
4781 return;
4782}
4783
4784bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004785 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004786 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004787 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004788 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004789 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004790 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004791 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004792 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004793 }
4794 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004795 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004796 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004797 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004798 return true;
4799 }
4800 return false;
4801}
4802
Ted Kremenek8189cde2009-02-07 01:47:29 +00004803void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4804 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004805 const char *argPtr = strchr(Name, '(');
4806 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004807
Steve Naroff54055232008-10-27 17:20:55 +00004808 LParen = argPtr; // output the start.
4809 argPtr++; // skip past the left paren.
4810 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004811
Steve Naroff54055232008-10-27 17:20:55 +00004812 while (*argPtr && parenCount) {
4813 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004814 case '(': parenCount++; break;
4815 case ')': parenCount--; break;
4816 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004817 }
4818 if (parenCount) argPtr++;
4819 }
4820 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4821 RParen = argPtr; // output the end
4822}
4823
4824void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4825 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4826 RewriteBlockPointerFunctionArgs(FD);
4827 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004828 }
Steve Naroff54055232008-10-27 17:20:55 +00004829 // Handle Variables and Typedefs.
4830 SourceLocation DeclLoc = ND->getLocation();
4831 QualType DeclT;
4832 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4833 DeclT = VD->getType();
4834 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4835 DeclT = TDD->getUnderlyingType();
4836 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4837 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004838 else
Steve Naroff54055232008-10-27 17:20:55 +00004839 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004840
Steve Naroff54055232008-10-27 17:20:55 +00004841 const char *startBuf = SM->getCharacterData(DeclLoc);
4842 const char *endBuf = startBuf;
4843 // scan backward (from the decl location) for the end of the previous decl.
4844 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4845 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004846
Steve Naroff54055232008-10-27 17:20:55 +00004847 // *startBuf != '^' if we are dealing with a pointer to function that
4848 // may take block argument types (which will be handled below).
4849 if (*startBuf == '^') {
4850 // Replace the '^' with '*', computing a negative offset.
4851 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004852 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004853 }
4854 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4855 // Replace the '^' with '*' for arguments.
4856 DeclLoc = ND->getLocation();
4857 startBuf = SM->getCharacterData(DeclLoc);
4858 const char *argListBegin, *argListEnd;
4859 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4860 while (argListBegin < argListEnd) {
4861 if (*argListBegin == '^') {
4862 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004863 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004864 }
4865 argListBegin++;
4866 }
4867 }
4868 return;
4869}
4870
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004871
4872/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4873/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4874/// struct Block_byref_id_object *src) {
4875/// _Block_object_assign (&_dest->object, _src->object,
4876/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4877/// [|BLOCK_FIELD_IS_WEAK]) // object
4878/// _Block_object_assign(&_dest->object, _src->object,
4879/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4880/// [|BLOCK_FIELD_IS_WEAK]) // block
4881/// }
4882/// And:
4883/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4884/// _Block_object_dispose(_src->object,
4885/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4886/// [|BLOCK_FIELD_IS_WEAK]) // object
4887/// _Block_object_dispose(_src->object,
4888/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4889/// [|BLOCK_FIELD_IS_WEAK]) // block
4890/// }
4891
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004892std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4893 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004894 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004895 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004896 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004897 CopyDestroyCache.insert(flag);
4898 S = "static void __Block_byref_id_object_copy_";
4899 S += utostr(flag);
4900 S += "(void *dst, void *src) {\n";
4901
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004902 // offset into the object pointer is computed as:
4903 // void * + void* + int + int + void* + void *
4904 unsigned IntSize =
4905 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4906 unsigned VoidPtrSize =
4907 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4908
4909 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4910 S += " _Block_object_assign((char*)dst + ";
4911 S += utostr(offset);
4912 S += ", *(void * *) ((char*)src + ";
4913 S += utostr(offset);
4914 S += "), ";
4915 S += utostr(flag);
4916 S += ");\n}\n";
4917
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004918 S += "static void __Block_byref_id_object_dispose_";
4919 S += utostr(flag);
4920 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004921 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4922 S += utostr(offset);
4923 S += "), ";
4924 S += utostr(flag);
4925 S += ");\n}\n";
4926 return S;
4927}
4928
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004929/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4930/// the declaration into:
4931/// struct __Block_byref_ND {
4932/// void *__isa; // NULL for everything except __weak pointers
4933/// struct __Block_byref_ND *__forwarding;
4934/// int32_t __flags;
4935/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004936/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4937/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004938/// typex ND;
4939/// };
4940///
4941/// It then replaces declaration of ND variable with:
4942/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4943/// __size=sizeof(struct __Block_byref_ND),
4944/// ND=initializer-if-any};
4945///
4946///
4947void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004948 // Insert declaration for the function in which block literal is
4949 // used.
4950 if (CurFunctionDeclToDeclareForBlock)
4951 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004952 int flag = 0;
4953 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004954 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004955 if (DeclLoc.isInvalid())
4956 // If type location is missing, it is because of missing type (a warning).
4957 // Use variable's location which is good for this case.
4958 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004959 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004960 SourceLocation X = ND->getLocEnd();
4961 X = SM->getInstantiationLoc(X);
4962 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004963 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004964 std::string ByrefType;
4965 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004966 ByrefType += " {\n";
4967 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004968 RewriteByRefString(ByrefType, Name, ND);
4969 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004970 ByrefType += " int __flags;\n";
4971 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004972 // Add void *__Block_byref_id_object_copy;
4973 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004974 QualType Ty = ND->getType();
4975 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4976 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004977 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4978 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004979 }
4980
4981 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004982 ByrefType += " " + Name + ";\n";
4983 ByrefType += "};\n";
4984 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004985 SourceLocation FunLocStart;
4986 if (CurFunctionDef)
4987 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4988 else {
4989 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4990 FunLocStart = CurMethodDef->getLocStart();
4991 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004992 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004993 if (Ty.isObjCGCWeak()) {
4994 flag |= BLOCK_FIELD_IS_WEAK;
4995 isa = 1;
4996 }
4997
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004998 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004999 flag = BLOCK_BYREF_CALLER;
5000 QualType Ty = ND->getType();
5001 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5002 if (Ty->isBlockPointerType())
5003 flag |= BLOCK_FIELD_IS_BLOCK;
5004 else
5005 flag |= BLOCK_FIELD_IS_OBJECT;
5006 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005007 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005008 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005009 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005010
5011 // struct __Block_byref_ND ND =
5012 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5013 // initializer-if-any};
5014 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005015 unsigned flags = 0;
5016 if (HasCopyAndDispose)
5017 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005018 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005019 ByrefType.clear();
5020 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005021 std::string ForwardingCastType("(");
5022 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005023 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005024 ByrefType += " " + Name + " = {(void*)";
5025 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005026 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005027 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005028 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005029 ByrefType += "sizeof(";
5030 RewriteByRefString(ByrefType, Name, ND);
5031 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005032 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005033 ByrefType += ", __Block_byref_id_object_copy_";
5034 ByrefType += utostr(flag);
5035 ByrefType += ", __Block_byref_id_object_dispose_";
5036 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005037 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005038 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005039 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005040 }
5041 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005042 SourceLocation startLoc;
5043 Expr *E = ND->getInit();
5044 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5045 startLoc = ECE->getLParenLoc();
5046 else
5047 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005048 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005049 endBuf = SM->getCharacterData(startLoc);
5050
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005051 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005052 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005053 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005054 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005055 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005056 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005057 ByrefType += "sizeof(";
5058 RewriteByRefString(ByrefType, Name, ND);
5059 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005060 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005061 ByrefType += "__Block_byref_id_object_copy_";
5062 ByrefType += utostr(flag);
5063 ByrefType += ", __Block_byref_id_object_dispose_";
5064 ByrefType += utostr(flag);
5065 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005066 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005067 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005068
5069 // Complete the newly synthesized compound expression by inserting a right
5070 // curly brace before the end of the declaration.
5071 // FIXME: This approach avoids rewriting the initializer expression. It
5072 // also assumes there is only one declarator. For example, the following
5073 // isn't currently supported by this routine (in general):
5074 //
5075 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5076 //
5077 const char *startBuf = SM->getCharacterData(startLoc);
5078 const char *semiBuf = strchr(startBuf, ';');
5079 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5080 SourceLocation semiLoc =
5081 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5082
Benjamin Kramerd999b372010-02-14 14:14:16 +00005083 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005084 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005085 return;
5086}
5087
Mike Stump1eb44332009-09-09 15:08:12 +00005088void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005089 // Add initializers for any closure decl refs.
5090 GetBlockDeclRefExprs(Exp->getBody());
5091 if (BlockDeclRefs.size()) {
5092 // Unique all "by copy" declarations.
5093 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005094 if (!BlockDeclRefs[i]->isByRef()) {
5095 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5096 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5097 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5098 }
5099 }
Steve Naroff54055232008-10-27 17:20:55 +00005100 // Unique all "by ref" declarations.
5101 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5102 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005103 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5104 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5105 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5106 }
Steve Naroff54055232008-10-27 17:20:55 +00005107 }
5108 // Find any imported blocks...they will need special attention.
5109 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005110 if (BlockDeclRefs[i]->isByRef() ||
5111 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005112 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005113 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005114 }
5115}
5116
Steve Narofffa15fd92008-10-28 20:29:00 +00005117FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5118 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005119 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005120 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00005121 ID, FType, 0, FunctionDecl::Extern,
5122 FunctionDecl::None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005123}
5124
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005125Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5126 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005127 Blocks.push_back(Exp);
5128
5129 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005130
5131 // Add inner imported variables now used in current block.
5132 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005133 if (!InnerBlockDeclRefs.empty()) {
5134 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5135 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5136 ValueDecl *VD = Exp->getDecl();
5137 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005138 // We need to save the copied-in variables in nested
5139 // blocks because it is needed at the end for some of the API generations.
5140 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005141 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5142 BlockDeclRefs.push_back(Exp);
5143 BlockByCopyDeclsPtrSet.insert(VD);
5144 BlockByCopyDecls.push_back(VD);
5145 }
5146 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5147 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5148 BlockDeclRefs.push_back(Exp);
5149 BlockByRefDeclsPtrSet.insert(VD);
5150 BlockByRefDecls.push_back(VD);
5151 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005152 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005153 // Find any imported blocks...they will need special attention.
5154 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5155 if (InnerBlockDeclRefs[i]->isByRef() ||
5156 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5157 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5158 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005159 }
5160 InnerDeclRefsCount.push_back(countOfInnerDecls);
5161
Steve Narofffa15fd92008-10-28 20:29:00 +00005162 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Steve Narofffa15fd92008-10-28 20:29:00 +00005164 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005165 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005166 else if (CurMethodDef)
5167 BuildUniqueMethodName(FuncName, CurMethodDef);
5168 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005169 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005170
Steve Narofffa15fd92008-10-28 20:29:00 +00005171 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005172
Steve Narofffa15fd92008-10-28 20:29:00 +00005173 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5174 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005175
Steve Narofffa15fd92008-10-28 20:29:00 +00005176 // Get a pointer to the function type so we can cast appropriately.
5177 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5178
5179 FunctionDecl *FD;
5180 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005181
Steve Narofffa15fd92008-10-28 20:29:00 +00005182 // Simulate a contructor call...
5183 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005184 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005185
Steve Narofffa15fd92008-10-28 20:29:00 +00005186 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005187
Steve Narofffdc03722008-10-29 21:23:59 +00005188 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005189 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005190 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5191 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005192 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5193 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005194 InitExprs.push_back(castExpr);
5195
Steve Naroff01aec112009-12-06 21:14:13 +00005196 // Initialize the block descriptor.
5197 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Steve Naroff01aec112009-12-06 21:14:13 +00005199 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5200 &Context->Idents.get(DescData.c_str()),
5201 Context->VoidPtrTy, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005202 VarDecl::Static, VarDecl::None);
Steve Naroff01aec112009-12-06 21:14:13 +00005203 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5204 new (Context) DeclRefExpr(NewVD,
5205 Context->VoidPtrTy, SourceLocation()),
5206 UnaryOperator::AddrOf,
5207 Context->getPointerType(Context->VoidPtrTy),
5208 SourceLocation());
5209 InitExprs.push_back(DescRefExpr);
5210
Steve Narofffa15fd92008-10-28 20:29:00 +00005211 // Add initializers for any closure decl refs.
5212 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005213 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005214 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005215 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005216 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005217 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005218 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005219 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005220 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005221 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005222 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005223 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005224 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5225 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005226 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005227 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005228 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005229 if (HasLocalVariableExternalStorage(*I)) {
5230 QualType QT = (*I)->getType();
5231 QT = Context->getPointerType(QT);
5232 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5233 SourceLocation());
5234 }
5235
Steve Narofffa15fd92008-10-28 20:29:00 +00005236 }
Mike Stump1eb44332009-09-09 15:08:12 +00005237 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005238 }
5239 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005240 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005241 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005242 ValueDecl *ND = (*I);
5243 std::string Name(ND->getNameAsString());
5244 std::string RecName;
5245 RewriteByRefString(RecName, Name, ND);
5246 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5247 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005248 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005249 SourceLocation(), II);
5250 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5251 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5252
Chris Lattner8ec03f52008-11-24 03:54:41 +00005253 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005254 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5255 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005256 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005257 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005258 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005259 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005260 }
5261 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005262 if (ImportedBlockDecls.size()) {
5263 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5264 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005265 unsigned IntSize =
5266 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005267 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5268 Context->IntTy, SourceLocation());
5269 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005270 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005271 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5272 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005273 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005274 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005275 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005276 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5277 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005278 BlockDeclRefs.clear();
5279 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005280 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005281 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005282 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005283 ImportedBlockDecls.clear();
5284 return NewRep;
5285}
5286
5287//===----------------------------------------------------------------------===//
5288// Function Body / Expression rewriting
5289//===----------------------------------------------------------------------===//
5290
Steve Naroffc77a6362008-12-04 16:24:46 +00005291// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5292// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5293// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5294// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5295// Since the rewriter isn't capable of rewriting rewritten code, it's important
5296// we get this right.
5297void RewriteObjC::CollectPropertySetters(Stmt *S) {
5298 // Perform a bottom up traversal of all children.
5299 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5300 CI != E; ++CI)
5301 if (*CI)
5302 CollectPropertySetters(*CI);
5303
5304 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5305 if (BinOp->isAssignmentOp()) {
5306 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5307 PropSetters[PRE] = BinOp;
5308 }
5309 }
5310}
5311
Steve Narofffa15fd92008-10-28 20:29:00 +00005312Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005313 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005314 isa<DoStmt>(S) || isa<ForStmt>(S))
5315 Stmts.push_back(S);
5316 else if (isa<ObjCForCollectionStmt>(S)) {
5317 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005318 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005319 }
Mike Stump1eb44332009-09-09 15:08:12 +00005320
Steve Narofffa15fd92008-10-28 20:29:00 +00005321 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Steve Narofffa15fd92008-10-28 20:29:00 +00005323 // Perform a bottom up rewrite of all children.
5324 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5325 CI != E; ++CI)
5326 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005327 Stmt *newStmt;
5328 Stmt *S = (*CI);
5329 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5330 Expr *OldBase = IvarRefExpr->getBase();
5331 bool replaced = false;
5332 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5333 if (replaced) {
5334 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5335 ReplaceStmt(OldBase, IRE->getBase());
5336 else
5337 ReplaceStmt(S, newStmt);
5338 }
5339 }
5340 else
5341 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005342 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005343 *CI = newStmt;
5344 }
Mike Stump1eb44332009-09-09 15:08:12 +00005345
Steve Narofffa15fd92008-10-28 20:29:00 +00005346 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005347 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005348 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5349 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005350 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005351 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005352 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005353 // Rewrite the block body in place.
5354 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005355 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005356 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005357 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005358 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005359
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005360 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5361
Steve Narofffa15fd92008-10-28 20:29:00 +00005362 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005363 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 return blockTranscribed;
5365 }
5366 // Handle specific things.
5367 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5368 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005369
Steve Naroffc77a6362008-12-04 16:24:46 +00005370 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5371 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5372 if (BinOp) {
5373 // Because the rewriter doesn't allow us to rewrite rewritten code,
5374 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005375 DisableReplaceStmt = true;
5376 // Save the source range. Even if we disable the replacement, the
5377 // rewritten node will have been inserted into the tree. If the synthesized
5378 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005379 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005380 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5381 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005382 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005383 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005384 //
5385 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5386 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5387 // to see the original expression). Consider this example:
5388 //
5389 // Foo *obj1, *obj2;
5390 //
5391 // obj1.i = [obj2 rrrr];
5392 //
5393 // 'BinOp' for the previous expression looks like:
5394 //
5395 // (BinaryOperator 0x231ccf0 'int' '='
5396 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5397 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5398 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5399 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5400 //
5401 // 'newStmt' represents the rewritten message expression. For example:
5402 //
5403 // (CallExpr 0x231d300 'id':'struct objc_object *'
5404 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5405 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5406 // (CStyleCastExpr 0x231d220 'void *'
5407 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5408 //
5409 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5410 // can be used as the setter argument. ReplaceStmt() will still 'see'
5411 // the original RHS (since we haven't altered BinOp).
5412 //
Mike Stump1eb44332009-09-09 15:08:12 +00005413 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005414 // node. As a result, we now leak the original AST nodes.
5415 //
Steve Naroffb619d952008-12-09 12:56:34 +00005416 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005417 } else {
5418 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005419 }
5420 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005421 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5422 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Steve Narofffa15fd92008-10-28 20:29:00 +00005424 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5425 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005426
Steve Narofffa15fd92008-10-28 20:29:00 +00005427 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005428#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 // Before we rewrite it, put the original message expression in a comment.
5430 SourceLocation startLoc = MessExpr->getLocStart();
5431 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Steve Narofffa15fd92008-10-28 20:29:00 +00005433 const char *startBuf = SM->getCharacterData(startLoc);
5434 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Steve Narofffa15fd92008-10-28 20:29:00 +00005436 std::string messString;
5437 messString += "// ";
5438 messString.append(startBuf, endBuf-startBuf+1);
5439 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005440
5441 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005442 // InsertText(clang::SourceLocation, char const*, unsigned int).
5443 // InsertText(startLoc, messString.c_str(), messString.size());
5444 // Tried this, but it didn't work either...
5445 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005446#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005447 return RewriteMessageExpr(MessExpr);
5448 }
Mike Stump1eb44332009-09-09 15:08:12 +00005449
Steve Narofffa15fd92008-10-28 20:29:00 +00005450 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5451 return RewriteObjCTryStmt(StmtTry);
5452
5453 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5454 return RewriteObjCSynchronizedStmt(StmtTry);
5455
5456 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5457 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005458
Steve Narofffa15fd92008-10-28 20:29:00 +00005459 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5460 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005461
5462 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005464 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 OrigStmtRange.getEnd());
5466 if (BreakStmt *StmtBreakStmt =
5467 dyn_cast<BreakStmt>(S))
5468 return RewriteBreakStmt(StmtBreakStmt);
5469 if (ContinueStmt *StmtContinueStmt =
5470 dyn_cast<ContinueStmt>(S))
5471 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005472
5473 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005474 // and cast exprs.
5475 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5476 // FIXME: What we're doing here is modifying the type-specifier that
5477 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005478 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005479 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5480 // the context of an ObjCForCollectionStmt. For example:
5481 // NSArray *someArray;
5482 // for (id <FooProtocol> index in someArray) ;
5483 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5484 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005485 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005486 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005487
Steve Narofffa15fd92008-10-28 20:29:00 +00005488 // Blocks rewrite rules.
5489 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5490 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005491 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005492 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005493 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005495 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005496 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005497 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005498 if (VD->hasAttr<BlocksAttr>()) {
5499 static unsigned uniqueByrefDeclCount = 0;
5500 assert(!BlockByRefDeclNo.count(ND) &&
5501 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5502 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005503 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005504 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005505 else
5506 RewriteTypeOfDecl(VD);
5507 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005508 }
5509 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005510 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005511 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005512 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005513 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5514 }
5515 }
5516 }
Mike Stump1eb44332009-09-09 15:08:12 +00005517
Steve Narofffa15fd92008-10-28 20:29:00 +00005518 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5519 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005520
5521 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005522 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5523 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005524 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5525 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005526 && "Statement stack mismatch");
5527 Stmts.pop_back();
5528 }
5529 // Handle blocks rewriting.
5530 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5531 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005532 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005534 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5535 ValueDecl *VD = DRE->getDecl();
5536 if (VD->hasAttr<BlocksAttr>())
5537 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005538 if (HasLocalVariableExternalStorage(VD))
5539 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005540 }
5541
Steve Narofffa15fd92008-10-28 20:29:00 +00005542 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005543 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005544 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005545 ReplaceStmt(S, BlockCall);
5546 return BlockCall;
5547 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005548 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005549 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 RewriteCastExpr(CE);
5551 }
5552#if 0
5553 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005554 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005555 // Get the new text.
5556 std::string SStr;
5557 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005558 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005559 const std::string &Str = Buf.str();
5560
5561 printf("CAST = %s\n", &Str[0]);
5562 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5563 delete S;
5564 return Replacement;
5565 }
5566#endif
5567 // Return this stmt unmodified.
5568 return S;
5569}
5570
Steve Naroff3d7e7862009-12-05 15:55:59 +00005571void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5572 for (RecordDecl::field_iterator i = RD->field_begin(),
5573 e = RD->field_end(); i != e; ++i) {
5574 FieldDecl *FD = *i;
5575 if (isTopLevelBlockPointerType(FD->getType()))
5576 RewriteBlockPointerDecl(FD);
5577 if (FD->getType()->isObjCQualifiedIdType() ||
5578 FD->getType()->isObjCQualifiedInterfaceType())
5579 RewriteObjCQualifiedInterfaceTypes(FD);
5580 }
5581}
5582
Steve Narofffa15fd92008-10-28 20:29:00 +00005583/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5584/// main file of the input.
5585void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5586 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005587 if (FD->isOverloadedOperator())
5588 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005589
Steve Narofffa15fd92008-10-28 20:29:00 +00005590 // Since function prototypes don't have ParmDecl's, we check the function
5591 // prototype. This enables us to rewrite function declarations and
5592 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005593 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005594
Sebastian Redld3a413d2009-04-26 20:35:05 +00005595 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005596 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005597 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005598 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005599 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005600 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005601 Body =
5602 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5603 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005604 CurrentBody = 0;
5605 if (PropParentMap) {
5606 delete PropParentMap;
5607 PropParentMap = 0;
5608 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005609 // This synthesizes and inserts the block "impl" struct, invoke function,
5610 // and any copy/dispose helper functions.
5611 InsertBlockLiteralsWithinFunction(FD);
5612 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005613 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005614 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005615 return;
5616 }
5617 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005618 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005619 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005620 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005621 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005622 Body =
5623 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5624 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005625 CurrentBody = 0;
5626 if (PropParentMap) {
5627 delete PropParentMap;
5628 PropParentMap = 0;
5629 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 InsertBlockLiteralsWithinMethod(MD);
5631 CurMethodDef = 0;
5632 }
5633 }
5634 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5635 ClassImplementation.push_back(CI);
5636 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5637 CategoryImplementation.push_back(CI);
5638 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5639 RewriteForwardClassDecl(CD);
5640 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5641 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005642 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005643 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005644 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 CheckFunctionPointerDecl(VD->getType(), VD);
5646 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005647 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005648 RewriteCastExpr(CE);
5649 }
5650 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005651 } else if (VD->getType()->isRecordType()) {
5652 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5653 if (RD->isDefinition())
5654 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005655 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005656 if (VD->getInit()) {
5657 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005658 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005659 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005660 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005661 CurrentBody = 0;
5662 if (PropParentMap) {
5663 delete PropParentMap;
5664 PropParentMap = 0;
5665 }
Mike Stump1eb44332009-09-09 15:08:12 +00005666 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005667 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005668 GlobalVarDecl = 0;
5669
5670 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005671 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005672 RewriteCastExpr(CE);
5673 }
5674 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005675 return;
5676 }
5677 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005678 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005680 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005681 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5682 return;
5683 }
5684 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005685 if (RD->isDefinition())
5686 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005687 return;
5688 }
5689 // Nothing yet.
5690}
5691
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005692void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005693 if (Diags.hasErrorOccurred())
5694 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005695
Steve Narofffa15fd92008-10-28 20:29:00 +00005696 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Steve Naroff621edce2009-04-29 16:37:50 +00005698 // Here's a great place to add any extra declarations that may be needed.
5699 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005700 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005701 E = ProtocolExprDecls.end(); I != E; ++I)
5702 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5703
Benjamin Kramerd999b372010-02-14 14:14:16 +00005704 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005705 if (ClassImplementation.size() || CategoryImplementation.size())
5706 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005707
Steve Narofffa15fd92008-10-28 20:29:00 +00005708 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5709 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005710 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005711 Rewrite.getRewriteBufferFor(MainFileID)) {
5712 //printf("Changed:\n");
5713 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5714 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005715 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 }
Steve Narofface66252008-11-13 20:07:04 +00005717
Steve Naroff621edce2009-04-29 16:37:50 +00005718 if (ClassImplementation.size() || CategoryImplementation.size() ||
5719 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005720 // Rewrite Objective-c meta data*
5721 std::string ResultStr;
5722 SynthesizeMetaDataIntoBuffer(ResultStr);
5723 // Emit metadata.
5724 *OutFile << ResultStr;
5725 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005726 OutFile->flush();
5727}