blob: 351667e32f95b9d4126e210466854299d8f9bf20 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
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);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000278 bool isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000279 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000280 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000281 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000282 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattnerf04da132007-10-24 17:06:59 +0000284 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000285 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000286 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Steve Naroff8599e7a2008-12-08 16:43:47 +0000288 Stmt *CurrentBody;
289 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattnere64b7772007-10-24 16:57:36 +0000291 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000292 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
293 bool &replaced);
294 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000295 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000296 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000297 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000298 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000300 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000301 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000302 void WarnAboutReturnGotoStmts(Stmt *S);
303 void HasReturnStmts(Stmt *S, bool &hasReturns);
304 void RewriteTryReturnStmts(Stmt *S);
305 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000306 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000307 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000308 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
309 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000313 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000314 Expr **args, unsigned nargs,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
317 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
318 SourceLocation StartLoc=SourceLocation(),
319 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000320 Stmt *RewriteBreakStmt(BreakStmt *S);
321 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000322 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Steve Naroff09b266e2007-10-30 23:14:51 +0000324 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000325 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000326 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000327 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000328 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000329 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000330 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000331 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000332 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000333 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000334
Chris Lattnerf04da132007-10-24 17:06:59 +0000335 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000339 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000340 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Douglas Gregor653f1b12009-04-23 01:02:12 +0000342 template<typename MethodIterator>
343 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
344 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000345 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000346 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000347 const char *ClassName,
348 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Steve Naroff621edce2009-04-29 16:37:50 +0000350 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
351 const char *prefix,
352 const char *ClassName,
353 std::string &Result);
354 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000355 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000356 const char *ClassName,
357 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000358 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000360 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000361 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000362 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000363 void RewriteImplementations();
364 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Steve Naroff54055232008-10-27 17:20:55 +0000366 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000367 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000368 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Steve Naroff54055232008-10-27 17:20:55 +0000370 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
371 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
373 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000374 void RewriteBlockCall(CallExpr *Exp);
375 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000376 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000377 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000378 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000379 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000380 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
382 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000383 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000385 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000386 std::string SynthesizeBlockImpl(BlockExpr *CE,
387 std::string Tag, std::string Desc);
388 std::string SynthesizeBlockDescriptor(std::string DescTag,
389 std::string ImplTag,
390 int i, const char *funcName,
391 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000392 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000393 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000394 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000395 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Steve Naroff54055232008-10-27 17:20:55 +0000397 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000398 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000399 void GetInnerBlockDeclRefExprs(Stmt *S,
400 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000401 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Steve Naroff54055232008-10-27 17:20:55 +0000403 // We avoid calling Type::isBlockPointerType(), since it operates on the
404 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000405 bool isTopLevelBlockPointerType(QualType T) {
406 return isa<BlockPointerType>(T);
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000409 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
410 /// to a function pointer type and upon success, returns true; false
411 /// otherwise.
412 bool convertBlockPointerToFunctionPointer(QualType &T) {
413 if (isTopLevelBlockPointerType(T)) {
414 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
415 T = Context->getPointerType(BPT->getPointeeType());
416 return true;
417 }
418 return false;
419 }
420
Steve Naroff54055232008-10-27 17:20:55 +0000421 // FIXME: This predicate seems like it would be useful to add to ASTContext.
422 bool isObjCType(QualType T) {
423 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
424 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Steve Naroff54055232008-10-27 17:20:55 +0000426 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Steve Naroff54055232008-10-27 17:20:55 +0000428 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
429 OCT == Context->getCanonicalType(Context->getObjCClassType()))
430 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Ted Kremenek6217b802009-07-29 21:53:49 +0000432 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000433 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000434 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000435 return true;
436 }
437 return false;
438 }
439 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000440 void GetExtentOfArgList(const char *Name, const char *&LParen,
441 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000442 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Steve Narofffa15fd92008-10-28 20:29:00 +0000444 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000445 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
446 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Steve Naroff621edce2009-04-29 16:37:50 +0000448 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000449 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000450 if (From[i] == '"')
451 To += "\\\"";
452 else
453 To += From[i];
454 }
455 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000456 };
John McCall9d125032010-01-15 18:39:57 +0000457
458 // Helper function: create a CStyleCastExpr with trivial type source info.
459 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
460 CastExpr::CastKind Kind, Expr *E) {
461 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Anders Carlsson41b2dcd2010-04-24 18:38:56 +0000462 return new (Ctx) CStyleCastExpr(Ty, Kind, E, CXXBaseSpecifierArray(), TInfo,
John McCall9d125032010-01-15 18:39:57 +0000463 SourceLocation(), SourceLocation());
464 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000465}
466
Mike Stump1eb44332009-09-09 15:08:12 +0000467void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
468 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000469 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000470 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000471 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000472 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000473 // All the args are checked/rewritten. Don't call twice!
474 RewriteBlockPointerDecl(D);
475 break;
476 }
477 }
478}
479
480void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000481 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000482 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000483 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000484}
485
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000486static bool IsHeaderFile(const std::string &Filename) {
487 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000489 if (DotPos == std::string::npos) {
490 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000491 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000494 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
495 // C header: .h
496 // C++ header: .hh or .H;
497 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000498}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000499
Eli Friedman66d6f042009-05-18 22:20:00 +0000500RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000501 Diagnostic &D, const LangOptions &LOpts,
502 bool silenceMacroWarn)
503 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
504 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000505 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000506 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000507 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000508 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000509 "rewriter doesn't support user-specified control flow semantics "
510 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000511}
512
Eli Friedmanbce831b2009-05-18 22:29:17 +0000513ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
514 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000515 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000516 const LangOptions &LOpts,
517 bool SilenceRewriteMacroWarning) {
518 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000519}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000520
Steve Naroffb29b4272008-04-14 22:03:09 +0000521void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000522 Context = &context;
523 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000524 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000525 MsgSendFunctionDecl = 0;
526 MsgSendSuperFunctionDecl = 0;
527 MsgSendStretFunctionDecl = 0;
528 MsgSendSuperStretFunctionDecl = 0;
529 MsgSendFpretFunctionDecl = 0;
530 GetClassFunctionDecl = 0;
531 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000532 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000533 SelGetUidFunctionDecl = 0;
534 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000535 ConstantStringClassReference = 0;
536 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000537 CurMethodDef = 0;
538 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000539 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000540 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000542 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000543 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000544 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000545 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000546 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000547 PropParentMap = 0;
548 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000549 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000550 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 // Get the ID and start/end of the main file.
553 MainFileID = SM->getMainFileID();
554 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
555 MainFileStart = MainBuf->getBufferStart();
556 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner2c78b872009-04-14 23:22:57 +0000558 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000560 // declaring objc_selector outside the parameter list removes a silly
561 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000562 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000563 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000564 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000565 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000566 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000567 if (LangOpts.Microsoft) {
568 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000569 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
570 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000572 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
575 Preamble += "typedef struct objc_object Protocol;\n";
576 Preamble += "#define _REWRITER_typedef_Protocol\n";
577 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 if (LangOpts.Microsoft) {
579 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
580 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
581 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000582 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000584 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000585 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000586 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000589 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000595 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
596 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000597 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000599 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
600 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
601 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
603 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000604 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000605 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
607 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
608 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
610 Preamble += "struct __objcFastEnumerationState {\n\t";
611 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000612 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000613 Preamble += "unsigned long *mutationsPtr;\n\t";
614 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "#define __FASTENUMERATIONSTATE\n";
617 Preamble += "#endif\n";
618 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
619 Preamble += "struct __NSConstantStringImpl {\n";
620 Preamble += " int *isa;\n";
621 Preamble += " int flags;\n";
622 Preamble += " char *str;\n";
623 Preamble += " long length;\n";
624 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000625 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
626 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
627 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000628 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000629 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000630 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
631 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000632 // Blocks preamble.
633 Preamble += "#ifndef BLOCK_IMPL\n";
634 Preamble += "#define BLOCK_IMPL\n";
635 Preamble += "struct __block_impl {\n";
636 Preamble += " void *isa;\n";
637 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000638 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000639 Preamble += " void *FuncPtr;\n";
640 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000641 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000642 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000643 Preamble += "extern \"C\" __declspec(dllexport) "
644 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000645 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
646 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
647 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
648 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000649 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
650 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000651 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
652 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
653 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000654 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000655 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000656 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
657 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000658 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000659 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000660 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000661 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000662 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000663 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000664 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000665 Preamble += "#define __weak\n";
666 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000667 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
668 // as this avoids warning in any 64bit/32bit compilation model.
669 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000670}
671
672
Chris Lattnerf04da132007-10-24 17:06:59 +0000673//===----------------------------------------------------------------------===//
674// Top Level Driver Code
675//===----------------------------------------------------------------------===//
676
Chris Lattner682bf922009-03-29 16:50:03 +0000677void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000678 if (Diags.hasErrorOccurred())
679 return;
680
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000681 // Two cases: either the decl could be in the main file, or it could be in a
682 // #included file. If the former, rewrite it now. If the later, check to see
683 // if we rewrote the #include/#import.
684 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000685 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000687 // If this is for a builtin, ignore it.
688 if (Loc.isInvalid()) return;
689
Steve Naroffebf2b562007-10-23 23:50:29 +0000690 // Look for built-in declarations that we need to refer during the rewrite.
691 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000692 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000693 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000694 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000695 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000696 ConstantStringClassReference = FVD;
697 return;
698 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000699 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000700 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000701 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000702 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000703 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000704 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000705 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000706 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000707 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000708 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
709 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000710 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
711 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000712 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000713 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000714 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000716 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000717 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000718}
719
Chris Lattnerf04da132007-10-24 17:06:59 +0000720//===----------------------------------------------------------------------===//
721// Syntactic (non-AST) Rewriting Code
722//===----------------------------------------------------------------------===//
723
Steve Naroffb29b4272008-04-14 22:03:09 +0000724void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000725 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000726 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
727 const char *MainBufStart = MainBuf.begin();
728 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000731 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000732 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
733 if (*BufPtr == '#') {
734 if (++BufPtr == MainBufEnd)
735 return;
736 while (*BufPtr == ' ' || *BufPtr == '\t')
737 if (++BufPtr == MainBufEnd)
738 return;
739 if (!strncmp(BufPtr, "import", ImportLen)) {
740 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000741 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000742 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000743 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000744 BufPtr += ImportLen;
745 }
746 }
747 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000748}
749
Steve Naroffb29b4272008-04-14 22:03:09 +0000750void RewriteObjC::RewriteTabs() {
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000751 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
752 const char *MainBufStart = MainBuf.begin();
753 const char *MainBufEnd = MainBuf.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattnerf04da132007-10-24 17:06:59 +0000755 // Loop over the whole file, looking for tabs.
756 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
757 if (*BufPtr != '\t')
758 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattnerf04da132007-10-24 17:06:59 +0000760 // Okay, we found a tab. This tab will turn into at least one character,
761 // but it depends on which 'virtual column' it is in. Compute that now.
762 unsigned VCol = 0;
763 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
764 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
765 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattnerf04da132007-10-24 17:06:59 +0000767 // Okay, now that we know the virtual column, we know how many spaces to
768 // insert. We assume 8-character tab-stops.
769 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattnerf04da132007-10-24 17:06:59 +0000771 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000772 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
773 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000774
Chris Lattnerf04da132007-10-24 17:06:59 +0000775 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000776 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000777 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000778}
779
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
781 ObjCIvarDecl *OID) {
782 std::string S;
783 S = "((struct ";
784 S += ClassDecl->getIdentifier()->getName();
785 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000786 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000787 return S;
788}
789
Steve Naroffa0876e82008-12-02 17:36:43 +0000790void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
791 ObjCImplementationDecl *IMD,
792 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000793 static bool objcGetPropertyDefined = false;
794 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000795 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000796 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000797 const char *startBuf = SM->getCharacterData(startLoc);
798 assert((*startBuf == '@') && "bogus @synthesize location");
799 const char *semiBuf = strchr(startBuf, ';');
800 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000801 SourceLocation onePastSemiLoc =
802 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000803
804 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
805 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Steve Naroffeb0646c2008-12-02 15:48:25 +0000807 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000808 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000809 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000810 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000811
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000812 if (!OID)
813 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000814 unsigned Attributes = PD->getPropertyAttributes();
815 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
816 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
817 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000818 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000819 if (GenGetProperty && !objcGetPropertyDefined) {
820 objcGetPropertyDefined = true;
821 // FIXME. Is this attribute correct in all cases?
822 Getr = "\nextern \"C\" __declspec(dllimport) "
823 "id objc_getProperty(id, SEL, long, bool);\n";
824 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000825 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
826 Getr += "{ ";
827 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000828 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000829 if (GenGetProperty) {
830 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
831 Getr += "typedef ";
832 const FunctionType *FPRetType = 0;
833 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
834 FPRetType);
835 Getr += " _TYPE";
836 if (FPRetType) {
837 Getr += ")"; // close the precedence "scope" for "*".
838
839 // Now, emit the argument types (if any).
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000840 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000841 Getr += "(";
842 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
843 if (i) Getr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000844 std::string ParamStr = FT->getArgType(i).getAsString(
845 Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000846 Getr += ParamStr;
847 }
848 if (FT->isVariadic()) {
849 if (FT->getNumArgs()) Getr += ", ";
850 Getr += "...";
851 }
852 Getr += ")";
853 } else
854 Getr += "()";
855 }
856 Getr += ";\n";
857 Getr += "return (_TYPE)";
858 Getr += "objc_getProperty(self, _cmd, ";
859 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
860 Getr += ", 1)";
861 }
862 else
863 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000864 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000865 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000866 if (PD->isReadOnly())
867 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Steve Naroffeb0646c2008-12-02 15:48:25 +0000869 // Generate the 'setter' function.
870 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
872 ObjCPropertyDecl::OBJC_PR_copy);
873 if (GenSetProperty && !objcSetPropertyDefined) {
874 objcSetPropertyDefined = true;
875 // FIXME. Is this attribute correct in all cases?
876 Setr = "\nextern \"C\" __declspec(dllimport) "
877 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
878 }
879
Steve Naroffeb0646c2008-12-02 15:48:25 +0000880 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000881 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000882 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000883 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 if (GenSetProperty) {
885 Setr += "objc_setProperty (self, _cmd, ";
886 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
887 Setr += ", (id)";
888 Setr += PD->getNameAsCString();
889 Setr += ", ";
890 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
891 Setr += "0, ";
892 else
893 Setr += "1, ";
894 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
895 Setr += "1)";
896 else
897 Setr += "0)";
898 }
899 else {
900 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
901 Setr += PD->getNameAsCString();
902 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000903 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000904 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000905}
Chris Lattner8a12c272007-10-11 18:38:32 +0000906
Steve Naroffb29b4272008-04-14 22:03:09 +0000907void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000908 // Get the start location and compute the semi location.
909 SourceLocation startLoc = ClassDecl->getLocation();
910 const char *startBuf = SM->getCharacterData(startLoc);
911 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Chris Lattnerf04da132007-10-24 17:06:59 +0000913 // Translate to typedef's that forward reference structs with the same name
914 // as the class. As a convenience, we include the original declaration
915 // as a comment.
916 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000917 typedefString += "// @class ";
918 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
919 I != E; ++I) {
920 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
921 typedefString += ForwardDecl->getNameAsString();
922 if (I+1 != E)
923 typedefString += ", ";
924 else
925 typedefString += ";\n";
926 }
927
Chris Lattner67956052009-02-20 18:04:31 +0000928 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
929 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000930 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000931 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000932 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000933 typedefString += "\n";
934 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000935 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000936 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000937 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000938 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000939 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Steve Naroff934f2762007-10-24 22:48:43 +0000942 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000943 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000944}
945
Steve Naroffb29b4272008-04-14 22:03:09 +0000946void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000947 // When method is a synthesized one, such as a getter/setter there is
948 // nothing to rewrite.
949 if (Method->isSynthesized())
950 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000951 SourceLocation LocStart = Method->getLocStart();
952 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Chris Lattner30fc9332009-02-04 01:06:56 +0000954 if (SM->getInstantiationLineNumber(LocEnd) >
955 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 InsertText(LocStart, "#if 0\n");
957 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000958 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000959 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000960 }
961}
962
Mike Stump1eb44332009-09-09 15:08:12 +0000963void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000964 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Benjamin Kramerd999b372010-02-14 14:14:16 +0000966 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000967 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000968}
969
Steve Naroffb29b4272008-04-14 22:03:09 +0000970void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000971 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Steve Naroff423cb562007-10-30 13:30:57 +0000973 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000974 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000976 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
977 E = CatDecl->prop_end(); I != E; ++I)
978 RewriteProperty(*I);
979
Mike Stump1eb44332009-09-09 15:08:12 +0000980 for (ObjCCategoryDecl::instmeth_iterator
981 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000982 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000983 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000984 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000985 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000986 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000987 RewriteMethodDeclaration(*I);
988
Steve Naroff423cb562007-10-30 13:30:57 +0000989 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000990 ReplaceText(CatDecl->getAtEndRange().getBegin(),
991 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000992}
993
Steve Naroffb29b4272008-04-14 22:03:09 +0000994void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000995 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Steve Naroff752d6ef2007-10-30 16:42:30 +0000997 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000999
1000 for (ObjCProtocolDecl::instmeth_iterator
1001 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001002 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001003 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001004 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001005 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001006 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001007 RewriteMethodDeclaration(*I);
1008
Steve Naroff752d6ef2007-10-30 16:42:30 +00001009 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001010 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001011 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001012
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001013 // Must comment out @optional/@required
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
1016 for (const char *p = startBuf; p < endBuf; p++) {
1017 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001018 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001019 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001021 }
1022 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001023 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001024 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001026 }
1027 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001028}
1029
Steve Naroffb29b4272008-04-14 22:03:09 +00001030void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001031 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001032 if (LocStart.isInvalid())
1033 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001034 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001035 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001036}
1037
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001038void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1039 const FunctionType *&FPRetType) {
1040 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001041 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001042 else if (T->isFunctionPointerType() ||
1043 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001044 // needs special handling, since pointer-to-functions have special
1045 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001046 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001047 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001048 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001049 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001050 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001051 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001052 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001053 ResultStr += FPRetType->getResultType().getAsString(
1054 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001055 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001056 }
1057 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001058 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001059}
1060
1061void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1062 std::string &ResultStr) {
1063 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1064 const FunctionType *FPRetType = 0;
1065 ResultStr += "\nstatic ";
1066 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001067 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001071
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001072 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001073 NameStr += "_I_";
1074 else
1075 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001077 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001078 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001079
1080 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001081 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001082 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001083 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001086 {
1087 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 int len = selString.size();
1089 for (int i = 0; i < len; i++)
1090 if (selString[i] == ':')
1091 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001092 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001093 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001094 // Remember this name for metadata emission
1095 MethodInternalNames[OMD] = NameStr;
1096 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 // Rewrite arguments
1099 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001102 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001103 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001104 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001105 if (!LangOpts.Microsoft) {
1106 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1107 ResultStr += "struct ";
1108 }
1109 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001110 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001111 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001112 }
1113 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001114 ResultStr += Context->getObjCClassType().getAsString(
1115 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001117 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001118 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001122 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1123 E = OMD->param_end(); PI != E; ++PI) {
1124 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001125 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001126 if (PDecl->getType()->isObjCQualifiedIdType()) {
1127 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001128 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001129 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001130 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001131 QualType QT = PDecl->getType();
1132 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1133 if (convertBlockPointerToFunctionPointer(QT))
1134 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1135 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001136 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001137 ResultStr += Name;
1138 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001139 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001140 if (OMD->isVariadic())
1141 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001142 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Steve Naroff76e429d2008-07-16 14:40:40 +00001144 if (FPRetType) {
1145 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Steve Naroff76e429d2008-07-16 14:40:40 +00001147 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001148 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001149 ResultStr += "(";
1150 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1151 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001152 std::string ParamStr = FT->getArgType(i).getAsString(
1153 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 ResultStr += ParamStr;
1155 }
1156 if (FT->isVariadic()) {
1157 if (FT->getNumArgs()) ResultStr += ", ";
1158 ResultStr += "...";
1159 }
1160 ResultStr += ")";
1161 } else {
1162 ResultStr += "()";
1163 }
1164 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001166void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001167 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1168 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001170 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001172 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001173 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1174 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001175 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 ObjCMethodDecl *OMD = *I;
1178 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001179 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001180 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001181
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185 }
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001187 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001188 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1189 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001190 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001191 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 ObjCMethodDecl *OMD = *I;
1193 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001195 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001197 const char *startBuf = SM->getCharacterData(LocStart);
1198 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001199 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001200 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001201 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001202 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001203 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001204 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001205 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001206 }
1207
Benjamin Kramerd999b372010-02-14 14:14:16 +00001208 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001209}
1210
Steve Naroffb29b4272008-04-14 22:03:09 +00001211void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001212 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001213 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001214 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001215 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001216 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001217 ResultStr += "\n";
1218 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001219 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001220 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001221 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001222 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001223 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001224 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001225 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001226 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001227 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
1229 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001230 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001231 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001232 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001233 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001234 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001235 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001236 for (ObjCInterfaceDecl::classmeth_iterator
1237 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001238 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001239 RewriteMethodDeclaration(*I);
1240
Steve Naroff2feac5e2007-10-30 03:43:13 +00001241 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001242 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1243 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001244}
1245
Steve Naroffb619d952008-12-09 12:56:34 +00001246Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1247 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001248 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1249 // This allows us to reuse all the fun and games in SynthMessageExpr().
1250 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1251 ObjCMessageExpr *MsgExpr;
1252 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1253 llvm::SmallVector<Expr *, 1> ExprVec;
1254 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Steve Naroff8599e7a2008-12-08 16:43:47 +00001256 Stmt *Receiver = PropRefExpr->getBase();
1257 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1258 if (PRE && PropGetters[PRE]) {
1259 // This allows us to handle chain/nested property getters.
1260 Receiver = PropGetters[PRE];
1261 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001262 if (isa<ObjCSuperExpr>(Receiver))
1263 MsgExpr = ObjCMessageExpr::Create(*Context,
1264 PDecl->getType().getNonReferenceType(),
1265 /*FIXME?*/SourceLocation(),
1266 Receiver->getLocStart(),
1267 /*IsInstanceSuper=*/true,
1268 cast<Expr>(Receiver)->getType(),
1269 PDecl->getSetterName(),
1270 PDecl->getSetterMethodDecl(),
1271 &ExprVec[0], 1,
1272 /*FIXME:*/SourceLocation());
1273 else
1274 MsgExpr = ObjCMessageExpr::Create(*Context,
1275 PDecl->getType().getNonReferenceType(),
1276 /*FIXME: */SourceLocation(),
1277 cast<Expr>(Receiver),
1278 PDecl->getSetterName(),
1279 PDecl->getSetterMethodDecl(),
1280 &ExprVec[0], 1,
1281 /*FIXME:*/SourceLocation());
Steve Naroffc77a6362008-12-04 16:24:46 +00001282 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Steve Naroffc77a6362008-12-04 16:24:46 +00001284 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001285 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001286 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001290 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001291}
1292
Steve Naroffc77a6362008-12-04 16:24:46 +00001293Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1295 // This allows us to reuse all the fun and games in SynthMessageExpr().
1296 ObjCMessageExpr *MsgExpr;
1297 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Steve Naroff8599e7a2008-12-08 16:43:47 +00001299 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Steve Naroff8599e7a2008-12-08 16:43:47 +00001301 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1302 if (PRE && PropGetters[PRE]) {
1303 // This allows us to handle chain/nested property getters.
1304 Receiver = PropGetters[PRE];
1305 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001306
1307 if (isa<ObjCSuperExpr>(Receiver))
1308 MsgExpr = ObjCMessageExpr::Create(*Context,
1309 PDecl->getType().getNonReferenceType(),
1310 /*FIXME:*/SourceLocation(),
1311 Receiver->getLocStart(),
1312 /*IsInstanceSuper=*/true,
1313 cast<Expr>(Receiver)->getType(),
1314 PDecl->getGetterName(),
1315 PDecl->getGetterMethodDecl(),
1316 0, 0,
1317 /*FIXME:*/SourceLocation());
1318 else
1319 MsgExpr = ObjCMessageExpr::Create(*Context,
1320 PDecl->getType().getNonReferenceType(),
1321 /*FIXME:*/SourceLocation(),
1322 cast<Expr>(Receiver),
1323 PDecl->getGetterName(),
1324 PDecl->getGetterMethodDecl(),
1325 0, 0,
1326 /*FIXME:*/SourceLocation());
Steve Naroff15f081d2008-12-03 00:56:33 +00001327
Steve Naroff4c3580e2008-12-04 23:50:32 +00001328 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001329
1330 if (!PropParentMap)
1331 PropParentMap = new ParentMap(CurrentBody);
1332
1333 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1334 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1335 // We stash away the ReplacingStmt since actually doing the
1336 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1337 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001338 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1339 // to things that stay around.
1340 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001341 return PropRefExpr; // return the original...
1342 } else {
1343 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001344 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001345 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1346 // to things that stay around.
1347 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001348 return ReplacingStmt;
1349 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001350}
1351
Mike Stump1eb44332009-09-09 15:08:12 +00001352Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001353 SourceLocation OrigStart,
1354 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001355 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001356 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001357 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001358 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001359 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001360 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001361 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001362 // lookup which class implements the instance variable.
1363 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001364 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001365 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001366 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Steve Narofff0757612008-05-08 17:52:16 +00001368 // Synthesize an explicit cast to gain access to the ivar.
1369 std::string RecName = clsDeclared->getIdentifier()->getName();
1370 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001371 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001372 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001373 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001374 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1375 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001376 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1377 CastExpr::CK_Unknown,
1378 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001379 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001380 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1381 IV->getBase()->getLocEnd(),
1382 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001383 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001384 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001385 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001386 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1387 IV->getLocation(),
1388 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001389 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001390 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001391 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001392 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001393 // Cannot delete IV->getBase(), since PE points to it.
1394 // Replace the old base with the cast. This is important when doing
1395 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001396 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001397 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001398 }
Steve Naroff84472a82008-04-18 21:55:08 +00001399 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001400 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Steve Naroff9f525972008-05-06 23:20:07 +00001402 // Explicit ivar refs need to have a cast inserted.
1403 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001404 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001405 ObjCInterfaceType *iFaceDecl =
1406 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001407 // lookup which class implements the instance variable.
1408 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001409 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001410 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001411 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Steve Naroff9f525972008-05-06 23:20:07 +00001413 // Synthesize an explicit cast to gain access to the ivar.
1414 std::string RecName = clsDeclared->getIdentifier()->getName();
1415 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001416 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001417 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001418 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001419 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1420 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001421 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1422 CastExpr::CK_Unknown,
1423 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001424 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001425 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001426 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001427 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001428 // Cannot delete IV->getBase(), since PE points to it.
1429 // Replace the old base with the cast. This is important when doing
1430 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001431 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001432 return IV;
1433 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001434 }
Steve Naroff84472a82008-04-18 21:55:08 +00001435 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001436}
1437
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001438Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1439 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1440 CI != E; ++CI) {
1441 if (*CI) {
1442 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1443 if (newStmt)
1444 *CI = newStmt;
1445 }
1446 }
1447 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1448 SourceRange OrigStmtRange = S->getSourceRange();
1449 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1450 replaced);
1451 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001452 }
1453 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1454 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1455 return newStmt;
1456 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001457 return S;
1458}
1459
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460/// SynthCountByEnumWithState - To print:
1461/// ((unsigned int (*)
1462/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001463/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001464/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001465/// "countByEnumeratingWithState:objects:count:"),
1466/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001467/// (id *)items, (unsigned int)16)
1468///
Steve Naroffb29b4272008-04-14 22:03:09 +00001469void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001470 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1471 "id *, unsigned int))(void *)objc_msgSend)";
1472 buf += "\n\t\t";
1473 buf += "((id)l_collection,\n\t\t";
1474 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1475 buf += "\n\t\t";
1476 buf += "&enumState, "
1477 "(id *)items, (unsigned int)16)";
1478}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001479
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001480/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1481/// statement to exit to its outer synthesized loop.
1482///
Steve Naroffb29b4272008-04-14 22:03:09 +00001483Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001484 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1485 return S;
1486 // replace break with goto __break_label
1487 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001489 SourceLocation startLoc = S->getLocStart();
1490 buf = "goto __break_label_";
1491 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001492 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001493
1494 return 0;
1495}
1496
1497/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1498/// statement to continue with its inner synthesized loop.
1499///
Steve Naroffb29b4272008-04-14 22:03:09 +00001500Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001501 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1502 return S;
1503 // replace continue with goto __continue_label
1504 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001506 SourceLocation startLoc = S->getLocStart();
1507 buf = "goto __continue_label_";
1508 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001509 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001511 return 0;
1512}
1513
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001514/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001515/// It rewrites:
1516/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001518/// Into:
1519/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001520/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001522/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001524/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001526/// if (limit) {
1527/// unsigned long startMutations = *enumState.mutationsPtr;
1528/// do {
1529/// unsigned long counter = 0;
1530/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001531/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001532/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001533/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001534/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001535/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001536/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001537/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001538/// objects:items count:16]);
1539/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001540/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001541/// }
1542/// else
1543/// elem = nil;
1544/// }
1545///
Steve Naroffb29b4272008-04-14 22:03:09 +00001546Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001547 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001548 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001549 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001550 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001551 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001552 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001554 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001555 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001556 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001557 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001558 std::string buf;
1559 buf = "\n{\n\t";
1560 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1561 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001562 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001563 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001564 if (ElementType->isObjCQualifiedIdType() ||
1565 ElementType->isObjCQualifiedInterfaceType())
1566 // Simply use 'id' for all qualified types.
1567 elementTypeAsString = "id";
1568 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001569 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001570 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001572 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573 buf += elementName;
1574 buf += ";\n\t";
1575 }
Chris Lattner06767512008-04-08 05:52:18 +00001576 else {
1577 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001578 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001579 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1580 if (VD->getType()->isObjCQualifiedIdType() ||
1581 VD->getType()->isObjCQualifiedInterfaceType())
1582 // Simply use 'id' for all qualified types.
1583 elementTypeAsString = "id";
1584 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001585 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001588 // struct __objcFastEnumerationState enumState = { 0 };
1589 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1590 // id items[16];
1591 buf += "id items[16];\n\t";
1592 // id l_collection = (id)
1593 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001594 // Find start location of 'collection' the hard way!
1595 const char *startCollectionBuf = startBuf;
1596 startCollectionBuf += 3; // skip 'for'
1597 startCollectionBuf = strchr(startCollectionBuf, '(');
1598 startCollectionBuf++; // skip '('
1599 // find 'in' and skip it.
1600 while (*startCollectionBuf != ' ' ||
1601 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1602 (*(startCollectionBuf+3) != ' ' &&
1603 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1604 startCollectionBuf++;
1605 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001606
1607 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001608 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001610 SourceLocation rightParenLoc = S->getRParenLoc();
1611 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1612 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1616 // objects:items count:16];
1617 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001618 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 // ((unsigned int (*)
1620 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001621 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001622 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001623 // "countByEnumeratingWithState:objects:count:"),
1624 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625 // (id *)items, (unsigned int)16);
1626 buf += "unsigned long limit =\n\t\t";
1627 SynthCountByEnumWithState(buf);
1628 buf += ";\n\t";
1629 /// if (limit) {
1630 /// unsigned long startMutations = *enumState.mutationsPtr;
1631 /// do {
1632 /// unsigned long counter = 0;
1633 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001634 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001635 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001636 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001637 buf += "if (limit) {\n\t";
1638 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1639 buf += "do {\n\t\t";
1640 buf += "unsigned long counter = 0;\n\t\t";
1641 buf += "do {\n\t\t\t";
1642 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1643 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1644 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001645 buf += " = (";
1646 buf += elementTypeAsString;
1647 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001648 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001649 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001650
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001651 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001652 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001653 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 /// objects:items count:16]);
1655 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001656 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 /// }
1658 /// else
1659 /// elem = nil;
1660 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001661 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001662 buf = ";\n\t";
1663 buf += "__continue_label_";
1664 buf += utostr(ObjCBcLabelNo.back());
1665 buf += ": ;";
1666 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001667 buf += "} while (counter < limit);\n\t";
1668 buf += "} while (limit = ";
1669 SynthCountByEnumWithState(buf);
1670 buf += ");\n\t";
1671 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001672 buf += " = ((";
1673 buf += elementTypeAsString;
1674 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001675 buf += "__break_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 buf += "}\n\t";
1679 buf += "else\n\t\t";
1680 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001681 buf += " = ((";
1682 buf += elementTypeAsString;
1683 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001684 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001686 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001687 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001688 if (isa<CompoundStmt>(S->getBody())) {
1689 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001690 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001691 } else {
1692 /* Need to treat single statements specially. For example:
1693 *
1694 * for (A *a in b) if (stuff()) break;
1695 * for (A *a in b) xxxyy;
1696 *
1697 * The following code simply scans ahead to the semi to find the actual end.
1698 */
1699 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1700 const char *semiBuf = strchr(stmtBuf, ';');
1701 assert(semiBuf && "Can't find ';'");
1702 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001703 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001704 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001705 Stmts.pop_back();
1706 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001707 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001708}
1709
Mike Stump1eb44332009-09-09 15:08:12 +00001710/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001711/// This routine rewrites @synchronized(expr) stmt;
1712/// into:
1713/// objc_sync_enter(expr);
1714/// @try stmt @finally { objc_sync_exit(expr); }
1715///
Steve Naroffb29b4272008-04-14 22:03:09 +00001716Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001717 // Get the start location and compute the semi location.
1718 SourceLocation startLoc = S->getLocStart();
1719 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001721 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001722
1723 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001724 buf = "objc_sync_enter((id)";
1725 const char *lparenBuf = startBuf;
1726 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001727 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001728 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1729 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001730 // been rewritten! (which implies the SourceLocation's are invalid).
1731 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001732 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001733 while (*endBuf != ')') endBuf--;
1734 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001735 buf = ");\n";
1736 // declare a new scope with two variables, _stack and _rethrow.
1737 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1738 buf += "int buf[18/*32-bit i386*/];\n";
1739 buf += "char *pointers[4];} _stack;\n";
1740 buf += "id volatile _rethrow = 0;\n";
1741 buf += "objc_exception_try_enter(&_stack);\n";
1742 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001743 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001744 startLoc = S->getSynchBody()->getLocEnd();
1745 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Steve Naroffc7089f12008-08-19 13:04:19 +00001747 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001748 SourceLocation lastCurlyLoc = startLoc;
1749 buf = "}\nelse {\n";
1750 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001751 buf += "}\n";
1752 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001753 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001754
1755 std::string syncBuf;
1756 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001757 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1758 CastExpr::CK_Unknown,
1759 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001760 std::string syncExprBufS;
1761 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001762 syncExpr->printPretty(syncExprBuf, *Context, 0,
1763 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001764 syncBuf += syncExprBuf.str();
1765 syncBuf += ");";
1766
1767 buf += syncBuf;
1768 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001769 buf += "}\n";
1770 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Benjamin Kramerd999b372010-02-14 14:14:16 +00001772 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001773
1774 bool hasReturns = false;
1775 HasReturnStmts(S->getSynchBody(), hasReturns);
1776 if (hasReturns)
1777 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1778
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001779 return 0;
1780}
1781
Steve Naroffb85e77a2009-12-05 21:43:12 +00001782void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1783{
Steve Naroff8c565152008-12-05 17:03:39 +00001784 // Perform a bottom up traversal of all children.
1785 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1786 CI != E; ++CI)
1787 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001788 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001789
Steve Naroffb85e77a2009-12-05 21:43:12 +00001790 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001791 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001792 TryFinallyContainsReturnDiag);
1793 }
1794 return;
1795}
1796
Steve Naroffb85e77a2009-12-05 21:43:12 +00001797void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1798{
1799 // Perform a bottom up traversal of all children.
1800 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1801 CI != E; ++CI)
1802 if (*CI)
1803 HasReturnStmts(*CI, hasReturns);
1804
1805 if (isa<ReturnStmt>(S))
1806 hasReturns = true;
1807 return;
1808}
1809
1810void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1811 // Perform a bottom up traversal of all children.
1812 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1813 CI != E; ++CI)
1814 if (*CI) {
1815 RewriteTryReturnStmts(*CI);
1816 }
1817 if (isa<ReturnStmt>(S)) {
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
1820
1821 const char *semiBuf = strchr(startBuf, ';');
1822 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1823 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1824
1825 std::string buf;
1826 buf = "{ objc_exception_try_exit(&_stack); return";
1827
Benjamin Kramerd999b372010-02-14 14:14:16 +00001828 ReplaceText(startLoc, 6, buf);
1829 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001830 }
1831 return;
1832}
1833
1834void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1835 // Perform a bottom up traversal of all children.
1836 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1837 CI != E; ++CI)
1838 if (*CI) {
1839 RewriteSyncReturnStmts(*CI, syncExitBuf);
1840 }
1841 if (isa<ReturnStmt>(S)) {
1842 SourceLocation startLoc = S->getLocStart();
1843 const char *startBuf = SM->getCharacterData(startLoc);
1844
1845 const char *semiBuf = strchr(startBuf, ';');
1846 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1847 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1848
1849 std::string buf;
1850 buf = "{ objc_exception_try_exit(&_stack);";
1851 buf += syncExitBuf;
1852 buf += " return";
1853
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(startLoc, 6, buf);
1855 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001856 }
1857 return;
1858}
1859
Steve Naroffb29b4272008-04-14 22:03:09 +00001860Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001861 // Get the start location and compute the semi location.
1862 SourceLocation startLoc = S->getLocStart();
1863 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Steve Naroff75730982007-11-07 04:08:17 +00001865 assert((*startBuf == '@') && "bogus @try location");
1866
1867 std::string buf;
1868 // declare a new scope with two variables, _stack and _rethrow.
1869 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1870 buf += "int buf[18/*32-bit i386*/];\n";
1871 buf += "char *pointers[4];} _stack;\n";
1872 buf += "id volatile _rethrow = 0;\n";
1873 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001874 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001875
Benjamin Kramerd999b372010-02-14 14:14:16 +00001876 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Steve Naroff75730982007-11-07 04:08:17 +00001878 startLoc = S->getTryBody()->getLocEnd();
1879 startBuf = SM->getCharacterData(startLoc);
1880
1881 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Steve Naroff75730982007-11-07 04:08:17 +00001883 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001884 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001885 startLoc = startLoc.getFileLocWithOffset(1);
1886 buf = " /* @catch begin */ else {\n";
1887 buf += " id _caught = objc_exception_extract(&_stack);\n";
1888 buf += " objc_exception_try_enter (&_stack);\n";
1889 buf += " if (_setjmp(_stack.buf))\n";
1890 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1891 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Benjamin Kramerd999b372010-02-14 14:14:16 +00001893 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001894 } else { /* no catch list */
1895 buf = "}\nelse {\n";
1896 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1897 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001898 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001899 }
Steve Naroff75730982007-11-07 04:08:17 +00001900 bool sawIdTypedCatch = false;
1901 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001902 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1903 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001904 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001905
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001906 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001907 buf = "if ("; // we are generating code for the first catch clause
1908 else
1909 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001910 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001911 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Steve Naroff75730982007-11-07 04:08:17 +00001913 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Steve Naroff75730982007-11-07 04:08:17 +00001915 const char *lParenLoc = strchr(startBuf, '(');
1916
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001917 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001918 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001919 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001920 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1921 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001922 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001923 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001924 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Steve Naroffe12e6922008-02-01 20:02:07 +00001926 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001927 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001928 } else if (catchDecl) {
1929 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001930 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001931 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001932 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001933 sawIdTypedCatch = true;
John McCall506b57e2010-05-17 21:00:27 +00001934 } else if (const ObjCObjectPointerType *Ptr =
1935 t->getAs<ObjCObjectPointerType>()) {
1936 // Should be a pointer to a class.
1937 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1938 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001939 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001940 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001941 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001942 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001943 }
1944 }
1945 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001946 lastCatchBody = Catch->getCatchBody();
1947 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001948 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1949 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1950 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1951 assert((*rParenBuf == ')') && "bogus @catch paren location");
1952 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Mike Stump1eb44332009-09-09 15:08:12 +00001954 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001955 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001956 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001957 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001958 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001959 }
Steve Naroff75730982007-11-07 04:08:17 +00001960 }
1961 // Complete the catch list...
1962 if (lastCatchBody) {
1963 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001964 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1965 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff378f47a2008-09-11 15:29:03 +00001967 // Insert the last (implicit) else clause *before* the right curly brace.
1968 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1969 buf = "} /* last catch end */\n";
1970 buf += "else {\n";
1971 buf += " _rethrow = _caught;\n";
1972 buf += " objc_exception_try_exit(&_stack);\n";
1973 buf += "} } /* @catch end */\n";
1974 if (!S->getFinallyStmt())
1975 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001976 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Steve Naroff75730982007-11-07 04:08:17 +00001978 // Set lastCurlyLoc
1979 lastCurlyLoc = lastCatchBody->getLocEnd();
1980 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001981 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001982 startLoc = finalStmt->getLocStart();
1983 startBuf = SM->getCharacterData(startLoc);
1984 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Benjamin Kramerd999b372010-02-14 14:14:16 +00001986 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Steve Naroff75730982007-11-07 04:08:17 +00001988 Stmt *body = finalStmt->getFinallyBody();
1989 SourceLocation startLoc = body->getLocStart();
1990 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001991 assert(*SM->getCharacterData(startLoc) == '{' &&
1992 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001993 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001994 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Steve Naroff75730982007-11-07 04:08:17 +00001996 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001998 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001999 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Steve Naroff75730982007-11-07 04:08:17 +00002001 // Set lastCurlyLoc
2002 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Steve Naroff8c565152008-12-05 17:03:39 +00002004 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002005 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002006 } else { /* no finally clause - make sure we synthesize an implicit one */
2007 buf = "{ /* implicit finally clause */\n";
2008 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2009 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2010 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002011 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002012
2013 // Now check for any return/continue/go statements within the @try.
2014 // The implicit finally clause won't called if the @try contains any
2015 // jump statements.
2016 bool hasReturns = false;
2017 HasReturnStmts(S->getTryBody(), hasReturns);
2018 if (hasReturns)
2019 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002020 }
2021 // Now emit the final closing curly brace...
2022 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002023 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002024 return 0;
2025}
2026
Steve Naroffb29b4272008-04-14 22:03:09 +00002027Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002028 return 0;
2029}
2030
Steve Naroffb29b4272008-04-14 22:03:09 +00002031Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002032 return 0;
2033}
2034
Mike Stump1eb44332009-09-09 15:08:12 +00002035// This can't be done with ReplaceStmt(S, ThrowExpr), since
2036// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002037// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002038Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002039 // Get the start location and compute the semi location.
2040 SourceLocation startLoc = S->getLocStart();
2041 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Steve Naroff2bd03922007-11-07 15:32:26 +00002043 assert((*startBuf == '@') && "bogus @throw location");
2044
2045 std::string buf;
2046 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002047 if (S->getThrowExpr())
2048 buf = "objc_exception_throw(";
2049 else // add an implicit argument
2050 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002052 // handle "@ throw" correctly.
2053 const char *wBuf = strchr(startBuf, 'w');
2054 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002055 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Steve Naroff2bd03922007-11-07 15:32:26 +00002057 const char *semiBuf = strchr(startBuf, ';');
2058 assert((*semiBuf == ';') && "@throw: can't find ';'");
2059 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002060 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002061 return 0;
2062}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002063
Steve Naroffb29b4272008-04-14 22:03:09 +00002064Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002065 // Create a new string expression.
2066 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002067 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002068 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002069 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2070 StrEncoding.length(), false,StrType,
2071 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002072 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Chris Lattner07506182007-11-30 22:53:43 +00002074 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002075 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002076 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002077}
2078
Steve Naroffb29b4272008-04-14 22:03:09 +00002079Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002080 if (!SelGetUidFunctionDecl)
2081 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002082 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2083 // Create a call to sel_registerName("selName").
2084 llvm::SmallVector<Expr*, 8> SelExprs;
2085 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002086 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002087 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002088 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002089 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002090 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2091 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002092 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002093 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002094 return SelExp;
2095}
2096
Steve Naroffb29b4272008-04-14 22:03:09 +00002097CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002098 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2099 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002100 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002101 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Steve Naroffebf2b562007-10-23 23:50:29 +00002103 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002104 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Steve Naroffebf2b562007-10-23 23:50:29 +00002106 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002107 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002108 ImplicitCastExpr *ICE =
2109 new (Context) ImplicitCastExpr(pToFunc, CastExpr::CK_Unknown,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002110 DRE, CXXBaseSpecifierArray(),
Sebastian Redl906082e2010-07-20 04:20:21 +00002111 ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002112
John McCall183700f2009-09-21 23:43:11 +00002113 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002115 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002116 new (Context) CallExpr(*Context, ICE, args, nargs,
2117 FT->getCallResultType(*Context), EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002118 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002119}
2120
Steve Naroffd5255f52007-11-01 13:24:47 +00002121static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2122 const char *&startRef, const char *&endRef) {
2123 while (startBuf < endBuf) {
2124 if (*startBuf == '<')
2125 startRef = startBuf; // mark the start.
2126 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002127 if (startRef && *startRef == '<') {
2128 endRef = startBuf; // mark the end.
2129 return true;
2130 }
2131 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002132 }
2133 startBuf++;
2134 }
2135 return false;
2136}
2137
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002138static void scanToNextArgument(const char *&argRef) {
2139 int angle = 0;
2140 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2141 if (*argRef == '<')
2142 angle++;
2143 else if (*argRef == '>')
2144 angle--;
2145 argRef++;
2146 }
2147 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2148}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002149
Steve Naroffb29b4272008-04-14 22:03:09 +00002150bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002151 if (T->isObjCQualifiedIdType())
2152 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002153 if (const PointerType *PT = T->getAs<PointerType>()) {
2154 if (PT->getPointeeType()->isObjCQualifiedIdType())
2155 return true;
2156 }
2157 if (T->isObjCObjectPointerType()) {
2158 T = T->getPointeeType();
2159 return T->isObjCQualifiedInterfaceType();
2160 }
2161 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002162}
2163
Steve Naroff4f95b752008-07-29 18:15:38 +00002164void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2165 QualType Type = E->getType();
2166 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002167 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Steve Naroffcda658e2008-11-19 21:15:47 +00002169 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2170 Loc = ECE->getLParenLoc();
2171 EndLoc = ECE->getRParenLoc();
2172 } else {
2173 Loc = E->getLocStart();
2174 EndLoc = E->getLocEnd();
2175 }
2176 // This will defend against trying to rewrite synthesized expressions.
2177 if (Loc.isInvalid() || EndLoc.isInvalid())
2178 return;
2179
Steve Naroff4f95b752008-07-29 18:15:38 +00002180 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002181 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002182 const char *startRef = 0, *endRef = 0;
2183 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2184 // Get the locations of the startRef, endRef.
2185 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2186 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2187 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002188 InsertText(LessLoc, "/*");
2189 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002190 }
2191 }
2192}
2193
Steve Naroffb29b4272008-04-14 22:03:09 +00002194void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002195 SourceLocation Loc;
2196 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002197 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002198 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2199 Loc = VD->getLocation();
2200 Type = VD->getType();
2201 }
2202 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2203 Loc = FD->getLocation();
2204 // Check for ObjC 'id' and class types that have been adorned with protocol
2205 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002206 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002208 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002209 if (!proto)
2210 return;
2211 Type = proto->getResultType();
2212 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002213 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2214 Loc = FD->getLocation();
2215 Type = FD->getType();
2216 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002217 else
2218 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002220 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002221 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Steve Naroffd5255f52007-11-01 13:24:47 +00002223 const char *endBuf = SM->getCharacterData(Loc);
2224 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002225 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002226 startBuf--; // scan backward (from the decl location) for return type.
2227 const char *startRef = 0, *endRef = 0;
2228 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2229 // Get the locations of the startRef, endRef.
2230 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2231 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2232 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002233 InsertText(LessLoc, "/*");
2234 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002235 }
2236 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002237 if (!proto)
2238 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002239 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002240 const char *startBuf = SM->getCharacterData(Loc);
2241 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002242 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2243 if (needToScanForQualifiers(proto->getArgType(i))) {
2244 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Steve Naroffd5255f52007-11-01 13:24:47 +00002246 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002247 // scan forward (from the decl location) for argument types.
2248 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002249 const char *startRef = 0, *endRef = 0;
2250 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2251 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002252 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002253 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002254 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002255 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002256 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002257 InsertText(LessLoc, "/*");
2258 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002259 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002260 startBuf = ++endBuf;
2261 }
2262 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002263 // If the function name is derived from a macro expansion, then the
2264 // argument buffer will not follow the name. Need to speak with Chris.
2265 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002266 startBuf++; // scan forward (from the decl location) for argument types.
2267 startBuf++;
2268 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002269 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002270}
2271
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002272void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2273 QualType QT = ND->getType();
2274 const Type* TypePtr = QT->getAs<Type>();
2275 if (!isa<TypeOfExprType>(TypePtr))
2276 return;
2277 while (isa<TypeOfExprType>(TypePtr)) {
2278 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2279 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2280 TypePtr = QT->getAs<Type>();
2281 }
2282 // FIXME. This will not work for multiple declarators; as in:
2283 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002284 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002285 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2286 const char *startBuf = SM->getCharacterData(DeclLoc);
2287 if (ND->getInit()) {
2288 std::string Name(ND->getNameAsString());
2289 TypeAsString += " " + Name + " = ";
2290 Expr *E = ND->getInit();
2291 SourceLocation startLoc;
2292 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2293 startLoc = ECE->getLParenLoc();
2294 else
2295 startLoc = E->getLocStart();
2296 startLoc = SM->getInstantiationLoc(startLoc);
2297 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002298 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002299 }
2300 else {
2301 SourceLocation X = ND->getLocEnd();
2302 X = SM->getInstantiationLoc(X);
2303 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002304 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002305 }
2306}
2307
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002308// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002309void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002310 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2311 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002312 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002313 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002314 &ArgTys[0], ArgTys.size(),
2315 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002316 false, false, 0, 0,
2317 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002318 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002319 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002320 SelGetUidIdent, getFuncType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002321 FunctionDecl::Extern,
2322 FunctionDecl::None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002323}
2324
Steve Naroffb29b4272008-04-14 22:03:09 +00002325void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002326 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002327 if (FD->getIdentifier() &&
2328 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002329 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002330 return;
2331 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002332 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002333}
2334
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002335void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2336 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002337 const char *argPtr = TypeString.c_str();
2338 if (!strchr(argPtr, '^')) {
2339 Str += TypeString;
2340 return;
2341 }
2342 while (*argPtr) {
2343 Str += (*argPtr == '^' ? '*' : *argPtr);
2344 argPtr++;
2345 }
2346}
2347
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002348// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002349void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2350 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002351 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002352 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002353 const char *argPtr = TypeString.c_str();
2354 int paren = 0;
2355 while (*argPtr) {
2356 switch (*argPtr) {
2357 case '(':
2358 Str += *argPtr;
2359 paren++;
2360 break;
2361 case ')':
2362 Str += *argPtr;
2363 paren--;
2364 break;
2365 case '^':
2366 Str += '*';
2367 if (paren == 1)
2368 Str += VD->getNameAsString();
2369 break;
2370 default:
2371 Str += *argPtr;
2372 break;
2373 }
2374 argPtr++;
2375 }
2376}
2377
2378
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002379void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2380 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2381 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2382 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2383 if (!proto)
2384 return;
2385 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002386 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002387 FdStr += " ";
2388 FdStr += FD->getNameAsCString();
2389 FdStr += "(";
2390 unsigned numArgs = proto->getNumArgs();
2391 for (unsigned i = 0; i < numArgs; i++) {
2392 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002393 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002394 if (i+1 < numArgs)
2395 FdStr += ", ";
2396 }
2397 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002398 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002399 CurFunctionDeclToDeclareForBlock = 0;
2400}
2401
Steve Naroffc0a123c2008-03-11 17:37:02 +00002402// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002403void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002404 if (SuperContructorFunctionDecl)
2405 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002406 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002407 llvm::SmallVector<QualType, 16> ArgTys;
2408 QualType argT = Context->getObjCIdType();
2409 assert(!argT.isNull() && "Can't find 'id' type");
2410 ArgTys.push_back(argT);
2411 ArgTys.push_back(argT);
2412 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2413 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002414 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002415 false, false, 0, 0,
2416 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002417 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002418 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002419 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002420 FunctionDecl::Extern,
2421 FunctionDecl::None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002422}
2423
Steve Naroff09b266e2007-10-30 23:14:51 +00002424// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002425void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2427 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002435 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002436 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002437 false, false, 0, 0,
2438 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002439 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002440 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002441 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002442 FunctionDecl::Extern,
2443 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002444}
2445
Steve Naroff874e2322007-11-15 10:28:18 +00002446// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002447void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002448 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2449 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002450 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002451 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002452 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002453 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2454 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2455 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002456 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002457 assert(!argT.isNull() && "Can't find 'SEL' type");
2458 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002459 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002460 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002461 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002462 false, false, 0, 0,
2463 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002464 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002465 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002466 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002467 FunctionDecl::Extern,
2468 FunctionDecl::None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002469}
2470
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002471// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002472void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002473 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2474 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002475 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002476 assert(!argT.isNull() && "Can't find 'id' type");
2477 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002478 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002479 assert(!argT.isNull() && "Can't find 'SEL' type");
2480 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002481 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002482 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002483 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002484 false, false, 0, 0,
2485 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002486 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002487 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002488 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002489 FunctionDecl::Extern,
2490 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002491}
2492
Mike Stump1eb44332009-09-09 15:08:12 +00002493// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002494// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002495void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002496 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002497 &Context->Idents.get("objc_msgSendSuper_stret");
2498 llvm::SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002499 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002500 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002501 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002502 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2503 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2504 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002505 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002506 assert(!argT.isNull() && "Can't find 'SEL' type");
2507 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002508 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002509 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002510 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002511 false, false, 0, 0,
2512 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002513 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002514 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002515 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002516 FunctionDecl::Extern,
2517 FunctionDecl::None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002518}
2519
Steve Naroff1284db82008-05-08 22:02:18 +00002520// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002521void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002522 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2523 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002525 assert(!argT.isNull() && "Can't find 'id' type");
2526 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002527 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002528 assert(!argT.isNull() && "Can't find 'SEL' type");
2529 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002530 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002531 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002532 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002533 false, false, 0, 0,
2534 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002535 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002536 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002537 msgSendIdent, msgSendType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002538 FunctionDecl::Extern,
2539 FunctionDecl::None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002540}
2541
Steve Naroff09b266e2007-10-30 23:14:51 +00002542// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002543void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002544 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2545 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002546 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002547 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002548 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002549 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002550 false, false, 0, 0,
2551 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002552 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002553 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002554 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002555 FunctionDecl::Extern,
2556 FunctionDecl::None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002557}
2558
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002559// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2560void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2561 IdentifierInfo *getSuperClassIdent =
2562 &Context->Idents.get("class_getSuperclass");
2563 llvm::SmallVector<QualType, 16> ArgTys;
2564 ArgTys.push_back(Context->getObjCClassType());
2565 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2566 &ArgTys[0], ArgTys.size(),
2567 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002568 false, false, 0, 0,
2569 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002570 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002571 SourceLocation(),
2572 getSuperClassIdent,
2573 getClassType, 0,
2574 FunctionDecl::Extern,
2575 FunctionDecl::None,
2576 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002577}
2578
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002579// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002580void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002581 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2582 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002583 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002584 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002585 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002586 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002587 false, false, 0, 0,
2588 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002589 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002590 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002591 getClassIdent, getClassType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002592 FunctionDecl::Extern,
2593 FunctionDecl::None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002594}
2595
Steve Naroffb29b4272008-04-14 22:03:09 +00002596Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002597 QualType strType = getConstantStringStructType();
2598
2599 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002600
2601 std::string tmpName = InFileName;
2602 unsigned i;
2603 for (i=0; i < tmpName.length(); i++) {
2604 char c = tmpName.at(i);
2605 // replace any non alphanumeric characters with '_'.
2606 if (!isalpha(c) && (c < '0' || c > '9'))
2607 tmpName[i] = '_';
2608 }
2609 S += tmpName;
2610 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002611 S += utostr(NumObjCStringLiterals++);
2612
Steve Naroffba92b2e2008-03-27 22:29:16 +00002613 Preamble += "static __NSConstantStringImpl " + S;
2614 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2615 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002617 std::string prettyBufS;
2618 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002619 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2620 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002621 Preamble += prettyBuf.str();
2622 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002623 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002624
2625 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002626 &Context->Idents.get(S), strType, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002627 VarDecl::Static, VarDecl::None);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002628 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2629 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002630 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002631 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002632 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002633 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2634 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002635 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002636 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002637 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002638}
2639
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002640bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002641 // check if we are sending a message to 'super'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002642 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2643 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002644}
2645
2646// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002647QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002648 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002649 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002650 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002651 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002652 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Steve Naroff874e2322007-11-15 10:28:18 +00002654 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002655 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002656 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002657 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002658
Steve Naroff874e2322007-11-15 10:28:18 +00002659 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002660 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002661 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2662 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002663 FieldTypes[i], 0,
2664 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002665 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002666 }
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Douglas Gregor838db382010-02-11 01:19:42 +00002668 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002669 }
2670 return Context->getTagDeclType(SuperStructDecl);
2671}
2672
Steve Naroffb29b4272008-04-14 22:03:09 +00002673QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002674 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002675 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002676 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002677 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002678 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002680 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002681 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002682 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002683 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002684 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002685 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002686 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002687 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002688
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002689 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002690 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002691 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2692 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002693 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002694 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002695 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002696 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002697 }
2698
Douglas Gregor838db382010-02-11 01:19:42 +00002699 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 }
2701 return Context->getTagDeclType(ConstantStringDecl);
2702}
2703
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002704Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2705 SourceLocation StartLoc,
2706 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002707 if (!SelGetUidFunctionDecl)
2708 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002709 if (!MsgSendFunctionDecl)
2710 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002711 if (!MsgSendSuperFunctionDecl)
2712 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002713 if (!MsgSendStretFunctionDecl)
2714 SynthMsgSendStretFunctionDecl();
2715 if (!MsgSendSuperStretFunctionDecl)
2716 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002717 if (!MsgSendFpretFunctionDecl)
2718 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002719 if (!GetClassFunctionDecl)
2720 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002721 if (!GetSuperClassFunctionDecl)
2722 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002723 if (!GetMetaClassFunctionDecl)
2724 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Steve Naroff874e2322007-11-15 10:28:18 +00002726 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002727 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2728 // May need to use objc_msgSend_stret() as well.
2729 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002730 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2731 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002732 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002733 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002734 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002735 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002736 }
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Steve Naroff934f2762007-10-24 22:48:43 +00002738 // Synthesize a call to objc_msgSend().
2739 llvm::SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002740 switch (Exp->getReceiverKind()) {
2741 case ObjCMessageExpr::SuperClass: {
2742 MsgSendFlavor = MsgSendSuperFunctionDecl;
2743 if (MsgSendStretFlavor)
2744 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2745 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Douglas Gregor04badcf2010-04-21 00:45:42 +00002747 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Douglas Gregor04badcf2010-04-21 00:45:42 +00002749 llvm::SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002750
Douglas Gregor04badcf2010-04-21 00:45:42 +00002751 // set the receiver to self, the first argument to all methods.
2752 InitExprs.push_back(
2753 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2754 CastExpr::CK_Unknown,
2755 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2756 Context->getObjCIdType(),
2757 SourceLocation()))
2758 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Douglas Gregor04badcf2010-04-21 00:45:42 +00002760 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2761 llvm::SmallVector<Expr*, 8> ClsExprs;
2762 QualType argType = Context->getPointerType(Context->CharTy);
2763 ClsExprs.push_back(StringLiteral::Create(*Context,
2764 ClassDecl->getIdentifier()->getNameStart(),
2765 ClassDecl->getIdentifier()->getLength(),
2766 false, argType, SourceLocation()));
2767 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2768 &ClsExprs[0],
2769 ClsExprs.size(),
2770 StartLoc,
2771 EndLoc);
2772 // (Class)objc_getClass("CurrentClass")
2773 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2774 Context->getObjCClassType(),
2775 CastExpr::CK_Unknown, Cls);
2776 ClsExprs.clear();
2777 ClsExprs.push_back(ArgExpr);
2778 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2779 &ClsExprs[0], ClsExprs.size(),
2780 StartLoc, EndLoc);
2781
2782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 // To turn off a warning, type-cast to 'id'
2784 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2785 NoTypeInfoCStyleCastExpr(Context,
2786 Context->getObjCIdType(),
2787 CastExpr::CK_Unknown, Cls));
2788 // struct objc_super
2789 QualType superType = getSuperStructType();
2790 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002791
Douglas Gregor04badcf2010-04-21 00:45:42 +00002792 if (LangOpts.Microsoft) {
2793 SynthSuperContructorFunctionDecl();
2794 // Simulate a contructor call...
2795 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2796 superType, SourceLocation());
2797 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2798 InitExprs.size(),
2799 superType, SourceLocation());
2800 // The code for super is a little tricky to prevent collision with
2801 // the structure definition in the header. The rewriter has it's own
2802 // internal definition (__rw_objc_super) that is uses. This is why
2803 // we need the cast below. For example:
2804 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2805 //
2806 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2807 Context->getPointerType(SuperRep->getType()),
2808 SourceLocation());
2809 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2810 Context->getPointerType(superType),
2811 CastExpr::CK_Unknown, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002812 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002813 // (struct objc_super) { <exprs from above> }
2814 InitListExpr *ILE =
2815 new (Context) InitListExpr(*Context, SourceLocation(),
2816 &InitExprs[0], InitExprs.size(),
2817 SourceLocation());
2818 TypeSourceInfo *superTInfo
2819 = Context->getTrivialTypeSourceInfo(superType);
2820 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2821 superType, ILE, false);
2822 // struct objc_super *
2823 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2824 Context->getPointerType(SuperRep->getType()),
2825 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002826 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002827 MsgExprs.push_back(SuperRep);
2828 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002829 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830
2831 case ObjCMessageExpr::Class: {
2832 llvm::SmallVector<Expr*, 8> ClsExprs;
2833 QualType argType = Context->getPointerType(Context->CharTy);
2834 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002835 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 IdentifierInfo *clsName = Class->getIdentifier();
2837 ClsExprs.push_back(StringLiteral::Create(*Context,
2838 clsName->getNameStart(),
2839 clsName->getLength(),
2840 false, argType,
2841 SourceLocation()));
2842 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2843 &ClsExprs[0],
2844 ClsExprs.size(),
2845 StartLoc, EndLoc);
2846 MsgExprs.push_back(Cls);
2847 break;
2848 }
2849
2850 case ObjCMessageExpr::SuperInstance:{
2851 MsgSendFlavor = MsgSendSuperFunctionDecl;
2852 if (MsgSendStretFlavor)
2853 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2854 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2855 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2856 llvm::SmallVector<Expr*, 4> InitExprs;
2857
2858 InitExprs.push_back(
2859 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2860 CastExpr::CK_Unknown,
2861 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2862 Context->getObjCIdType(),
2863 SourceLocation()))
2864 ); // set the 'receiver'.
2865
2866 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2867 llvm::SmallVector<Expr*, 8> ClsExprs;
2868 QualType argType = Context->getPointerType(Context->CharTy);
2869 ClsExprs.push_back(StringLiteral::Create(*Context,
2870 ClassDecl->getIdentifier()->getNameStart(),
2871 ClassDecl->getIdentifier()->getLength(),
2872 false, argType, SourceLocation()));
2873 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2874 &ClsExprs[0],
2875 ClsExprs.size(),
2876 StartLoc, EndLoc);
2877 // (Class)objc_getClass("CurrentClass")
2878 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2879 Context->getObjCClassType(),
2880 CastExpr::CK_Unknown, Cls);
2881 ClsExprs.clear();
2882 ClsExprs.push_back(ArgExpr);
2883 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2884 &ClsExprs[0], ClsExprs.size(),
2885 StartLoc, EndLoc);
2886
2887 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2888 // To turn off a warning, type-cast to 'id'
2889 InitExprs.push_back(
2890 // set 'super class', using class_getSuperclass().
2891 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2892 CastExpr::CK_Unknown, Cls));
2893 // struct objc_super
2894 QualType superType = getSuperStructType();
2895 Expr *SuperRep;
2896
2897 if (LangOpts.Microsoft) {
2898 SynthSuperContructorFunctionDecl();
2899 // Simulate a contructor call...
2900 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2901 superType, SourceLocation());
2902 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2903 InitExprs.size(),
2904 superType, SourceLocation());
2905 // The code for super is a little tricky to prevent collision with
2906 // the structure definition in the header. The rewriter has it's own
2907 // internal definition (__rw_objc_super) that is uses. This is why
2908 // we need the cast below. For example:
2909 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2910 //
2911 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
2912 Context->getPointerType(SuperRep->getType()),
2913 SourceLocation());
2914 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2915 Context->getPointerType(superType),
2916 CastExpr::CK_Unknown, SuperRep);
2917 } else {
2918 // (struct objc_super) { <exprs from above> }
2919 InitListExpr *ILE =
2920 new (Context) InitListExpr(*Context, SourceLocation(),
2921 &InitExprs[0], InitExprs.size(),
2922 SourceLocation());
2923 TypeSourceInfo *superTInfo
2924 = Context->getTrivialTypeSourceInfo(superType);
2925 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2926 superType, ILE, false);
2927 }
2928 MsgExprs.push_back(SuperRep);
2929 break;
2930 }
2931
2932 case ObjCMessageExpr::Instance: {
2933 // Remove all type-casts because it may contain objc-style types; e.g.
2934 // Foo<Proto> *.
2935 Expr *recExpr = Exp->getInstanceReceiver();
2936 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2937 recExpr = CE->getSubExpr();
2938 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2939 CastExpr::CK_Unknown, recExpr);
2940 MsgExprs.push_back(recExpr);
2941 break;
2942 }
2943 }
2944
Steve Naroffbeaf2992007-11-03 11:27:19 +00002945 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002946 llvm::SmallVector<Expr*, 8> SelExprs;
2947 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002948 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002949 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002950 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002951 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002952 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002953 &SelExprs[0], SelExprs.size(),
2954 StartLoc,
2955 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002956 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Steve Naroff934f2762007-10-24 22:48:43 +00002958 // Now push any user supplied arguments.
2959 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002960 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002961 // Make all implicit casts explicit...ICE comes in handy:-)
2962 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2963 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002964 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002965 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002966 : ICE->getType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002967 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002968 (void)convertBlockPointerToFunctionPointer(type);
John McCall9d125032010-01-15 18:39:57 +00002969 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2970 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002971 }
2972 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002973 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002974 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002975 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002976 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002977 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2978 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002979 }
Mike Stump1eb44332009-09-09 15:08:12 +00002980 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002981 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002982 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2983 // out the argument in the original expression (since we aren't deleting
2984 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2985 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002986 }
Steve Naroffab972d32007-11-04 22:37:50 +00002987 // Generate the funky cast.
2988 CastExpr *cast;
2989 llvm::SmallVector<QualType, 8> ArgTypes;
2990 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002991
Steve Naroffab972d32007-11-04 22:37:50 +00002992 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002993 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2994 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2995 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002996 ArgTypes.push_back(Context->getObjCIdType());
2997 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002998 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002999 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003000 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3001 E = OMD->param_end(); PI != E; ++PI) {
3002 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003003 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003004 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003005 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003006 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003007 ArgTypes.push_back(t);
3008 }
Chris Lattner89951a82009-02-20 18:43:26 +00003009 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3010 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003011 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003012 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003013 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003014 }
3015 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003016 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003017
Steve Naroffab972d32007-11-04 22:37:50 +00003018 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003019 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003020 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003021
Mike Stump1eb44332009-09-09 15:08:12 +00003022 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003023 // If we don't do this cast, we get the following bizarre warning/note:
3024 // xx.m:13: warning: function called through a non-compatible type
3025 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003026 cast = NoTypeInfoCStyleCastExpr(Context,
3027 Context->getPointerType(Context->VoidTy),
3028 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Steve Naroffab972d32007-11-04 22:37:50 +00003030 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003031 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003032 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00003033 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00003034 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003035 false, false, 0, 0,
3036 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00003037 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003038 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3039 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003040
3041 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003042 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003043
John McCall183700f2009-09-21 23:43:11 +00003044 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003045 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003046 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003047 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003048 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003049 if (MsgSendStretFlavor) {
3050 // We have the method which returns a struct/union. Must also generate
3051 // call to objc_msgSend_stret and hang both varieties on a conditional
3052 // expression which dictate which one to envoke depending on size of
3053 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003054
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003055 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003056 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003057 SourceLocation());
3058 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003059 cast = NoTypeInfoCStyleCastExpr(Context,
3060 Context->getPointerType(Context->VoidTy),
3061 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003062 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00003063 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003064 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003065 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003066 false, false, 0, 0,
3067 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003068 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003069 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3070 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003072 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003073 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003074
John McCall183700f2009-09-21 23:43:11 +00003075 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003076 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003077 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003078 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003080 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003081 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003082 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003083 Context->getSizeType(),
3084 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003085 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3086 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3087 // For X86 it is more complicated and some kind of target specific routine
3088 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003089 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003090 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00003091 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003092 Context->IntTy,
3093 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003094 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3095 BinaryOperator::LE,
3096 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003097 SourceLocation());
3098 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003099 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003100 new (Context) ConditionalOperator(lessThanExpr,
3101 SourceLocation(), CE,
3102 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003103 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003106 return ReplacingStmt;
3107}
3108
Steve Naroffb29b4272008-04-14 22:03:09 +00003109Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003110 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3111 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Steve Naroff934f2762007-10-24 22:48:43 +00003113 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003114 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003115
3116 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003117 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003118}
3119
Steve Naroff621edce2009-04-29 16:37:50 +00003120// typedef struct objc_object Protocol;
3121QualType RewriteObjC::getProtocolType() {
3122 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003123 TypeSourceInfo *TInfo
3124 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003125 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003126 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003127 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003128 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003129 }
3130 return Context->getTypeDeclType(ProtocolTypeDecl);
3131}
3132
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003133/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003134/// a synthesized/forward data reference (to the protocol's metadata).
3135/// The forward references (and metadata) are generated in
3136/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003137Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003138 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3139 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003140 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00003141 ID, getProtocolType(), 0,
3142 VarDecl::Extern, VarDecl::None);
Steve Naroff621edce2009-04-29 16:37:50 +00003143 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3144 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3145 Context->getPointerType(DRE->getType()),
3146 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003147 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3148 CastExpr::CK_Unknown,
3149 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003150 ReplaceStmt(Exp, castExpr);
3151 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003152 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003153 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003155}
3156
Mike Stump1eb44332009-09-09 15:08:12 +00003157bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003158 const char *endBuf) {
3159 while (startBuf < endBuf) {
3160 if (*startBuf == '#') {
3161 // Skip whitespace.
3162 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3163 ;
3164 if (!strncmp(startBuf, "if", strlen("if")) ||
3165 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3166 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3167 !strncmp(startBuf, "define", strlen("define")) ||
3168 !strncmp(startBuf, "undef", strlen("undef")) ||
3169 !strncmp(startBuf, "else", strlen("else")) ||
3170 !strncmp(startBuf, "elif", strlen("elif")) ||
3171 !strncmp(startBuf, "endif", strlen("endif")) ||
3172 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3173 !strncmp(startBuf, "include", strlen("include")) ||
3174 !strncmp(startBuf, "import", strlen("import")) ||
3175 !strncmp(startBuf, "include_next", strlen("include_next")))
3176 return true;
3177 }
3178 startBuf++;
3179 }
3180 return false;
3181}
3182
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003183/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003184/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003185void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003186 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003187 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003188 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003189 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003190 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003191 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003192 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003193 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003194 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003195 SourceLocation LocStart = CDecl->getLocStart();
3196 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003197
Steve Narofffea763e82007-11-14 19:25:57 +00003198 const char *startBuf = SM->getCharacterData(LocStart);
3199 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003200
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003201 // If no ivars and no root or if its root, directly or indirectly,
3202 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003203 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3204 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003205 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003206 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003207 return;
3208 }
Mike Stump1eb44332009-09-09 15:08:12 +00003209
3210 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003211 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003212 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003213 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003214 if (LangOpts.Microsoft)
3215 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003216
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003217 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003218 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003219 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003220 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003221 // If the buffer contains preprocessor directives, we do more fine-grained
3222 // rewrites. This is intended to fix code that looks like (which occurs in
3223 // NSURL.h, for example):
3224 //
3225 // #ifdef XYZ
3226 // @interface Foo : NSObject
3227 // #else
3228 // @interface FooBar : NSObject
3229 // #endif
3230 // {
3231 // int i;
3232 // }
3233 // @end
3234 //
3235 // This clause is segregated to avoid breaking the common case.
3236 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003237 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003238 CDecl->getClassLoc();
3239 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003240 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003241
Chris Lattnercafeb352009-02-20 18:18:36 +00003242 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003243 // advance to the end of the referenced protocols.
3244 while (endHeader < cursor && *endHeader != '>') endHeader++;
3245 endHeader++;
3246 }
3247 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003248 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003249 } else {
3250 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003251 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003252 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003253 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003254 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003255 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003256 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003257 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003258 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003259
Steve Narofffea763e82007-11-14 19:25:57 +00003260 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003261 SourceLocation OnePastCurly =
3262 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003263 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003264 }
3265 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003266
Steve Narofffea763e82007-11-14 19:25:57 +00003267 // Now comment out any visibility specifiers.
3268 while (cursor < endBuf) {
3269 if (*cursor == '@') {
3270 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003271 // Skip whitespace.
3272 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3273 /*scan*/;
3274
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003275 // FIXME: presence of @public, etc. inside comment results in
3276 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003277 if (!strncmp(cursor, "public", strlen("public")) ||
3278 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003279 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003280 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003281 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003282 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003283 // FIXME: If there are cases where '<' is used in ivar declaration part
3284 // of user code, then scan the ivar list and use needToScanForQualifiers
3285 // for type checking.
3286 else if (*cursor == '<') {
3287 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003288 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003289 cursor = strchr(cursor, '>');
3290 cursor++;
3291 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003292 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003293 } else if (*cursor == '^') { // rewrite block specifier.
3294 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003295 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003296 }
Steve Narofffea763e82007-11-14 19:25:57 +00003297 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003298 }
Steve Narofffea763e82007-11-14 19:25:57 +00003299 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003300 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003301 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003302 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003303 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003304 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003305 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003307 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003308 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003309 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003310 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003311 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003312 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003313}
3314
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003315// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003316/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003317template<typename MethodIterator>
3318void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3319 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003320 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003321 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003322 const char *ClassName,
3323 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003324 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003326 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003327 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003328 SEL _cmd;
3329 char *method_types;
3330 void *_imp;
3331 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003332 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003333 Result += "\nstruct _objc_method {\n";
3334 Result += "\tSEL _cmd;\n";
3335 Result += "\tchar *method_types;\n";
3336 Result += "\tvoid *_imp;\n";
3337 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003339 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003340 }
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003342 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Steve Naroff946a6932008-03-11 00:12:29 +00003344 /* struct {
3345 struct _objc_method_list *next_method;
3346 int method_count;
3347 struct _objc_method method_list[];
3348 }
3349 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003350 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003351 Result += "\nstatic struct {\n";
3352 Result += "\tstruct _objc_method_list *next_method;\n";
3353 Result += "\tint method_count;\n";
3354 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003355 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003356 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003357 Result += prefix;
3358 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3359 Result += "_METHODS_";
3360 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003361 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003362 Result += IsInstanceMethod ? "inst" : "cls";
3363 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003364 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003365
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003366 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003367 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003368 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003369 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003370 Result += "\", \"";
3371 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003372 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003373 Result += MethodInternalNames[*MethodBegin];
3374 Result += "}\n";
3375 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3376 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003377 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003378 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003379 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003380 Result += "\", \"";
3381 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003382 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003383 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003384 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003385 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003386 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003387}
3388
Steve Naroff621edce2009-04-29 16:37:50 +00003389/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003390void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003391RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3392 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003393 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003394
3395 // Output struct protocol_methods holder of method selector and type.
3396 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3397 /* struct protocol_methods {
3398 SEL _cmd;
3399 char *method_types;
3400 }
3401 */
3402 Result += "\nstruct _protocol_methods {\n";
3403 Result += "\tstruct objc_selector *_cmd;\n";
3404 Result += "\tchar *method_types;\n";
3405 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003406
Steve Naroff621edce2009-04-29 16:37:50 +00003407 objc_protocol_methods = true;
3408 }
3409 // Do not synthesize the protocol more than once.
3410 if (ObjCSynthesizedProtocols.count(PDecl))
3411 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003413 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3414 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3415 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003416 /* struct _objc_protocol_method_list {
3417 int protocol_method_count;
3418 struct protocol_methods protocols[];
3419 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003420 */
Steve Naroff621edce2009-04-29 16:37:50 +00003421 Result += "\nstatic struct {\n";
3422 Result += "\tint protocol_method_count;\n";
3423 Result += "\tstruct _protocol_methods protocol_methods[";
3424 Result += utostr(NumMethods);
3425 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3426 Result += PDecl->getNameAsString();
3427 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3428 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Steve Naroff621edce2009-04-29 16:37:50 +00003430 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003431 for (ObjCProtocolDecl::instmeth_iterator
3432 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003433 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003434 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003435 Result += "\t ,{{(struct objc_selector *)\"";
3436 else
3437 Result += "\t ,{(struct objc_selector *)\"";
3438 Result += (*I)->getSelector().getAsString().c_str();
3439 std::string MethodTypeString;
3440 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3441 Result += "\", \"";
3442 Result += MethodTypeString;
3443 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003444 }
Steve Naroff621edce2009-04-29 16:37:50 +00003445 Result += "\t }\n};\n";
3446 }
Mike Stump1eb44332009-09-09 15:08:12 +00003447
Steve Naroff621edce2009-04-29 16:37:50 +00003448 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003449 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3450 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003451 if (NumMethods > 0) {
3452 /* struct _objc_protocol_method_list {
3453 int protocol_method_count;
3454 struct protocol_methods protocols[];
3455 }
3456 */
3457 Result += "\nstatic struct {\n";
3458 Result += "\tint protocol_method_count;\n";
3459 Result += "\tstruct _protocol_methods protocol_methods[";
3460 Result += utostr(NumMethods);
3461 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3462 Result += PDecl->getNameAsString();
3463 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3464 "{\n\t";
3465 Result += utostr(NumMethods);
3466 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Steve Naroff621edce2009-04-29 16:37:50 +00003468 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003469 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003470 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003471 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003472 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003473 Result += "\t ,{{(struct objc_selector *)\"";
3474 else
3475 Result += "\t ,{(struct objc_selector *)\"";
3476 Result += (*I)->getSelector().getAsString().c_str();
3477 std::string MethodTypeString;
3478 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3479 Result += "\", \"";
3480 Result += MethodTypeString;
3481 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003482 }
Steve Naroff621edce2009-04-29 16:37:50 +00003483 Result += "\t }\n};\n";
3484 }
3485
3486 // Output:
3487 /* struct _objc_protocol {
3488 // Objective-C 1.0 extensions
3489 struct _objc_protocol_extension *isa;
3490 char *protocol_name;
3491 struct _objc_protocol **protocol_list;
3492 struct _objc_protocol_method_list *instance_methods;
3493 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003494 };
Steve Naroff621edce2009-04-29 16:37:50 +00003495 */
3496 static bool objc_protocol = false;
3497 if (!objc_protocol) {
3498 Result += "\nstruct _objc_protocol {\n";
3499 Result += "\tstruct _objc_protocol_extension *isa;\n";
3500 Result += "\tchar *protocol_name;\n";
3501 Result += "\tstruct _objc_protocol **protocol_list;\n";
3502 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3503 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003504 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Steve Naroff621edce2009-04-29 16:37:50 +00003506 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003507 }
Mike Stump1eb44332009-09-09 15:08:12 +00003508
Steve Naroff621edce2009-04-29 16:37:50 +00003509 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3510 Result += PDecl->getNameAsString();
3511 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3512 "{\n\t0, \"";
3513 Result += PDecl->getNameAsString();
3514 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003515 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003516 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3517 Result += PDecl->getNameAsString();
3518 Result += ", ";
3519 }
3520 else
3521 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003522 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003523 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3524 Result += PDecl->getNameAsString();
3525 Result += "\n";
3526 }
3527 else
3528 Result += "0\n";
3529 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Steve Naroff621edce2009-04-29 16:37:50 +00003531 // Mark this protocol as having been generated.
3532 if (!ObjCSynthesizedProtocols.insert(PDecl))
3533 assert(false && "protocol already synthesized");
3534
3535}
3536
3537void RewriteObjC::
3538RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3539 const char *prefix, const char *ClassName,
3540 std::string &Result) {
3541 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003542
Steve Naroff621edce2009-04-29 16:37:50 +00003543 for (unsigned i = 0; i != Protocols.size(); i++)
3544 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3545
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003546 // Output the top lovel protocol meta-data for the class.
3547 /* struct _objc_protocol_list {
3548 struct _objc_protocol_list *next;
3549 int protocol_count;
3550 struct _objc_protocol *class_protocols[];
3551 }
3552 */
3553 Result += "\nstatic struct {\n";
3554 Result += "\tstruct _objc_protocol_list *next;\n";
3555 Result += "\tint protocol_count;\n";
3556 Result += "\tstruct _objc_protocol *class_protocols[";
3557 Result += utostr(Protocols.size());
3558 Result += "];\n} _OBJC_";
3559 Result += prefix;
3560 Result += "_PROTOCOLS_";
3561 Result += ClassName;
3562 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3563 "{\n\t0, ";
3564 Result += utostr(Protocols.size());
3565 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003567 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003568 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003569 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003570
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003571 for (unsigned i = 1; i != Protocols.size(); i++) {
3572 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003573 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003574 Result += "\n";
3575 }
3576 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003577}
3578
Steve Naroff621edce2009-04-29 16:37:50 +00003579
Mike Stump1eb44332009-09-09 15:08:12 +00003580/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003581/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003582void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003583 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003584 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003585 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003586 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003587 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003588 CDecl = CDecl->getNextClassCategory())
3589 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3590 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003593 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003594 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003596 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003597 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003598 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003599
3600 // If any of our property implementations have associated getters or
3601 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003602 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3603 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003604 Prop != PropEnd; ++Prop) {
3605 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3606 continue;
3607 if (!(*Prop)->getPropertyIvarDecl())
3608 continue;
3609 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3610 if (!PD)
3611 continue;
3612 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3613 InstanceMethods.push_back(Getter);
3614 if (PD->isReadOnly())
3615 continue;
3616 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3617 InstanceMethods.push_back(Setter);
3618 }
3619 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003620 true, "CATEGORY_", FullCategoryName.c_str(),
3621 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003623 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003624 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003625 false, "CATEGORY_", FullCategoryName.c_str(),
3626 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003628 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003629 // Null CDecl is case of a category implementation with no category interface
3630 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003631 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3632 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003633 /* struct _objc_category {
3634 char *category_name;
3635 char *class_name;
3636 struct _objc_method_list *instance_methods;
3637 struct _objc_method_list *class_methods;
3638 struct _objc_protocol_list *protocols;
3639 // Objective-C 1.0 extensions
3640 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003641 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003642 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003643 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003644 */
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003646 static bool objc_category = false;
3647 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003648 Result += "\nstruct _objc_category {\n";
3649 Result += "\tchar *category_name;\n";
3650 Result += "\tchar *class_name;\n";
3651 Result += "\tstruct _objc_method_list *instance_methods;\n";
3652 Result += "\tstruct _objc_method_list *class_methods;\n";
3653 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003654 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003655 Result += "\tstruct _objc_property_list *instance_properties;\n";
3656 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003657 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003658 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003659 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3660 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003661 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003662 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003663 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003664 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003665 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003667 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003668 Result += "\t, (struct _objc_method_list *)"
3669 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3670 Result += FullCategoryName;
3671 Result += "\n";
3672 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003673 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003674 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003675 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003676 Result += "\t, (struct _objc_method_list *)"
3677 "&_OBJC_CATEGORY_CLASS_METHODS_";
3678 Result += FullCategoryName;
3679 Result += "\n";
3680 }
3681 else
3682 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Chris Lattnercafeb352009-02-20 18:18:36 +00003684 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003685 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003686 Result += FullCategoryName;
3687 Result += "\n";
3688 }
3689 else
3690 Result += "\t, 0\n";
3691 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003692}
3693
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003694/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3695/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003696void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003697 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003698 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003699 if (ivar->isBitField()) {
3700 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3701 // place all bitfields at offset 0.
3702 Result += "0";
3703 } else {
3704 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003705 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003706 if (LangOpts.Microsoft)
3707 Result += "_IMPL";
3708 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003709 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003710 Result += ")";
3711 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003712}
3713
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003714//===----------------------------------------------------------------------===//
3715// Meta Data Emission
3716//===----------------------------------------------------------------------===//
3717
Steve Naroffb29b4272008-04-14 22:03:09 +00003718void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003719 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003720 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003722 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003723 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003724 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003725 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003726 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003727 }
Mike Stump1eb44332009-09-09 15:08:12 +00003728
Chris Lattnerbe6df082007-12-12 07:56:42 +00003729 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003730 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003731 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003732 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003733 if (NumIvars > 0) {
3734 static bool objc_ivar = false;
3735 if (!objc_ivar) {
3736 /* struct _objc_ivar {
3737 char *ivar_name;
3738 char *ivar_type;
3739 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003740 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003741 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003742 Result += "\nstruct _objc_ivar {\n";
3743 Result += "\tchar *ivar_name;\n";
3744 Result += "\tchar *ivar_type;\n";
3745 Result += "\tint ivar_offset;\n";
3746 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003748 objc_ivar = true;
3749 }
3750
Steve Naroff946a6932008-03-11 00:12:29 +00003751 /* struct {
3752 int ivar_count;
3753 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003754 };
Steve Naroff946a6932008-03-11 00:12:29 +00003755 */
Mike Stump1eb44332009-09-09 15:08:12 +00003756 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003757 Result += "\tint ivar_count;\n";
3758 Result += "\tstruct _objc_ivar ivar_list[";
3759 Result += utostr(NumIvars);
3760 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003761 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003762 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003763 "{\n\t";
3764 Result += utostr(NumIvars);
3765 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003767 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003768 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003769 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003770 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003771 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003772 IV != IVEnd; ++IV)
3773 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003774 IVI = IDecl->ivar_begin();
3775 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003776 } else {
3777 IVI = CDecl->ivar_begin();
3778 IVE = CDecl->ivar_end();
3779 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003780 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003781 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003782 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003783 std::string TmpString, StrEncoding;
3784 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3785 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003786 Result += StrEncoding;
3787 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003788 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003789 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003790 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003791 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003792 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003793 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003794 std::string TmpString, StrEncoding;
3795 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3796 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003797 Result += StrEncoding;
3798 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003799 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003800 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003801 }
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003803 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003804 }
Mike Stump1eb44332009-09-09 15:08:12 +00003805
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003806 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003807 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003808 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003809
3810 // If any of our property implementations have associated getters or
3811 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003812 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3813 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003814 Prop != PropEnd; ++Prop) {
3815 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3816 continue;
3817 if (!(*Prop)->getPropertyIvarDecl())
3818 continue;
3819 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3820 if (!PD)
3821 continue;
3822 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3823 InstanceMethods.push_back(Getter);
3824 if (PD->isReadOnly())
3825 continue;
3826 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3827 InstanceMethods.push_back(Setter);
3828 }
3829 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003830 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003831
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003832 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003833 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003834 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003835
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003836 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003837 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3838 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003840 // Declaration of class/meta-class metadata
3841 /* struct _objc_class {
3842 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003843 const char *super_class_name;
3844 char *name;
3845 long version;
3846 long info;
3847 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003848 struct _objc_ivar_list *ivars;
3849 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003850 struct objc_cache *cache;
3851 struct objc_protocol_list *protocols;
3852 const char *ivar_layout;
3853 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003854 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003855 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003856 static bool objc_class = false;
3857 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003858 Result += "\nstruct _objc_class {\n";
3859 Result += "\tstruct _objc_class *isa;\n";
3860 Result += "\tconst char *super_class_name;\n";
3861 Result += "\tchar *name;\n";
3862 Result += "\tlong version;\n";
3863 Result += "\tlong info;\n";
3864 Result += "\tlong instance_size;\n";
3865 Result += "\tstruct _objc_ivar_list *ivars;\n";
3866 Result += "\tstruct _objc_method_list *methods;\n";
3867 Result += "\tstruct objc_cache *cache;\n";
3868 Result += "\tstruct _objc_protocol_list *protocols;\n";
3869 Result += "\tconst char *ivar_layout;\n";
3870 Result += "\tstruct _objc_class_ext *ext;\n";
3871 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003872 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003873 }
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003875 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003876 ObjCInterfaceDecl *RootClass = 0;
3877 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003878 while (SuperClass) {
3879 RootClass = SuperClass;
3880 SuperClass = SuperClass->getSuperClass();
3881 }
3882 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003883
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003884 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003885 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003886 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003887 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003888 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003889 Result += "\"";
3890
3891 if (SuperClass) {
3892 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003893 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003894 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003895 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003896 Result += "\"";
3897 }
3898 else {
3899 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003900 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003901 Result += "\"";
3902 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003903 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003904 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003905 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003906 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003907 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003908 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003909 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003910 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003911 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003912 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003913 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003914 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003915 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003916 Result += ",0,0\n";
3917 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003918 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\t,0,0,0,0\n";
3920 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003922 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003923 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003924 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003925 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003926 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003927 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003928 if (SuperClass) {
3929 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003930 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003932 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003933 Result += "\"";
3934 }
3935 else {
3936 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003937 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 Result += "\"";
3939 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003940 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003941 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003942 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003943 Result += ",0";
3944 else {
3945 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003946 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003947 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003948 if (LangOpts.Microsoft)
3949 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003950 Result += ")";
3951 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003953 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003954 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003955 Result += "\n\t";
3956 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003957 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003958 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003959 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003960 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003961 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003962 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003964 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003965 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003966 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003967 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003968 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003969 Result += ", 0,0\n";
3970 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003971 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003972 Result += ",0,0,0\n";
3973 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003974}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003975
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003976/// RewriteImplementations - This routine rewrites all method implementations
3977/// and emits meta-data.
3978
Steve Narofface66252008-11-13 20:07:04 +00003979void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003980 int ClsDefCount = ClassImplementation.size();
3981 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003983 // Rewrite implemented methods
3984 for (int i = 0; i < ClsDefCount; i++)
3985 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003987 for (int i = 0; i < CatDefCount; i++)
3988 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003989}
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Steve Narofface66252008-11-13 20:07:04 +00003991void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3992 int ClsDefCount = ClassImplementation.size();
3993 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003994
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003995 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003996 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003997 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003999 // For each implemented category, write out all its meta data.
4000 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004001 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004002
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004003 // Write objc_symtab metadata
4004 /*
4005 struct _objc_symtab
4006 {
4007 long sel_ref_cnt;
4008 SEL *refs;
4009 short cls_def_cnt;
4010 short cat_def_cnt;
4011 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004012 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004013 */
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004015 Result += "\nstruct _objc_symtab {\n";
4016 Result += "\tlong sel_ref_cnt;\n";
4017 Result += "\tSEL *refs;\n";
4018 Result += "\tshort cls_def_cnt;\n";
4019 Result += "\tshort cat_def_cnt;\n";
4020 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4021 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004023 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004024 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004025 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004026 + ", " + utostr(CatDefCount) + "\n";
4027 for (int i = 0; i < ClsDefCount; i++) {
4028 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004029 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 Result += "\n";
4031 }
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004033 for (int i = 0; i < CatDefCount; i++) {
4034 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004035 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004036 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004037 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004038 Result += "\n";
4039 }
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004041 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004043 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004045 /*
4046 struct _objc_module {
4047 long version;
4048 long size;
4049 const char *name;
4050 struct _objc_symtab *symtab;
4051 }
4052 */
Mike Stump1eb44332009-09-09 15:08:12 +00004053
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 Result += "\nstruct _objc_module {\n";
4055 Result += "\tlong version;\n";
4056 Result += "\tlong size;\n";
4057 Result += "\tconst char *name;\n";
4058 Result += "\tstruct _objc_symtab *symtab;\n";
4059 Result += "};\n\n";
4060 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004061 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004062 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004063 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004065
4066 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004067 if (ProtocolExprDecls.size()) {
4068 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4069 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004070 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004071 E = ProtocolExprDecls.end(); I != E; ++I) {
4072 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4073 Result += (*I)->getNameAsString();
4074 Result += " = &_OBJC_PROTOCOL_";
4075 Result += (*I)->getNameAsString();
4076 Result += ";\n";
4077 }
4078 Result += "#pragma data_seg(pop)\n\n";
4079 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004080 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004081 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004082 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4083 Result += "&_OBJC_MODULES;\n";
4084 Result += "#pragma data_seg(pop)\n\n";
4085 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004086}
Chris Lattner311ff022007-10-16 22:36:42 +00004087
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004088void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4089 const std::string &Name,
4090 ValueDecl *VD) {
4091 assert(BlockByRefDeclNo.count(VD) &&
4092 "RewriteByRefString: ByRef decl missing");
4093 ResultStr += "struct __Block_byref_" + Name +
4094 "_" + utostr(BlockByRefDeclNo[VD]) ;
4095}
4096
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004097static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4098 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4099 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4100 return false;
4101}
4102
Steve Naroff54055232008-10-27 17:20:55 +00004103std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4104 const char *funcName,
4105 std::string Tag) {
4106 const FunctionType *AFT = CE->getFunctionType();
4107 QualType RT = AFT->getResultType();
4108 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004109 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Steve Naroff54055232008-10-27 17:20:55 +00004110 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004111
Steve Naroff54055232008-10-27 17:20:55 +00004112 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Douglas Gregor72564e72009-02-26 23:50:07 +00004114 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004115 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004116 // block (to reference imported block decl refs).
4117 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004118 } else if (BD->param_empty()) {
4119 S += "(" + StructRef + " *__cself)";
4120 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004121 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004122 assert(FT && "SynthesizeBlockFunc: No function proto");
4123 S += '(';
4124 // first add the implicit argument.
4125 S += StructRef + " *__cself, ";
4126 std::string ParamStr;
4127 for (BlockDecl::param_iterator AI = BD->param_begin(),
4128 E = BD->param_end(); AI != E; ++AI) {
4129 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004130 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004131 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004132 if (convertBlockPointerToFunctionPointer(QT))
4133 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004134 else
4135 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004136 S += ParamStr;
4137 }
4138 if (FT->isVariadic()) {
4139 if (!BD->param_empty()) S += ", ";
4140 S += "...";
4141 }
4142 S += ')';
4143 }
4144 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004145
Steve Naroff54055232008-10-27 17:20:55 +00004146 // Create local declarations to avoid rewriting all closure decl ref exprs.
4147 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004148 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004149 E = BlockByRefDecls.end(); I != E; ++I) {
4150 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004151 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004152 std::string TypeString;
4153 RewriteByRefString(TypeString, Name, (*I));
4154 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004155 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004156 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004157 }
Steve Naroff54055232008-10-27 17:20:55 +00004158 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004159 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004160 E = BlockByCopyDecls.end(); I != E; ++I) {
4161 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004162 // Handle nested closure invocation. For example:
4163 //
4164 // void (^myImportedClosure)(void);
4165 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004166 //
Steve Naroff54055232008-10-27 17:20:55 +00004167 // void (^anotherClosure)(void);
4168 // anotherClosure = ^(void) {
4169 // myImportedClosure(); // import and invoke the closure
4170 // };
4171 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004172 if (isTopLevelBlockPointerType((*I)->getType())) {
4173 RewriteBlockPointerTypeVariable(S, (*I));
4174 S += " = (";
4175 RewriteBlockPointerType(S, (*I)->getType());
4176 S += ")";
4177 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4178 }
4179 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004180 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004181 QualType QT = (*I)->getType();
4182 if (HasLocalVariableExternalStorage(*I))
4183 QT = Context->getPointerType(QT);
4184 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004185 S += Name + " = __cself->" +
4186 (*I)->getNameAsString() + "; // bound by copy\n";
4187 }
Steve Naroff54055232008-10-27 17:20:55 +00004188 }
4189 std::string RewrittenStr = RewrittenBlockExprs[CE];
4190 const char *cstr = RewrittenStr.c_str();
4191 while (*cstr++ != '{') ;
4192 S += cstr;
4193 S += "\n";
4194 return S;
4195}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004196
Steve Naroff54055232008-10-27 17:20:55 +00004197std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4198 const char *funcName,
4199 std::string Tag) {
4200 std::string StructRef = "struct " + Tag;
4201 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Steve Naroff54055232008-10-27 17:20:55 +00004203 S += funcName;
4204 S += "_block_copy_" + utostr(i);
4205 S += "(" + StructRef;
4206 S += "*dst, " + StructRef;
4207 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004208 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004209 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004210 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004211 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004212 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004213 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004214 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004215 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004216 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004217 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004218 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004219 S += "}\n";
4220
Steve Naroff54055232008-10-27 17:20:55 +00004221 S += "\nstatic void __";
4222 S += funcName;
4223 S += "_block_dispose_" + utostr(i);
4224 S += "(" + StructRef;
4225 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004226 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004227 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004228 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004229 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004230 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004231 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004232 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004233 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004234 }
Mike Stump1eb44332009-09-09 15:08:12 +00004235 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004236 return S;
4237}
4238
Steve Naroff01aec112009-12-06 21:14:13 +00004239std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4240 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004241 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004242 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Steve Naroff54055232008-10-27 17:20:55 +00004244 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004245 S += " struct " + Desc;
4246 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004247
Steve Naroff01aec112009-12-06 21:14:13 +00004248 Constructor += "(void *fp, "; // Invoke function pointer.
4249 Constructor += "struct " + Desc; // Descriptor pointer.
4250 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004251
Steve Naroff54055232008-10-27 17:20:55 +00004252 if (BlockDeclRefs.size()) {
4253 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004254 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004255 E = BlockByCopyDecls.end(); I != E; ++I) {
4256 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004257 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004258 std::string ArgName = "_" + FieldName;
4259 // Handle nested closure invocation. For example:
4260 //
4261 // void (^myImportedBlock)(void);
4262 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004263 //
Steve Naroff54055232008-10-27 17:20:55 +00004264 // void (^anotherBlock)(void);
4265 // anotherBlock = ^(void) {
4266 // myImportedBlock(); // import and invoke the closure
4267 // };
4268 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004269 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004270 S += "struct __block_impl *";
4271 Constructor += ", void *" + ArgName;
4272 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004273 QualType QT = (*I)->getType();
4274 if (HasLocalVariableExternalStorage(*I))
4275 QT = Context->getPointerType(QT);
4276 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4277 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004278 Constructor += ", " + ArgName;
4279 }
4280 S += FieldName + ";\n";
4281 }
4282 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004283 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004284 E = BlockByRefDecls.end(); I != E; ++I) {
4285 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004286 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004287 std::string ArgName = "_" + FieldName;
4288 // Handle nested closure invocation. For example:
4289 //
4290 // void (^myImportedBlock)(void);
4291 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004292 //
Steve Naroff54055232008-10-27 17:20:55 +00004293 // void (^anotherBlock)(void);
4294 // anotherBlock = ^(void) {
4295 // myImportedBlock(); // import and invoke the closure
4296 // };
4297 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004298 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004299 S += "struct __block_impl *";
4300 Constructor += ", void *" + ArgName;
4301 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004302 std::string TypeString;
4303 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004304 TypeString += " *";
4305 FieldName = TypeString + FieldName;
4306 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004307 Constructor += ", " + ArgName;
4308 }
4309 S += FieldName + "; // by ref\n";
4310 }
4311 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004312 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004313 if (GlobalVarDecl)
4314 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4315 else
4316 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004317 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004318
Steve Naroff01aec112009-12-06 21:14:13 +00004319 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004320
Steve Naroff54055232008-10-27 17:20:55 +00004321 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004322 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004323 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004324 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004325 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004326 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004327 Constructor += Name + " = (struct __block_impl *)_";
4328 else
4329 Constructor += Name + " = _";
4330 Constructor += Name + ";\n";
4331 }
4332 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004333 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004334 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004335 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004336 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004337 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004338 Constructor += Name + " = (struct __block_impl *)_";
4339 else
4340 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004341 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004342 }
4343 } else {
4344 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004345 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004346 if (GlobalVarDecl)
4347 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4348 else
4349 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004350 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4351 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004352 }
4353 Constructor += " ";
4354 Constructor += "}\n";
4355 S += Constructor;
4356 S += "};\n";
4357 return S;
4358}
4359
Steve Naroff01aec112009-12-06 21:14:13 +00004360std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4361 std::string ImplTag, int i,
4362 const char *FunName,
4363 unsigned hasCopy) {
4364 std::string S = "\nstatic struct " + DescTag;
4365
4366 S += " {\n unsigned long reserved;\n";
4367 S += " unsigned long Block_size;\n";
4368 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004369 S += " void (*copy)(struct ";
4370 S += ImplTag; S += "*, struct ";
4371 S += ImplTag; S += "*);\n";
4372
4373 S += " void (*dispose)(struct ";
4374 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004375 }
4376 S += "} ";
4377
4378 S += DescTag + "_DATA = { 0, sizeof(struct ";
4379 S += ImplTag + ")";
4380 if (hasCopy) {
4381 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4382 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4383 }
4384 S += "};\n";
4385 return S;
4386}
4387
Steve Naroff54055232008-10-27 17:20:55 +00004388void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004389 const char *FunName) {
4390 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004391 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004392 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004393 bool RewriteSC = (GlobalVarDecl &&
4394 !Blocks.empty() &&
4395 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4396 GlobalVarDecl->getType().getCVRQualifiers());
4397 if (RewriteSC) {
4398 std::string SC(" void __");
4399 SC += GlobalVarDecl->getNameAsString();
4400 SC += "() {}";
4401 InsertText(FunLocStart, SC);
4402 }
4403
Steve Naroff54055232008-10-27 17:20:55 +00004404 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004405 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4406 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004407 // Need to copy-in the inner copied-in variables not actually used in this
4408 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004409 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4410 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4411 ValueDecl *VD = Exp->getDecl();
4412 BlockDeclRefs.push_back(Exp);
4413 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4414 BlockByCopyDeclsPtrSet.insert(VD);
4415 BlockByCopyDecls.push_back(VD);
4416 }
4417 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4418 BlockByRefDeclsPtrSet.insert(VD);
4419 BlockByRefDecls.push_back(VD);
4420 }
4421 }
Steve Naroff54055232008-10-27 17:20:55 +00004422
Steve Naroff01aec112009-12-06 21:14:13 +00004423 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4424 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004425
Steve Naroff01aec112009-12-06 21:14:13 +00004426 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004427
Benjamin Kramerd999b372010-02-14 14:14:16 +00004428 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004429
Steve Naroff01aec112009-12-06 21:14:13 +00004430 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004431
Benjamin Kramerd999b372010-02-14 14:14:16 +00004432 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004433
4434 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004435 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004436 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004437 }
Steve Naroff01aec112009-12-06 21:14:13 +00004438 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4439 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004440 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Steve Naroff54055232008-10-27 17:20:55 +00004442 BlockDeclRefs.clear();
4443 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004444 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004445 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004446 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004447 ImportedBlockDecls.clear();
4448 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004449 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004450 // Must insert any 'const/volatile/static here. Since it has been
4451 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004452 std::string SC;
4453 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4454 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004455 if (GlobalVarDecl->getType().isConstQualified())
4456 SC += "const ";
4457 if (GlobalVarDecl->getType().isVolatileQualified())
4458 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004459 if (GlobalVarDecl->getType().isRestrictQualified())
4460 SC += "restrict ";
4461 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004462 }
4463
Steve Naroff54055232008-10-27 17:20:55 +00004464 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004465 InnerDeclRefsCount.clear();
4466 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004467 RewrittenBlockExprs.clear();
4468}
4469
4470void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4471 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004472 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Steve Naroff54055232008-10-27 17:20:55 +00004474 SynthesizeBlockLiterals(FunLocStart, FuncName);
4475}
4476
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004477static void BuildUniqueMethodName(std::string &Name,
4478 ObjCMethodDecl *MD) {
4479 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4480 Name = IFace->getNameAsCString();
4481 Name += "__" + MD->getSelector().getAsString();
4482 // Convert colons to underscores.
4483 std::string::size_type loc = 0;
4484 while ((loc = Name.find(":", loc)) != std::string::npos)
4485 Name.replace(loc, 1, "_");
4486}
4487
Steve Naroff54055232008-10-27 17:20:55 +00004488void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004489 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4490 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004491 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004492 std::string FuncName;
4493 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004494 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4495}
4496
4497void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4498 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4499 CI != E; ++CI)
4500 if (*CI) {
4501 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4502 GetBlockDeclRefExprs(CBE->getBody());
4503 else
4504 GetBlockDeclRefExprs(*CI);
4505 }
4506 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004507 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004508 // FIXME: Handle enums.
4509 if (!isa<FunctionDecl>(CDRE->getDecl()))
4510 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004511 }
4512 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4513 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4514 BlockDeclRefExpr *BDRE =
4515 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4516 DRE->getLocation(), false);
4517 BlockDeclRefs.push_back(BDRE);
4518 }
4519
Steve Naroff54055232008-10-27 17:20:55 +00004520 return;
4521}
4522
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004523void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4524 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004525 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004526 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4527 CI != E; ++CI)
4528 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004529 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4530 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004531 GetInnerBlockDeclRefExprs(CBE->getBody(),
4532 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004533 InnerContexts);
4534 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004535 else
4536 GetInnerBlockDeclRefExprs(*CI,
4537 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004538 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004539
4540 }
4541 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004542 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004543 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004544 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004545 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004546 }
4547 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4548 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4549 if (Var->isFunctionOrMethodVarDecl())
4550 ImportedLocalExternalDecls.insert(Var);
4551 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004552
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004553 return;
4554}
4555
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004556/// convertFunctionTypeOfBlocks - This routine converts a function type
4557/// whose result type may be a block pointer or whose argument type(s)
4558/// might be block pointers to an equivalent funtion type replacing
4559/// all block pointers to function pointers.
4560QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4561 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4562 // FTP will be null for closures that don't take arguments.
4563 // Generate a funky cast.
4564 llvm::SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004565 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004566 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004567
4568 if (FTP) {
4569 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4570 E = FTP->arg_type_end(); I && (I != E); ++I) {
4571 QualType t = *I;
4572 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004573 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004574 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004575 ArgTypes.push_back(t);
4576 }
4577 }
4578 QualType FuncType;
4579 // FIXME. Does this work if block takes no argument but has a return type
4580 // which is of block type?
4581 if (HasBlockType)
4582 FuncType = Context->getFunctionType(Res,
4583 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4584 false, false, 0, 0, FunctionType::ExtInfo());
4585 else FuncType = QualType(FT, 0);
4586 return FuncType;
4587}
4588
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004589Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004590 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004591 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004593 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004594 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004595 } else if (const BlockDeclRefExpr *CDRE =
4596 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004597 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004598 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004599 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004600 }
4601 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4602 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4603 }
4604 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4605 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4606 else if (const ConditionalOperator *CEXPR =
4607 dyn_cast<ConditionalOperator>(BlockExp)) {
4608 Expr *LHSExp = CEXPR->getLHS();
4609 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4610 Expr *RHSExp = CEXPR->getRHS();
4611 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4612 Expr *CONDExp = CEXPR->getCond();
4613 ConditionalOperator *CondExpr =
4614 new (Context) ConditionalOperator(CONDExp,
4615 SourceLocation(), cast<Expr>(LHSStmt),
4616 SourceLocation(), cast<Expr>(RHSStmt),
4617 Exp->getType());
4618 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004619 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4620 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004621 } else {
4622 assert(1 && "RewriteBlockClass: Bad type");
4623 }
4624 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004625 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004626 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004627 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004628 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004629
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004630 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004631 SourceLocation(),
4632 &Context->Idents.get("__block_impl"));
4633 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004634
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004635 // Generate a funky cast.
4636 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004637
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004638 // Push the block argument type.
4639 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004640 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004641 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004642 E = FTP->arg_type_end(); I && (I != E); ++I) {
4643 QualType t = *I;
4644 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004645 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004646 ArgTypes.push_back(t);
4647 }
Steve Naroff54055232008-10-27 17:20:55 +00004648 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004649 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004650 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004651 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4652 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004653 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004655 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004656
John McCall9d125032010-01-15 18:39:57 +00004657 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4658 CastExpr::CK_Unknown,
4659 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004660 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004661 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4662 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004663 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Douglas Gregor44b43212008-12-11 16:49:14 +00004665 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004666 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004667 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004668 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4669 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004670
John McCall9d125032010-01-15 18:39:57 +00004671 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4672 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004673 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004675 llvm::SmallVector<Expr*, 8> BlkExprs;
4676 // Add the implicit argument.
4677 BlkExprs.push_back(BlkCast);
4678 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004679 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004680 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004681 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004682 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004683 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4684 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004685 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004686 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004687}
4688
4689void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004690 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004692}
4693
Steve Naroff621edce2009-04-29 16:37:50 +00004694// We need to return the rewritten expression to handle cases where the
4695// BlockDeclRefExpr is embedded in another expression being rewritten.
4696// For example:
4697//
4698// int main() {
4699// __block Foo *f;
4700// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004701//
Steve Naroff621edce2009-04-29 16:37:50 +00004702// void (^myblock)() = ^() {
4703// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4704// i = 77;
4705// };
4706//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004707Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004708 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004709 // for each DeclRefExp where BYREFVAR is name of the variable.
4710 ValueDecl *VD;
4711 bool isArrow = true;
4712 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4713 VD = BDRE->getDecl();
4714 else {
4715 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4716 isArrow = false;
4717 }
4718
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004719 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4720 &Context->Idents.get("__forwarding"),
4721 Context->VoidPtrTy, 0,
4722 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004723 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4724 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004725 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004726
4727 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004728 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4729 &Context->Idents.get(Name),
4730 Context->VoidPtrTy, 0,
4731 /*BitWidth=*/0, /*Mutable=*/true);
4732 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004733 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004734
4735
4736
Steve Naroffdf8570d2009-02-02 17:19:26 +00004737 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004738 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4739 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004740 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004741 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004742}
4743
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004744// Rewrites the imported local variable V with external storage
4745// (static, extern, etc.) as *V
4746//
4747Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4748 ValueDecl *VD = DRE->getDecl();
4749 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4750 if (!ImportedLocalExternalDecls.count(Var))
4751 return DRE;
4752 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4753 DRE->getType(), DRE->getLocation());
4754 // Need parens to enforce precedence.
4755 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4756 Exp);
4757 ReplaceStmt(DRE, PE);
4758 return PE;
4759}
4760
Steve Naroffb2f9e512008-11-03 23:29:32 +00004761void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4762 SourceLocation LocStart = CE->getLParenLoc();
4763 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004764
4765 // Need to avoid trying to rewrite synthesized casts.
4766 if (LocStart.isInvalid())
4767 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004768 // Need to avoid trying to rewrite casts contained in macros.
4769 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4770 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004771
Steve Naroff54055232008-10-27 17:20:55 +00004772 const char *startBuf = SM->getCharacterData(LocStart);
4773 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004774 QualType QT = CE->getType();
4775 const Type* TypePtr = QT->getAs<Type>();
4776 if (isa<TypeOfExprType>(TypePtr)) {
4777 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4778 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4779 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004780 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004781 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004782 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004783 return;
4784 }
Steve Naroff54055232008-10-27 17:20:55 +00004785 // advance the location to startArgList.
4786 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004787
Steve Naroff54055232008-10-27 17:20:55 +00004788 while (*argPtr++ && (argPtr < endBuf)) {
4789 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004790 case '^':
4791 // Replace the '^' with '*'.
4792 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004793 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004794 break;
Steve Naroff54055232008-10-27 17:20:55 +00004795 }
4796 }
4797 return;
4798}
4799
4800void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4801 SourceLocation DeclLoc = FD->getLocation();
4802 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Steve Naroff54055232008-10-27 17:20:55 +00004804 // We have 1 or more arguments that have closure pointers.
4805 const char *startBuf = SM->getCharacterData(DeclLoc);
4806 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004807
Steve Naroff54055232008-10-27 17:20:55 +00004808 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Steve Naroff54055232008-10-27 17:20:55 +00004810 parenCount++;
4811 // advance the location to startArgList.
4812 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4813 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004814
Steve Naroff54055232008-10-27 17:20:55 +00004815 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004816
Steve Naroff54055232008-10-27 17:20:55 +00004817 while (*argPtr++ && parenCount) {
4818 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004819 case '^':
4820 // Replace the '^' with '*'.
4821 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004822 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004823 break;
4824 case '(':
4825 parenCount++;
4826 break;
4827 case ')':
4828 parenCount--;
4829 break;
Steve Naroff54055232008-10-27 17:20:55 +00004830 }
4831 }
4832 return;
4833}
4834
4835bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004836 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004837 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004838 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004839 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004840 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004841 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004842 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004843 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004844 }
4845 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004846 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004847 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004848 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004849 return true;
4850 }
4851 return false;
4852}
4853
Ted Kremenek8189cde2009-02-07 01:47:29 +00004854void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4855 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004856 const char *argPtr = strchr(Name, '(');
4857 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004858
Steve Naroff54055232008-10-27 17:20:55 +00004859 LParen = argPtr; // output the start.
4860 argPtr++; // skip past the left paren.
4861 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004862
Steve Naroff54055232008-10-27 17:20:55 +00004863 while (*argPtr && parenCount) {
4864 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004865 case '(': parenCount++; break;
4866 case ')': parenCount--; break;
4867 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004868 }
4869 if (parenCount) argPtr++;
4870 }
4871 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4872 RParen = argPtr; // output the end
4873}
4874
4875void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4876 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4877 RewriteBlockPointerFunctionArgs(FD);
4878 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004879 }
Steve Naroff54055232008-10-27 17:20:55 +00004880 // Handle Variables and Typedefs.
4881 SourceLocation DeclLoc = ND->getLocation();
4882 QualType DeclT;
4883 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4884 DeclT = VD->getType();
4885 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4886 DeclT = TDD->getUnderlyingType();
4887 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4888 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004889 else
Steve Naroff54055232008-10-27 17:20:55 +00004890 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Steve Naroff54055232008-10-27 17:20:55 +00004892 const char *startBuf = SM->getCharacterData(DeclLoc);
4893 const char *endBuf = startBuf;
4894 // scan backward (from the decl location) for the end of the previous decl.
4895 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4896 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004897
Steve Naroff54055232008-10-27 17:20:55 +00004898 // *startBuf != '^' if we are dealing with a pointer to function that
4899 // may take block argument types (which will be handled below).
4900 if (*startBuf == '^') {
4901 // Replace the '^' with '*', computing a negative offset.
4902 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004903 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004904 }
4905 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4906 // Replace the '^' with '*' for arguments.
4907 DeclLoc = ND->getLocation();
4908 startBuf = SM->getCharacterData(DeclLoc);
4909 const char *argListBegin, *argListEnd;
4910 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4911 while (argListBegin < argListEnd) {
4912 if (*argListBegin == '^') {
4913 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004914 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004915 }
4916 argListBegin++;
4917 }
4918 }
4919 return;
4920}
4921
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004922
4923/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4924/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4925/// struct Block_byref_id_object *src) {
4926/// _Block_object_assign (&_dest->object, _src->object,
4927/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4928/// [|BLOCK_FIELD_IS_WEAK]) // object
4929/// _Block_object_assign(&_dest->object, _src->object,
4930/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4931/// [|BLOCK_FIELD_IS_WEAK]) // block
4932/// }
4933/// And:
4934/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4935/// _Block_object_dispose(_src->object,
4936/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4937/// [|BLOCK_FIELD_IS_WEAK]) // object
4938/// _Block_object_dispose(_src->object,
4939/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4940/// [|BLOCK_FIELD_IS_WEAK]) // block
4941/// }
4942
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004943std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4944 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004945 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004946 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004947 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004948 CopyDestroyCache.insert(flag);
4949 S = "static void __Block_byref_id_object_copy_";
4950 S += utostr(flag);
4951 S += "(void *dst, void *src) {\n";
4952
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004953 // offset into the object pointer is computed as:
4954 // void * + void* + int + int + void* + void *
4955 unsigned IntSize =
4956 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4957 unsigned VoidPtrSize =
4958 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4959
4960 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4961 S += " _Block_object_assign((char*)dst + ";
4962 S += utostr(offset);
4963 S += ", *(void * *) ((char*)src + ";
4964 S += utostr(offset);
4965 S += "), ";
4966 S += utostr(flag);
4967 S += ");\n}\n";
4968
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004969 S += "static void __Block_byref_id_object_dispose_";
4970 S += utostr(flag);
4971 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004972 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4973 S += utostr(offset);
4974 S += "), ";
4975 S += utostr(flag);
4976 S += ");\n}\n";
4977 return S;
4978}
4979
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004980/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4981/// the declaration into:
4982/// struct __Block_byref_ND {
4983/// void *__isa; // NULL for everything except __weak pointers
4984/// struct __Block_byref_ND *__forwarding;
4985/// int32_t __flags;
4986/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004987/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4988/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004989/// typex ND;
4990/// };
4991///
4992/// It then replaces declaration of ND variable with:
4993/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4994/// __size=sizeof(struct __Block_byref_ND),
4995/// ND=initializer-if-any};
4996///
4997///
4998void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004999 // Insert declaration for the function in which block literal is
5000 // used.
5001 if (CurFunctionDeclToDeclareForBlock)
5002 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005003 int flag = 0;
5004 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005005 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005006 if (DeclLoc.isInvalid())
5007 // If type location is missing, it is because of missing type (a warning).
5008 // Use variable's location which is good for this case.
5009 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005010 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005011 SourceLocation X = ND->getLocEnd();
5012 X = SM->getInstantiationLoc(X);
5013 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005014 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005015 std::string ByrefType;
5016 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005017 ByrefType += " {\n";
5018 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005019 RewriteByRefString(ByrefType, Name, ND);
5020 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005021 ByrefType += " int __flags;\n";
5022 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005023 // Add void *__Block_byref_id_object_copy;
5024 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005025 QualType Ty = ND->getType();
5026 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5027 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005028 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5029 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005030 }
5031
5032 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005033 ByrefType += " " + Name + ";\n";
5034 ByrefType += "};\n";
5035 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005036 SourceLocation FunLocStart;
5037 if (CurFunctionDef)
5038 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5039 else {
5040 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5041 FunLocStart = CurMethodDef->getLocStart();
5042 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005043 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005044 if (Ty.isObjCGCWeak()) {
5045 flag |= BLOCK_FIELD_IS_WEAK;
5046 isa = 1;
5047 }
5048
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005049 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005050 flag = BLOCK_BYREF_CALLER;
5051 QualType Ty = ND->getType();
5052 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5053 if (Ty->isBlockPointerType())
5054 flag |= BLOCK_FIELD_IS_BLOCK;
5055 else
5056 flag |= BLOCK_FIELD_IS_OBJECT;
5057 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005058 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005059 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005060 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005061
5062 // struct __Block_byref_ND ND =
5063 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5064 // initializer-if-any};
5065 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005066 unsigned flags = 0;
5067 if (HasCopyAndDispose)
5068 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005069 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005070 ByrefType.clear();
5071 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005072 std::string ForwardingCastType("(");
5073 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005074 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005075 ByrefType += " " + Name + " = {(void*)";
5076 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005077 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005078 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005079 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005080 ByrefType += "sizeof(";
5081 RewriteByRefString(ByrefType, Name, ND);
5082 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005083 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005084 ByrefType += ", __Block_byref_id_object_copy_";
5085 ByrefType += utostr(flag);
5086 ByrefType += ", __Block_byref_id_object_dispose_";
5087 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005088 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005089 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00005090 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005091 }
5092 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005093 SourceLocation startLoc;
5094 Expr *E = ND->getInit();
5095 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5096 startLoc = ECE->getLParenLoc();
5097 else
5098 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005099 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005100 endBuf = SM->getCharacterData(startLoc);
5101
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005102 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005103 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005104 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005105 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005106 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005107 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005108 ByrefType += "sizeof(";
5109 RewriteByRefString(ByrefType, Name, ND);
5110 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005111 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005112 ByrefType += "__Block_byref_id_object_copy_";
5113 ByrefType += utostr(flag);
5114 ByrefType += ", __Block_byref_id_object_dispose_";
5115 ByrefType += utostr(flag);
5116 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005117 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005118 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005119
5120 // Complete the newly synthesized compound expression by inserting a right
5121 // curly brace before the end of the declaration.
5122 // FIXME: This approach avoids rewriting the initializer expression. It
5123 // also assumes there is only one declarator. For example, the following
5124 // isn't currently supported by this routine (in general):
5125 //
5126 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5127 //
5128 const char *startBuf = SM->getCharacterData(startLoc);
5129 const char *semiBuf = strchr(startBuf, ';');
5130 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5131 SourceLocation semiLoc =
5132 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5133
Benjamin Kramerd999b372010-02-14 14:14:16 +00005134 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005135 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005136 return;
5137}
5138
Mike Stump1eb44332009-09-09 15:08:12 +00005139void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005140 // Add initializers for any closure decl refs.
5141 GetBlockDeclRefExprs(Exp->getBody());
5142 if (BlockDeclRefs.size()) {
5143 // Unique all "by copy" declarations.
5144 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005145 if (!BlockDeclRefs[i]->isByRef()) {
5146 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5147 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5148 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5149 }
5150 }
Steve Naroff54055232008-10-27 17:20:55 +00005151 // Unique all "by ref" declarations.
5152 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5153 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005154 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5155 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5156 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5157 }
Steve Naroff54055232008-10-27 17:20:55 +00005158 }
5159 // Find any imported blocks...they will need special attention.
5160 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005161 if (BlockDeclRefs[i]->isByRef() ||
5162 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005163 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005164 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005165 }
5166}
5167
Steve Narofffa15fd92008-10-28 20:29:00 +00005168FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5169 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005170 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005171 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00005172 ID, FType, 0, FunctionDecl::Extern,
5173 FunctionDecl::None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005174}
5175
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005176Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5177 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005178 Blocks.push_back(Exp);
5179
5180 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005181
5182 // Add inner imported variables now used in current block.
5183 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005184 if (!InnerBlockDeclRefs.empty()) {
5185 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5186 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5187 ValueDecl *VD = Exp->getDecl();
5188 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005189 // We need to save the copied-in variables in nested
5190 // blocks because it is needed at the end for some of the API generations.
5191 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005192 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5193 BlockDeclRefs.push_back(Exp);
5194 BlockByCopyDeclsPtrSet.insert(VD);
5195 BlockByCopyDecls.push_back(VD);
5196 }
5197 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5198 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5199 BlockDeclRefs.push_back(Exp);
5200 BlockByRefDeclsPtrSet.insert(VD);
5201 BlockByRefDecls.push_back(VD);
5202 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005203 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005204 // Find any imported blocks...they will need special attention.
5205 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5206 if (InnerBlockDeclRefs[i]->isByRef() ||
5207 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5208 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5209 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005210 }
5211 InnerDeclRefsCount.push_back(countOfInnerDecls);
5212
Steve Narofffa15fd92008-10-28 20:29:00 +00005213 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005214
Steve Narofffa15fd92008-10-28 20:29:00 +00005215 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005216 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005217 else if (CurMethodDef)
5218 BuildUniqueMethodName(FuncName, CurMethodDef);
5219 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005220 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005221
Steve Narofffa15fd92008-10-28 20:29:00 +00005222 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005223
Steve Narofffa15fd92008-10-28 20:29:00 +00005224 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5225 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005226
Steve Narofffa15fd92008-10-28 20:29:00 +00005227 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005228 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5229 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005230
5231 FunctionDecl *FD;
5232 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005233
Steve Narofffa15fd92008-10-28 20:29:00 +00005234 // Simulate a contructor call...
5235 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005236 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005237
Steve Narofffa15fd92008-10-28 20:29:00 +00005238 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Steve Narofffdc03722008-10-29 21:23:59 +00005240 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005241 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005242 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5243 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005244 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5245 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005246 InitExprs.push_back(castExpr);
5247
Steve Naroff01aec112009-12-06 21:14:13 +00005248 // Initialize the block descriptor.
5249 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005250
Steve Naroff01aec112009-12-06 21:14:13 +00005251 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5252 &Context->Idents.get(DescData.c_str()),
5253 Context->VoidPtrTy, 0,
Douglas Gregor16573fa2010-04-19 22:54:31 +00005254 VarDecl::Static, VarDecl::None);
Steve Naroff01aec112009-12-06 21:14:13 +00005255 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5256 new (Context) DeclRefExpr(NewVD,
5257 Context->VoidPtrTy, SourceLocation()),
5258 UnaryOperator::AddrOf,
5259 Context->getPointerType(Context->VoidPtrTy),
5260 SourceLocation());
5261 InitExprs.push_back(DescRefExpr);
5262
Steve Narofffa15fd92008-10-28 20:29:00 +00005263 // Add initializers for any closure decl refs.
5264 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005265 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005266 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005267 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005269 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005270 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005271 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005272 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005273 if (HasLocalVariableExternalStorage(*I)) {
5274 QualType QT = (*I)->getType();
5275 QT = Context->getPointerType(QT);
5276 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5277 SourceLocation());
5278 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005279 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005280 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005281 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005282 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5283 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005284 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005285 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005286 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005287 if (HasLocalVariableExternalStorage(*I)) {
5288 QualType QT = (*I)->getType();
5289 QT = Context->getPointerType(QT);
5290 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5291 SourceLocation());
5292 }
5293
Steve Narofffa15fd92008-10-28 20:29:00 +00005294 }
Mike Stump1eb44332009-09-09 15:08:12 +00005295 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005296 }
5297 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005298 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005299 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005300 ValueDecl *ND = (*I);
5301 std::string Name(ND->getNameAsString());
5302 std::string RecName;
5303 RewriteByRefString(RecName, Name, ND);
5304 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5305 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005306 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005307 SourceLocation(), II);
5308 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5309 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5310
Chris Lattner8ec03f52008-11-24 03:54:41 +00005311 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005312 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5313 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005314 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005315 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005316 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005317 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005318 }
5319 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005320 if (ImportedBlockDecls.size()) {
5321 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5322 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005323 unsigned IntSize =
5324 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005325 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5326 Context->IntTy, SourceLocation());
5327 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005328 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005329 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5330 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005331 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005332 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005333 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005334 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5335 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005336 BlockDeclRefs.clear();
5337 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005338 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005339 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005340 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005341 ImportedBlockDecls.clear();
5342 return NewRep;
5343}
5344
5345//===----------------------------------------------------------------------===//
5346// Function Body / Expression rewriting
5347//===----------------------------------------------------------------------===//
5348
Steve Naroffc77a6362008-12-04 16:24:46 +00005349// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5350// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5351// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5352// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5353// Since the rewriter isn't capable of rewriting rewritten code, it's important
5354// we get this right.
5355void RewriteObjC::CollectPropertySetters(Stmt *S) {
5356 // Perform a bottom up traversal of all children.
5357 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5358 CI != E; ++CI)
5359 if (*CI)
5360 CollectPropertySetters(*CI);
5361
5362 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5363 if (BinOp->isAssignmentOp()) {
5364 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5365 PropSetters[PRE] = BinOp;
5366 }
5367 }
5368}
5369
Steve Narofffa15fd92008-10-28 20:29:00 +00005370Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005371 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005372 isa<DoStmt>(S) || isa<ForStmt>(S))
5373 Stmts.push_back(S);
5374 else if (isa<ObjCForCollectionStmt>(S)) {
5375 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005376 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005377 }
Mike Stump1eb44332009-09-09 15:08:12 +00005378
Steve Narofffa15fd92008-10-28 20:29:00 +00005379 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005380
Steve Narofffa15fd92008-10-28 20:29:00 +00005381 // Perform a bottom up rewrite of all children.
5382 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5383 CI != E; ++CI)
5384 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005385 Stmt *newStmt;
5386 Stmt *S = (*CI);
5387 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5388 Expr *OldBase = IvarRefExpr->getBase();
5389 bool replaced = false;
5390 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5391 if (replaced) {
5392 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5393 ReplaceStmt(OldBase, IRE->getBase());
5394 else
5395 ReplaceStmt(S, newStmt);
5396 }
5397 }
5398 else
5399 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005400 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 *CI = newStmt;
5402 }
Mike Stump1eb44332009-09-09 15:08:12 +00005403
Steve Narofffa15fd92008-10-28 20:29:00 +00005404 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005405 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005406 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5407 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005408 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005409 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005410 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 // Rewrite the block body in place.
5412 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005413 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005415 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005416 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005417
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005418 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5419
Steve Narofffa15fd92008-10-28 20:29:00 +00005420 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005421 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005422 return blockTranscribed;
5423 }
5424 // Handle specific things.
5425 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5426 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005427
Steve Naroffc77a6362008-12-04 16:24:46 +00005428 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5429 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5430 if (BinOp) {
5431 // Because the rewriter doesn't allow us to rewrite rewritten code,
5432 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005433 DisableReplaceStmt = true;
5434 // Save the source range. Even if we disable the replacement, the
5435 // rewritten node will have been inserted into the tree. If the synthesized
5436 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005437 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005438 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5439 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005440 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005441 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005442 //
5443 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5444 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5445 // to see the original expression). Consider this example:
5446 //
5447 // Foo *obj1, *obj2;
5448 //
5449 // obj1.i = [obj2 rrrr];
5450 //
5451 // 'BinOp' for the previous expression looks like:
5452 //
5453 // (BinaryOperator 0x231ccf0 'int' '='
5454 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5455 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5456 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5457 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5458 //
5459 // 'newStmt' represents the rewritten message expression. For example:
5460 //
5461 // (CallExpr 0x231d300 'id':'struct objc_object *'
5462 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5463 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5464 // (CStyleCastExpr 0x231d220 'void *'
5465 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5466 //
5467 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5468 // can be used as the setter argument. ReplaceStmt() will still 'see'
5469 // the original RHS (since we haven't altered BinOp).
5470 //
Mike Stump1eb44332009-09-09 15:08:12 +00005471 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005472 // node. As a result, we now leak the original AST nodes.
5473 //
Steve Naroffb619d952008-12-09 12:56:34 +00005474 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005475 } else {
5476 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005477 }
5478 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005479 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5480 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005481
Steve Narofffa15fd92008-10-28 20:29:00 +00005482 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5483 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005484
Steve Narofffa15fd92008-10-28 20:29:00 +00005485 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005486#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005487 // Before we rewrite it, put the original message expression in a comment.
5488 SourceLocation startLoc = MessExpr->getLocStart();
5489 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005490
Steve Narofffa15fd92008-10-28 20:29:00 +00005491 const char *startBuf = SM->getCharacterData(startLoc);
5492 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005493
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 std::string messString;
5495 messString += "// ";
5496 messString.append(startBuf, endBuf-startBuf+1);
5497 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005498
5499 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005500 // InsertText(clang::SourceLocation, char const*, unsigned int).
5501 // InsertText(startLoc, messString.c_str(), messString.size());
5502 // Tried this, but it didn't work either...
5503 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005504#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005505 return RewriteMessageExpr(MessExpr);
5506 }
Mike Stump1eb44332009-09-09 15:08:12 +00005507
Steve Narofffa15fd92008-10-28 20:29:00 +00005508 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5509 return RewriteObjCTryStmt(StmtTry);
5510
5511 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5512 return RewriteObjCSynchronizedStmt(StmtTry);
5513
5514 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5515 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005516
Steve Narofffa15fd92008-10-28 20:29:00 +00005517 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5518 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005519
5520 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005521 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005522 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005523 OrigStmtRange.getEnd());
5524 if (BreakStmt *StmtBreakStmt =
5525 dyn_cast<BreakStmt>(S))
5526 return RewriteBreakStmt(StmtBreakStmt);
5527 if (ContinueStmt *StmtContinueStmt =
5528 dyn_cast<ContinueStmt>(S))
5529 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005530
5531 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005532 // and cast exprs.
5533 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5534 // FIXME: What we're doing here is modifying the type-specifier that
5535 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005536 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005537 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5538 // the context of an ObjCForCollectionStmt. For example:
5539 // NSArray *someArray;
5540 // for (id <FooProtocol> index in someArray) ;
5541 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5542 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005543 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005544 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005545
Steve Narofffa15fd92008-10-28 20:29:00 +00005546 // Blocks rewrite rules.
5547 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5548 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005549 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005550 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005551 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005552 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005553 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005554 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005555 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005556 if (VD->hasAttr<BlocksAttr>()) {
5557 static unsigned uniqueByrefDeclCount = 0;
5558 assert(!BlockByRefDeclNo.count(ND) &&
5559 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5560 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005561 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005562 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005563 else
5564 RewriteTypeOfDecl(VD);
5565 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005566 }
5567 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005568 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005569 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005570 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005571 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5572 }
5573 }
5574 }
Mike Stump1eb44332009-09-09 15:08:12 +00005575
Steve Narofffa15fd92008-10-28 20:29:00 +00005576 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5577 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005578
5579 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005580 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5581 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005582 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5583 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005584 && "Statement stack mismatch");
5585 Stmts.pop_back();
5586 }
5587 // Handle blocks rewriting.
5588 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5589 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005590 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005591 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005592 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5593 ValueDecl *VD = DRE->getDecl();
5594 if (VD->hasAttr<BlocksAttr>())
5595 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005596 if (HasLocalVariableExternalStorage(VD))
5597 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005598 }
5599
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005601 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005602 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005603 ReplaceStmt(S, BlockCall);
5604 return BlockCall;
5605 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005607 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005608 RewriteCastExpr(CE);
5609 }
5610#if 0
5611 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005612 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5613 ICE->getSubExpr(),
5614 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005615 // Get the new text.
5616 std::string SStr;
5617 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005618 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005619 const std::string &Str = Buf.str();
5620
5621 printf("CAST = %s\n", &Str[0]);
5622 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5623 delete S;
5624 return Replacement;
5625 }
5626#endif
5627 // Return this stmt unmodified.
5628 return S;
5629}
5630
Steve Naroff3d7e7862009-12-05 15:55:59 +00005631void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5632 for (RecordDecl::field_iterator i = RD->field_begin(),
5633 e = RD->field_end(); i != e; ++i) {
5634 FieldDecl *FD = *i;
5635 if (isTopLevelBlockPointerType(FD->getType()))
5636 RewriteBlockPointerDecl(FD);
5637 if (FD->getType()->isObjCQualifiedIdType() ||
5638 FD->getType()->isObjCQualifiedInterfaceType())
5639 RewriteObjCQualifiedInterfaceTypes(FD);
5640 }
5641}
5642
Steve Narofffa15fd92008-10-28 20:29:00 +00005643/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5644/// main file of the input.
5645void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5646 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005647 if (FD->isOverloadedOperator())
5648 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 // Since function prototypes don't have ParmDecl's, we check the function
5651 // prototype. This enables us to rewrite function declarations and
5652 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005653 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005654
Sebastian Redld3a413d2009-04-26 20:35:05 +00005655 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005656 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005657 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005658 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005659 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005660 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005661 Body =
5662 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5663 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005664 CurrentBody = 0;
5665 if (PropParentMap) {
5666 delete PropParentMap;
5667 PropParentMap = 0;
5668 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005669 // This synthesizes and inserts the block "impl" struct, invoke function,
5670 // and any copy/dispose helper functions.
5671 InsertBlockLiteralsWithinFunction(FD);
5672 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005673 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005674 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005675 return;
5676 }
5677 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005678 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005679 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005680 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005681 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005682 Body =
5683 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5684 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005685 CurrentBody = 0;
5686 if (PropParentMap) {
5687 delete PropParentMap;
5688 PropParentMap = 0;
5689 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005690 InsertBlockLiteralsWithinMethod(MD);
5691 CurMethodDef = 0;
5692 }
5693 }
5694 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5695 ClassImplementation.push_back(CI);
5696 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5697 CategoryImplementation.push_back(CI);
5698 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5699 RewriteForwardClassDecl(CD);
5700 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5701 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005702 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005703 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005704 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005705 CheckFunctionPointerDecl(VD->getType(), VD);
5706 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005707 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005708 RewriteCastExpr(CE);
5709 }
5710 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005711 } else if (VD->getType()->isRecordType()) {
5712 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5713 if (RD->isDefinition())
5714 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005715 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005716 if (VD->getInit()) {
5717 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005718 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005719 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005720 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005721 CurrentBody = 0;
5722 if (PropParentMap) {
5723 delete PropParentMap;
5724 PropParentMap = 0;
5725 }
Mike Stump1eb44332009-09-09 15:08:12 +00005726 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005727 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005728 GlobalVarDecl = 0;
5729
5730 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005731 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005732 RewriteCastExpr(CE);
5733 }
5734 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005735 return;
5736 }
5737 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005738 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005739 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005740 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5742 return;
5743 }
5744 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005745 if (RD->isDefinition())
5746 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005747 return;
5748 }
5749 // Nothing yet.
5750}
5751
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005752void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 if (Diags.hasErrorOccurred())
5754 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Steve Naroff621edce2009-04-29 16:37:50 +00005758 // Here's a great place to add any extra declarations that may be needed.
5759 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005760 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005761 E = ProtocolExprDecls.end(); I != E; ++I)
5762 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5763
Benjamin Kramerd999b372010-02-14 14:14:16 +00005764 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005765 if (ClassImplementation.size() || CategoryImplementation.size())
5766 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005767
Steve Narofffa15fd92008-10-28 20:29:00 +00005768 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5769 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005770 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005771 Rewrite.getRewriteBufferFor(MainFileID)) {
5772 //printf("Changed:\n");
5773 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5774 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005775 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005776 }
Steve Narofface66252008-11-13 20:07:04 +00005777
Steve Naroff621edce2009-04-29 16:37:50 +00005778 if (ClassImplementation.size() || CategoryImplementation.size() ||
5779 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005780 // Rewrite Objective-c meta data*
5781 std::string ResultStr;
5782 SynthesizeMetaDataIntoBuffer(ResultStr);
5783 // Emit metadata.
5784 *OutFile << ResultStr;
5785 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005786 OutFile->flush();
5787}