blob: ba518069eb85802a1b53f14c9685491c6f0b37c9 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 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;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 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;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 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.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +0000158 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
165 if (isa<ObjCClassDecl>((*I))) {
166 RewriteForwardClassDecl(D);
167 break;
168 }
Chris Lattner682bf922009-03-29 16:50:03 +0000169 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000170 }
Chris Lattner682bf922009-03-29 16:50:03 +0000171 }
172 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000173 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000174 RewriteObjC(std::string inFile, raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000175 Diagnostic &D, const LangOptions &LOpts,
176 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000177
178 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000180 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000182 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 if (ReplacingStmt)
186 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000187
Steve Naroffb619d952008-12-09 12:56:34 +0000188 if (DisableReplaceStmt)
189 return; // Used when rewriting the assignment of a property setter.
190
Steve Naroff4c3580e2008-12-04 23:50:32 +0000191 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000192 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 ReplacedNodes[Old] = New;
194 return;
195 }
196 if (SilenceRewriteMacroWarning)
197 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000198 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
199 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000200 }
Steve Naroffb619d952008-12-09 12:56:34 +0000201
202 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000203 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000204 int Size = Rewrite.getRangeSize(SrcRange);
205 if (Size == -1) {
206 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
207 << Old->getSourceRange();
208 return;
209 }
210 // Get the new text.
211 std::string SStr;
212 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000213 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000214 const std::string &Str = S.str();
215
216 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000217 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000218 ReplacedNodes[Old] = New;
219 return;
220 }
221 if (SilenceRewriteMacroWarning)
222 return;
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 }
226
Chris Lattner5f9e2722011-07-23 10:55:15 +0000227 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000228 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000230 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000231 SilenceRewriteMacroWarning)
232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnerf04da132007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000248 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000249 void RewriteForwardClassDecl(DeclGroupRef D);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000255 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
256 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000257 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
258 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000259 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000260 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000261 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
262 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
263 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
264 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000265 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000266 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000267 void RewriteBlockPointerType(std::string& Str, QualType Type);
268 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000269 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000270 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000271 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000272 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000273 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000274 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000275 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000276 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000277 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattnerf04da132007-10-24 17:06:59 +0000279 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000280 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000281 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Steve Naroff8599e7a2008-12-08 16:43:47 +0000283 Stmt *CurrentBody;
284 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000285
Chris Lattnere64b7772007-10-24 16:57:36 +0000286 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000287 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
288 bool &replaced);
289 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000290 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
291 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000292 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000293 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000294 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000295 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000296 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000297 void WarnAboutReturnGotoStmts(Stmt *S);
298 void HasReturnStmts(Stmt *S, bool &hasReturns);
299 void RewriteTryReturnStmts(Stmt *S);
300 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000301 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000302 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000303 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000304 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
305 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000306 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000307 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000308 Expr **args, unsigned nargs,
309 SourceLocation StartLoc=SourceLocation(),
310 SourceLocation EndLoc=SourceLocation());
311 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000314 Stmt *RewriteBreakStmt(BreakStmt *S);
315 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000316 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Steve Naroff09b266e2007-10-30 23:14:51 +0000318 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000319 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000320 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000321 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000322 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000323 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000324 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000325 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000326 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000327 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Chris Lattnerf04da132007-10-24 17:06:59 +0000329 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000330 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000331 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000333 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Douglas Gregor653f1b12009-04-23 01:02:12 +0000336 template<typename MethodIterator>
337 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
338 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000339 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000340 StringRef prefix,
341 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000342 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Steve Naroff621edce2009-04-29 16:37:50 +0000344 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000345 StringRef prefix,
346 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000347 std::string &Result);
348 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 StringRef prefix,
350 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000351 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000352 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000353 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000354 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000355 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000356 void RewriteImplementations();
357 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Steve Naroff54055232008-10-27 17:20:55 +0000359 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000360 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000361 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
364 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000365
366 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000367 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000368 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000369 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000370 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000371 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000372 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000373
374 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000375 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000378 std::string SynthesizeBlockImpl(BlockExpr *CE,
379 std::string Tag, std::string Desc);
380 std::string SynthesizeBlockDescriptor(std::string DescTag,
381 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000383 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000384 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000385 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000387 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Steve Naroff54055232008-10-27 17:20:55 +0000389 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000390 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000391 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000392 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000393 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 // We avoid calling Type::isBlockPointerType(), since it operates on the
396 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000397 bool isTopLevelBlockPointerType(QualType T) {
398 return isa<BlockPointerType>(T);
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000401 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
402 /// to a function pointer type and upon success, returns true; false
403 /// otherwise.
404 bool convertBlockPointerToFunctionPointer(QualType &T) {
405 if (isTopLevelBlockPointerType(T)) {
406 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
407 T = Context->getPointerType(BPT->getPointeeType());
408 return true;
409 }
410 return false;
411 }
412
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000413 void convertToUnqualifiedObjCType(QualType &T) {
414 if (T->isObjCQualifiedIdType())
415 T = Context->getObjCIdType();
416 else if (T->isObjCQualifiedClassType())
417 T = Context->getObjCClassType();
418 else if (T->isObjCObjectPointerType() &&
419 T->getPointeeType()->isObjCQualifiedInterfaceType())
420 T = Context->getObjCIdType();
421 }
422
Steve Naroff54055232008-10-27 17:20:55 +0000423 // FIXME: This predicate seems like it would be useful to add to ASTContext.
424 bool isObjCType(QualType T) {
425 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
426 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Steve Naroff54055232008-10-27 17:20:55 +0000428 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Steve Naroff54055232008-10-27 17:20:55 +0000430 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
431 OCT == Context->getCanonicalType(Context->getObjCClassType()))
432 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Ted Kremenek6217b802009-07-29 21:53:49 +0000434 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000435 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000436 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000437 return true;
438 }
439 return false;
440 }
441 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000442 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000443 void GetExtentOfArgList(const char *Name, const char *&LParen,
444 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000445 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner5f9e2722011-07-23 10:55:15 +0000447 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000448 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000449 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Steve Naroff621edce2009-04-29 16:37:50 +0000451 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000453 if (From[i] == '"')
454 To += "\\\"";
455 else
456 To += From[i];
457 }
458 }
John McCalle23cf432010-12-14 08:05:40 +0000459
460 QualType getSimpleFunctionType(QualType result,
461 const QualType *args,
462 unsigned numArgs,
463 bool variadic = false) {
464 FunctionProtoType::ExtProtoInfo fpi;
465 fpi.Variadic = variadic;
466 return Context->getFunctionType(result, args, numArgs, fpi);
467 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000468 };
John McCall9d125032010-01-15 18:39:57 +0000469
470 // Helper function: create a CStyleCastExpr with trivial type source info.
471 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000472 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000473 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000474 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000475 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000476 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000477}
478
Mike Stump1eb44332009-09-09 15:08:12 +0000479void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
480 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000481 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000482 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000484 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000485 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000486 // All the args are checked/rewritten. Don't call twice!
487 RewriteBlockPointerDecl(D);
488 break;
489 }
490 }
491}
492
493void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000494 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000495 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000496 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000497}
498
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000499static bool IsHeaderFile(const std::string &Filename) {
500 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000502 if (DotPos == std::string::npos) {
503 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000504 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000507 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
508 // C header: .h
509 // C++ header: .hh or .H;
510 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000511}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000512
Chris Lattner5f9e2722011-07-23 10:55:15 +0000513RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000514 Diagnostic &D, const LangOptions &LOpts,
515 bool silenceMacroWarn)
516 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
517 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000518 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000519 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000520 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000521 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000522 "rewriter doesn't support user-specified control flow semantics "
523 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000524}
525
Eli Friedmanbce831b2009-05-18 22:29:17 +0000526ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000527 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000528 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000529 const LangOptions &LOpts,
530 bool SilenceRewriteMacroWarning) {
531 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000532}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000533
Steve Naroffb29b4272008-04-14 22:03:09 +0000534void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000535 Context = &context;
536 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000537 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000538 MsgSendFunctionDecl = 0;
539 MsgSendSuperFunctionDecl = 0;
540 MsgSendStretFunctionDecl = 0;
541 MsgSendSuperStretFunctionDecl = 0;
542 MsgSendFpretFunctionDecl = 0;
543 GetClassFunctionDecl = 0;
544 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000545 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000546 SelGetUidFunctionDecl = 0;
547 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548 ConstantStringClassReference = 0;
549 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000550 CurMethodDef = 0;
551 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000552 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000553 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000554 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000555 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000556 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000558 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000559 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000560 PropParentMap = 0;
561 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000562 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000563 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000565 // Get the ID and start/end of the main file.
566 MainFileID = SM->getMainFileID();
567 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
568 MainFileStart = MainBuf->getBufferStart();
569 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattner2c78b872009-04-14 23:22:57 +0000571 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000573 // declaring objc_selector outside the parameter list removes a silly
574 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000576 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000578 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000580 if (LangOpts.Microsoft) {
581 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000582 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
583 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000584 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000585 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000586 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000587 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
588 Preamble += "typedef struct objc_object Protocol;\n";
589 Preamble += "#define _REWRITER_typedef_Protocol\n";
590 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 if (LangOpts.Microsoft) {
592 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
593 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
594 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000595 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000596 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000598 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000608 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
609 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000611 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
613 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
615 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
616 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000617 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000618 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
620 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
621 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000622 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
623 Preamble += "struct __objcFastEnumerationState {\n\t";
624 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000625 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "unsigned long *mutationsPtr;\n\t";
627 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000628 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000629 Preamble += "#define __FASTENUMERATIONSTATE\n";
630 Preamble += "#endif\n";
631 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
632 Preamble += "struct __NSConstantStringImpl {\n";
633 Preamble += " int *isa;\n";
634 Preamble += " int flags;\n";
635 Preamble += " char *str;\n";
636 Preamble += " long length;\n";
637 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000638 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
639 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
640 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000642 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000643 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
644 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000645 // Blocks preamble.
646 Preamble += "#ifndef BLOCK_IMPL\n";
647 Preamble += "#define BLOCK_IMPL\n";
648 Preamble += "struct __block_impl {\n";
649 Preamble += " void *isa;\n";
650 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000651 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000652 Preamble += " void *FuncPtr;\n";
653 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000654 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000655 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000656 Preamble += "extern \"C\" __declspec(dllexport) "
657 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000658 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
659 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
660 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
661 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000662 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
663 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000664 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
665 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
666 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000667 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000668 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000669 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
670 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000671 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000672 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000673 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000674 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000675 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000676 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000677 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000678 Preamble += "#define __weak\n";
679 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000680 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
681 // as this avoids warning in any 64bit/32bit compilation model.
682 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000683}
684
685
Chris Lattnerf04da132007-10-24 17:06:59 +0000686//===----------------------------------------------------------------------===//
687// Top Level Driver Code
688//===----------------------------------------------------------------------===//
689
Chris Lattner682bf922009-03-29 16:50:03 +0000690void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000691 if (Diags.hasErrorOccurred())
692 return;
693
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000694 // Two cases: either the decl could be in the main file, or it could be in a
695 // #included file. If the former, rewrite it now. If the later, check to see
696 // if we rewrote the #include/#import.
697 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000698 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000700 // If this is for a builtin, ignore it.
701 if (Loc.isInvalid()) return;
702
Steve Naroffebf2b562007-10-23 23:50:29 +0000703 // Look for built-in declarations that we need to refer during the rewrite.
704 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000705 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000706 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000707 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000708 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000709 ConstantStringClassReference = FVD;
710 return;
711 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000712 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000713 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000714 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000715 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000717 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000718 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000719 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000720 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000721 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
722 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000723 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
724 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000725 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000726 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000727 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000728 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000729 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000730 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000731}
732
Chris Lattnerf04da132007-10-24 17:06:59 +0000733//===----------------------------------------------------------------------===//
734// Syntactic (non-AST) Rewriting Code
735//===----------------------------------------------------------------------===//
736
Steve Naroffb29b4272008-04-14 22:03:09 +0000737void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000738 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000739 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000740 const char *MainBufStart = MainBuf.begin();
741 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000742 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000744 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000745 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
746 if (*BufPtr == '#') {
747 if (++BufPtr == MainBufEnd)
748 return;
749 while (*BufPtr == ' ' || *BufPtr == '\t')
750 if (++BufPtr == MainBufEnd)
751 return;
752 if (!strncmp(BufPtr, "import", ImportLen)) {
753 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000754 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000755 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000756 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000757 BufPtr += ImportLen;
758 }
759 }
760 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000761}
762
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000763static std::string getIvarAccessString(ObjCIvarDecl *OID) {
764 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 std::string S;
766 S = "((struct ";
767 S += ClassDecl->getIdentifier()->getName();
768 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000769 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000770 return S;
771}
772
Steve Naroffa0876e82008-12-02 17:36:43 +0000773void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
774 ObjCImplementationDecl *IMD,
775 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000776 static bool objcGetPropertyDefined = false;
777 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000778 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000779 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 const char *startBuf = SM->getCharacterData(startLoc);
781 assert((*startBuf == '@') && "bogus @synthesize location");
782 const char *semiBuf = strchr(startBuf, ';');
783 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000784 SourceLocation onePastSemiLoc =
785 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786
787 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
788 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Steve Naroffeb0646c2008-12-02 15:48:25 +0000790 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000791 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000794 if (!OID)
795 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000796 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000797 if (!PD->getGetterMethodDecl()->isDefined()) {
798 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
799 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
800 ObjCPropertyDecl::OBJC_PR_copy));
801 std::string Getr;
802 if (GenGetProperty && !objcGetPropertyDefined) {
803 objcGetPropertyDefined = true;
804 // FIXME. Is this attribute correct in all cases?
805 Getr = "\nextern \"C\" __declspec(dllimport) "
806 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000807 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000808 RewriteObjCMethodDecl(OID->getContainingInterface(),
809 PD->getGetterMethodDecl(), Getr);
810 Getr += "{ ";
811 // Synthesize an explicit cast to gain access to the ivar.
812 // See objc-act.c:objc_synthesize_new_getter() for details.
813 if (GenGetProperty) {
814 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
815 Getr += "typedef ";
816 const FunctionType *FPRetType = 0;
817 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
818 FPRetType);
819 Getr += " _TYPE";
820 if (FPRetType) {
821 Getr += ")"; // close the precedence "scope" for "*".
822
823 // Now, emit the argument types (if any).
824 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
825 Getr += "(";
826 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
827 if (i) Getr += ", ";
828 std::string ParamStr = FT->getArgType(i).getAsString(
829 Context->PrintingPolicy);
830 Getr += ParamStr;
831 }
832 if (FT->isVariadic()) {
833 if (FT->getNumArgs()) Getr += ", ";
834 Getr += "...";
835 }
836 Getr += ")";
837 } else
838 Getr += "()";
839 }
840 Getr += ";\n";
841 Getr += "return (_TYPE)";
842 Getr += "objc_getProperty(self, _cmd, ";
843 SynthesizeIvarOffsetComputation(OID, Getr);
844 Getr += ", 1)";
845 }
846 else
847 Getr += "return " + getIvarAccessString(OID);
848 Getr += "; }";
849 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000850 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000851
852 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000853 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000854
Steve Naroffeb0646c2008-12-02 15:48:25 +0000855 // Generate the 'setter' function.
856 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000857 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
858 ObjCPropertyDecl::OBJC_PR_copy);
859 if (GenSetProperty && !objcSetPropertyDefined) {
860 objcSetPropertyDefined = true;
861 // FIXME. Is this attribute correct in all cases?
862 Setr = "\nextern \"C\" __declspec(dllimport) "
863 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
864 }
865
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000866 RewriteObjCMethodDecl(OID->getContainingInterface(),
867 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000868 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000869 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000870 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 if (GenSetProperty) {
872 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000873 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000874 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000875 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000876 Setr += ", ";
877 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
878 Setr += "0, ";
879 else
880 Setr += "1, ";
881 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
882 Setr += "1)";
883 else
884 Setr += "0)";
885 }
886 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000887 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000888 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000889 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000890 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000891 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000892}
Chris Lattner8a12c272007-10-11 18:38:32 +0000893
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000894void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
895 SourceLocation startLoc;
Chris Lattnerf04da132007-10-24 17:06:59 +0000896 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000897 const char *startBuf = 0;
898 const char *semiPtr = 0;
899 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
900 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
901 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
902 if (I == D.begin()) {
903 // Get the start location and compute the semi location.
904 startLoc = ClassDecl->getLocation();
905 startBuf = SM->getCharacterData(startLoc);
906 semiPtr = strchr(startBuf, ';');
907 typedefString += "// @class ";
908 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000909 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000910 }
911 // Translate to typedef's that forward reference structs with the same name
912 // as the class. As a convenience, we include the original declaration
913 // as a comment.
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000914
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000915
Steve Naroff32174822007-11-09 12:50:28 +0000916 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000917 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000918 typedefString += "\n";
919 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000920 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000921 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000922 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000923 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000924 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000925 }
Mike Stump1eb44332009-09-09 15:08:12 +0000926
Steve Naroff934f2762007-10-24 22:48:43 +0000927 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000928 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000929}
930
Steve Naroffb29b4272008-04-14 22:03:09 +0000931void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000932 // When method is a synthesized one, such as a getter/setter there is
933 // nothing to rewrite.
934 if (Method->isSynthesized())
935 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000936 SourceLocation LocStart = Method->getLocStart();
937 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000938
Chandler Carruth64211622011-07-25 21:09:52 +0000939 if (SM->getExpansionLineNumber(LocEnd) >
940 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000941 InsertText(LocStart, "#if 0\n");
942 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000944 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000945 }
946}
947
Mike Stump1eb44332009-09-09 15:08:12 +0000948void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000949 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Benjamin Kramerd999b372010-02-14 14:14:16 +0000951 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000952 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000953}
954
Steve Naroffb29b4272008-04-14 22:03:09 +0000955void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000956 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Steve Naroff423cb562007-10-30 13:30:57 +0000958 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000959 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000961 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
962 E = CatDecl->prop_end(); I != E; ++I)
963 RewriteProperty(*I);
964
Mike Stump1eb44332009-09-09 15:08:12 +0000965 for (ObjCCategoryDecl::instmeth_iterator
966 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000967 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000968 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000969 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000970 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000971 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000972 RewriteMethodDeclaration(*I);
973
Steve Naroff423cb562007-10-30 13:30:57 +0000974 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000975 ReplaceText(CatDecl->getAtEndRange().getBegin(),
976 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000977}
978
Steve Naroffb29b4272008-04-14 22:03:09 +0000979void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000980 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Steve Naroff752d6ef2007-10-30 16:42:30 +0000982 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000983 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000984
985 for (ObjCProtocolDecl::instmeth_iterator
986 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000988 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000989 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000990 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000991 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000992 RewriteMethodDeclaration(*I);
993
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000994 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
995 E = PDecl->prop_end(); I != E; ++I)
996 RewriteProperty(*I);
997
Steve Naroff752d6ef2007-10-30 16:42:30 +0000998 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000999 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001000 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001001
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001002 // Must comment out @optional/@required
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
1005 for (const char *p = startBuf; p < endBuf; p++) {
1006 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001007 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001008 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 }
1011 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001012 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001013 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001015 }
1016 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001017}
1018
Steve Naroffb29b4272008-04-14 22:03:09 +00001019void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001020 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001021 if (LocStart.isInvalid())
1022 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001023 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001024 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001025}
1026
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1028 const FunctionType *&FPRetType) {
1029 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001030 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001031 else if (T->isFunctionPointerType() ||
1032 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001033 // needs special handling, since pointer-to-functions have special
1034 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001035 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001036 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001037 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001038 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001039 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001040 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001041 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001042 ResultStr += FPRetType->getResultType().getAsString(
1043 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001044 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001045 }
1046 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001047 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048}
1049
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001050void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1051 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001052 std::string &ResultStr) {
1053 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1054 const FunctionType *FPRetType = 0;
1055 ResultStr += "\nstatic ";
1056 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001057 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001059 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001062 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001063 NameStr += "_I_";
1064 else
1065 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001067 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001068 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001069
1070 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001071 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001072 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001073 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001076 {
1077 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 int len = selString.size();
1079 for (int i = 0; i < len; i++)
1080 if (selString[i] == ':')
1081 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001082 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001084 // Remember this name for metadata emission
1085 MethodInternalNames[OMD] = NameStr;
1086 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 // Rewrite arguments
1089 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001090
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001092 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001093 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001094 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001095 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001096 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001097 ResultStr += "struct ";
1098 }
1099 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001100 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001101 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102 }
1103 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001104 ResultStr += Context->getObjCClassType().getAsString(
1105 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001108 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001109 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001112 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1113 E = OMD->param_end(); PI != E; ++PI) {
1114 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001116 if (PDecl->getType()->isObjCQualifiedIdType()) {
1117 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001118 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001119 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001121 QualType QT = PDecl->getType();
1122 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1123 if (convertBlockPointerToFunctionPointer(QT))
1124 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1125 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001126 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001127 ResultStr += Name;
1128 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001130 if (OMD->isVariadic())
1131 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001132 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Steve Naroff76e429d2008-07-16 14:40:40 +00001134 if (FPRetType) {
1135 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Steve Naroff76e429d2008-07-16 14:40:40 +00001137 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001138 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001139 ResultStr += "(";
1140 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1141 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001142 std::string ParamStr = FT->getArgType(i).getAsString(
1143 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001144 ResultStr += ParamStr;
1145 }
1146 if (FT->isVariadic()) {
1147 if (FT->getNumArgs()) ResultStr += ", ";
1148 ResultStr += "...";
1149 }
1150 ResultStr += ")";
1151 } else {
1152 ResultStr += "()";
1153 }
1154 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001156void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001157 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1158 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001160 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001162 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001163 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1164 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001165 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001167 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001168 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001170 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001171
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 const char *startBuf = SM->getCharacterData(LocStart);
1173 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001174 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175 }
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1179 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001180 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001182 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001183 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001184 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001185 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 const char *startBuf = SM->getCharacterData(LocStart);
1188 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001189 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001191 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001192 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001193 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001194 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001195 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001196 }
1197
Benjamin Kramerd999b372010-02-14 14:14:16 +00001198 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001199}
1200
Steve Naroffb29b4272008-04-14 22:03:09 +00001201void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001202 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001204 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001205 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001207 ResultStr += "\n";
1208 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001210 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001211 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001212 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001213 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001214 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001215 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001216 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001217 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001218
1219 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001220 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001221 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001222 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001223 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001224 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001225 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001226 for (ObjCInterfaceDecl::classmeth_iterator
1227 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001228 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001229 RewriteMethodDeclaration(*I);
1230
Steve Naroff2feac5e2007-10-30 03:43:13 +00001231 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001232 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1233 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001234}
1235
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001236Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001237 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001238 ObjCMethodDecl *OMD = 0;
1239 QualType Ty;
1240 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001241 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001242 bool Super = false;
1243 QualType SuperTy;
1244 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001245 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001246 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001247 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001248 if (ObjCPropertyRefExpr *PropRefExpr =
1249 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001250 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001251 if (PropRefExpr->isExplicitProperty()) {
1252 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1253 OMD = PDecl->getSetterMethodDecl();
1254 Ty = PDecl->getType();
1255 Sel = PDecl->getSetterName();
1256 } else {
1257 OMD = PropRefExpr->getImplicitPropertySetter();
1258 Sel = OMD->getSelector();
1259 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001260 }
John McCall12f78a62010-12-02 01:19:52 +00001261 Super = PropRefExpr->isSuperReceiver();
1262 if (!Super) {
1263 Receiver = PropRefExpr->getBase();
1264 } else {
1265 SuperTy = PropRefExpr->getSuperReceiverType();
1266 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001267 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001268 }
1269
1270 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001271 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001272 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001274 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001275 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001276 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001277 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001278 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001279 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001280 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001281 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001282 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001283 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001284 &ExprVec[0], 1,
1285 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001286 else {
1287 // FIXME. Refactor this into common code with that in
1288 // RewritePropertyOrImplicitGetter
1289 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1290 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1291 if (PropGetters[Exp])
1292 // This allows us to handle chain/nested property/implicit getters.
1293 Receiver = PropGetters[Exp];
1294
Douglas Gregor04badcf2010-04-21 00:45:42 +00001295 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001296 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001297 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001298 /*FIXME: */SourceLocation(),
1299 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001300 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001301 &ExprVec[0], 1,
1302 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001303 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001304 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Steve Naroffc77a6362008-12-04 16:24:46 +00001306 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001307 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001308 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001309 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1310 // to things that stay around.
1311 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001312 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001313}
1314
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001315Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1316 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001317 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001318 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001319 ObjCMethodDecl *OMD = 0;
1320 QualType Ty;
1321 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001322 bool Super = false;
1323 QualType SuperTy;
1324 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001325 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001326 if (ObjCPropertyRefExpr *PropRefExpr =
1327 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001328 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001329 if (PropRefExpr->isExplicitProperty()) {
1330 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1331 OMD = PDecl->getGetterMethodDecl();
1332 Ty = PDecl->getType();
1333 Sel = PDecl->getGetterName();
1334 } else {
1335 OMD = PropRefExpr->getImplicitPropertyGetter();
1336 Sel = OMD->getSelector();
1337 Ty = PropRefExpr->getType();
1338 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001339 Super = PropRefExpr->isSuperReceiver();
1340 if (!Super)
1341 Receiver = PropRefExpr->getBase();
1342 else {
John McCall12f78a62010-12-02 01:19:52 +00001343 SuperTy = PropRefExpr->getSuperReceiverType();
1344 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001345 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001346 }
1347
1348 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1349
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001350 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001351 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001352 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001353 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001354 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001355 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001356 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001357 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001358 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001359 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001360 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001361 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001362 else {
1363 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1364 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1365 if (PropGetters[Exp])
1366 // This allows us to handle chain/nested property/implicit getters.
1367 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001368 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001369 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001370 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001371 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001372 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001373 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001374 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001375 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001376 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001377
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001378 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1379 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001380
1381 if (!PropParentMap)
1382 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001383 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001384 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001385 ImplicitCastExpr*ICE=0;
1386 if (Parent)
1387 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1388 assert((ICE->getCastKind() == CK_GetObjCProperty)
1389 && "RewritePropertyOrImplicitGetter");
1390 Parent = PropParentMap->getParent(Parent);
1391 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1392 }
1393 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001394 // We stash away the ReplacingStmt since actually doing the
1395 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001396 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001397 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1398 // to things that stay around.
1399 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001400 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001401 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001402 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001403 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001404 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1405 // to things that stay around.
1406 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001407 return ReplacingStmt;
1408 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001409}
1410
Mike Stump1eb44332009-09-09 15:08:12 +00001411Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001412 SourceLocation OrigStart,
1413 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001414 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001415 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001416 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001417 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001418 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001419 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001420 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001421 // lookup which class implements the instance variable.
1422 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001423 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001424 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001425 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Steve Narofff0757612008-05-08 17:52:16 +00001427 // Synthesize an explicit cast to gain access to the ivar.
1428 std::string RecName = clsDeclared->getIdentifier()->getName();
1429 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001430 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001431 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001432 SourceLocation(), SourceLocation(),
1433 II);
Steve Narofff0757612008-05-08 17:52:16 +00001434 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1435 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001436 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001437 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001438 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001439 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001440 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001441 IV->getBase()->getLocEnd(),
1442 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001443 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001444 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001445 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001446 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001447 IV->getLocation(),
1448 D->getType(),
1449 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001450 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001451 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001452 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001453 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001454 // Cannot delete IV->getBase(), since PE points to it.
1455 // Replace the old base with the cast. This is important when doing
1456 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001457 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001458 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001459 }
Steve Naroff84472a82008-04-18 21:55:08 +00001460 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001461 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Steve Naroff9f525972008-05-06 23:20:07 +00001463 // Explicit ivar refs need to have a cast inserted.
1464 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001465 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001466 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001467 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001468 // lookup which class implements the instance variable.
1469 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001470 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001471 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001472 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Steve Naroff9f525972008-05-06 23:20:07 +00001474 // Synthesize an explicit cast to gain access to the ivar.
1475 std::string RecName = clsDeclared->getIdentifier()->getName();
1476 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001477 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001478 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001479 SourceLocation(), SourceLocation(),
1480 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001481 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1482 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001483 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001484 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001485 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001486 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001487 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001488 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001489 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001490 // Cannot delete IV->getBase(), since PE points to it.
1491 // Replace the old base with the cast. This is important when doing
1492 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001493 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001494 return IV;
1495 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001496 }
Steve Naroff84472a82008-04-18 21:55:08 +00001497 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001498}
1499
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001500Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001501 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001502 if (*CI) {
1503 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1504 if (newStmt)
1505 *CI = newStmt;
1506 }
1507 }
1508 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1509 SourceRange OrigStmtRange = S->getSourceRange();
1510 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1511 replaced);
1512 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001513 }
1514 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1515 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1516 return newStmt;
1517 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001518 return S;
1519}
1520
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521/// SynthCountByEnumWithState - To print:
1522/// ((unsigned int (*)
1523/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001524/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001526/// "countByEnumeratingWithState:objects:count:"),
1527/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001528/// (id *)items, (unsigned int)16)
1529///
Steve Naroffb29b4272008-04-14 22:03:09 +00001530void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001531 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1532 "id *, unsigned int))(void *)objc_msgSend)";
1533 buf += "\n\t\t";
1534 buf += "((id)l_collection,\n\t\t";
1535 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1536 buf += "\n\t\t";
1537 buf += "&enumState, "
1538 "(id *)items, (unsigned int)16)";
1539}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001540
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001541/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1542/// statement to exit to its outer synthesized loop.
1543///
Steve Naroffb29b4272008-04-14 22:03:09 +00001544Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001545 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1546 return S;
1547 // replace break with goto __break_label
1548 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001550 SourceLocation startLoc = S->getLocStart();
1551 buf = "goto __break_label_";
1552 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001553 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001554
1555 return 0;
1556}
1557
1558/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1559/// statement to continue with its inner synthesized loop.
1560///
Steve Naroffb29b4272008-04-14 22:03:09 +00001561Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001562 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1563 return S;
1564 // replace continue with goto __continue_label
1565 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001567 SourceLocation startLoc = S->getLocStart();
1568 buf = "goto __continue_label_";
1569 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001570 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001572 return 0;
1573}
1574
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001575/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001576/// It rewrites:
1577/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001579/// Into:
1580/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001581/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001582/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001583/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001584/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001585/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001587/// if (limit) {
1588/// unsigned long startMutations = *enumState.mutationsPtr;
1589/// do {
1590/// unsigned long counter = 0;
1591/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001592/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001594/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001595/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001596/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001597/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001598/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599/// objects:items count:16]);
1600/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001602/// }
1603/// else
1604/// elem = nil;
1605/// }
1606///
Steve Naroffb29b4272008-04-14 22:03:09 +00001607Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001608 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001609 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001610 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001612 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001616 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001617 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001618 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 std::string buf;
1620 buf = "\n{\n\t";
1621 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1622 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001623 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001624 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001625 if (ElementType->isObjCQualifiedIdType() ||
1626 ElementType->isObjCQualifiedInterfaceType())
1627 // Simply use 'id' for all qualified types.
1628 elementTypeAsString = "id";
1629 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001630 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001631 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001633 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 buf += elementName;
1635 buf += ";\n\t";
1636 }
Chris Lattner06767512008-04-08 05:52:18 +00001637 else {
1638 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001639 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001640 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1641 if (VD->getType()->isObjCQualifiedIdType() ||
1642 VD->getType()->isObjCQualifiedInterfaceType())
1643 // Simply use 'id' for all qualified types.
1644 elementTypeAsString = "id";
1645 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001646 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001647 }
Mike Stump1eb44332009-09-09 15:08:12 +00001648
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001649 // struct __objcFastEnumerationState enumState = { 0 };
1650 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1651 // id items[16];
1652 buf += "id items[16];\n\t";
1653 // id l_collection = (id)
1654 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001655 // Find start location of 'collection' the hard way!
1656 const char *startCollectionBuf = startBuf;
1657 startCollectionBuf += 3; // skip 'for'
1658 startCollectionBuf = strchr(startCollectionBuf, '(');
1659 startCollectionBuf++; // skip '('
1660 // find 'in' and skip it.
1661 while (*startCollectionBuf != ' ' ||
1662 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1663 (*(startCollectionBuf+3) != ' ' &&
1664 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1665 startCollectionBuf++;
1666 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001667
1668 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001669 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001670 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001671 SourceLocation rightParenLoc = S->getRParenLoc();
1672 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1673 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001674 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001676 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1677 // objects:items count:16];
1678 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 // ((unsigned int (*)
1681 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001682 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001683 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // "countByEnumeratingWithState:objects:count:"),
1685 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001686 // (id *)items, (unsigned int)16);
1687 buf += "unsigned long limit =\n\t\t";
1688 SynthCountByEnumWithState(buf);
1689 buf += ";\n\t";
1690 /// if (limit) {
1691 /// unsigned long startMutations = *enumState.mutationsPtr;
1692 /// do {
1693 /// unsigned long counter = 0;
1694 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001695 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001696 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001697 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001698 buf += "if (limit) {\n\t";
1699 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1700 buf += "do {\n\t\t";
1701 buf += "unsigned long counter = 0;\n\t\t";
1702 buf += "do {\n\t\t\t";
1703 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1704 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1705 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001706 buf += " = (";
1707 buf += elementTypeAsString;
1708 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001710 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001712 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001713 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001714 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 /// objects:items count:16]);
1716 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001717 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001718 /// }
1719 /// else
1720 /// elem = nil;
1721 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001722 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001723 buf = ";\n\t";
1724 buf += "__continue_label_";
1725 buf += utostr(ObjCBcLabelNo.back());
1726 buf += ": ;";
1727 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001728 buf += "} while (counter < limit);\n\t";
1729 buf += "} while (limit = ";
1730 SynthCountByEnumWithState(buf);
1731 buf += ");\n\t";
1732 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001733 buf += " = ((";
1734 buf += elementTypeAsString;
1735 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001736 buf += "__break_label_";
1737 buf += utostr(ObjCBcLabelNo.back());
1738 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001739 buf += "}\n\t";
1740 buf += "else\n\t\t";
1741 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001742 buf += " = ((";
1743 buf += elementTypeAsString;
1744 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001745 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001747 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001748 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001749 if (isa<CompoundStmt>(S->getBody())) {
1750 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001751 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001752 } else {
1753 /* Need to treat single statements specially. For example:
1754 *
1755 * for (A *a in b) if (stuff()) break;
1756 * for (A *a in b) xxxyy;
1757 *
1758 * The following code simply scans ahead to the semi to find the actual end.
1759 */
1760 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1761 const char *semiBuf = strchr(stmtBuf, ';');
1762 assert(semiBuf && "Can't find ';'");
1763 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001764 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001765 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001766 Stmts.pop_back();
1767 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001768 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001769}
1770
Mike Stump1eb44332009-09-09 15:08:12 +00001771/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001772/// This routine rewrites @synchronized(expr) stmt;
1773/// into:
1774/// objc_sync_enter(expr);
1775/// @try stmt @finally { objc_sync_exit(expr); }
1776///
Steve Naroffb29b4272008-04-14 22:03:09 +00001777Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001778 // Get the start location and compute the semi location.
1779 SourceLocation startLoc = S->getLocStart();
1780 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001782 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001783
1784 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001785 buf = "objc_sync_enter((id)";
1786 const char *lparenBuf = startBuf;
1787 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001788 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001789 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1790 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001791 // been rewritten! (which implies the SourceLocation's are invalid).
1792 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001793 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001794 while (*endBuf != ')') endBuf--;
1795 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001796 buf = ");\n";
1797 // declare a new scope with two variables, _stack and _rethrow.
1798 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1799 buf += "int buf[18/*32-bit i386*/];\n";
1800 buf += "char *pointers[4];} _stack;\n";
1801 buf += "id volatile _rethrow = 0;\n";
1802 buf += "objc_exception_try_enter(&_stack);\n";
1803 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001804 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001805 startLoc = S->getSynchBody()->getLocEnd();
1806 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Steve Naroffc7089f12008-08-19 13:04:19 +00001808 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001809 SourceLocation lastCurlyLoc = startLoc;
1810 buf = "}\nelse {\n";
1811 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001812 buf += "}\n";
1813 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001814 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001815
1816 std::string syncBuf;
1817 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001818 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00001819 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001820 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001821 std::string syncExprBufS;
1822 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001823 syncExpr->printPretty(syncExprBuf, *Context, 0,
1824 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001825 syncBuf += syncExprBuf.str();
1826 syncBuf += ");";
1827
1828 buf += syncBuf;
1829 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001830 buf += "}\n";
1831 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001832
Benjamin Kramerd999b372010-02-14 14:14:16 +00001833 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001834
1835 bool hasReturns = false;
1836 HasReturnStmts(S->getSynchBody(), hasReturns);
1837 if (hasReturns)
1838 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1839
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001840 return 0;
1841}
1842
Steve Naroffb85e77a2009-12-05 21:43:12 +00001843void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1844{
Steve Naroff8c565152008-12-05 17:03:39 +00001845 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001846 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001847 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001848 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001849
Steve Naroffb85e77a2009-12-05 21:43:12 +00001850 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001851 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001852 TryFinallyContainsReturnDiag);
1853 }
1854 return;
1855}
1856
Steve Naroffb85e77a2009-12-05 21:43:12 +00001857void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1858{
1859 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001860 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001861 if (*CI)
1862 HasReturnStmts(*CI, hasReturns);
1863
1864 if (isa<ReturnStmt>(S))
1865 hasReturns = true;
1866 return;
1867}
1868
1869void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1870 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001871 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001872 if (*CI) {
1873 RewriteTryReturnStmts(*CI);
1874 }
1875 if (isa<ReturnStmt>(S)) {
1876 SourceLocation startLoc = S->getLocStart();
1877 const char *startBuf = SM->getCharacterData(startLoc);
1878
1879 const char *semiBuf = strchr(startBuf, ';');
1880 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1881 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1882
1883 std::string buf;
1884 buf = "{ objc_exception_try_exit(&_stack); return";
1885
Benjamin Kramerd999b372010-02-14 14:14:16 +00001886 ReplaceText(startLoc, 6, buf);
1887 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888 }
1889 return;
1890}
1891
1892void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1893 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001894 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001895 if (*CI) {
1896 RewriteSyncReturnStmts(*CI, syncExitBuf);
1897 }
1898 if (isa<ReturnStmt>(S)) {
1899 SourceLocation startLoc = S->getLocStart();
1900 const char *startBuf = SM->getCharacterData(startLoc);
1901
1902 const char *semiBuf = strchr(startBuf, ';');
1903 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1904 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1905
1906 std::string buf;
1907 buf = "{ objc_exception_try_exit(&_stack);";
1908 buf += syncExitBuf;
1909 buf += " return";
1910
Benjamin Kramerd999b372010-02-14 14:14:16 +00001911 ReplaceText(startLoc, 6, buf);
1912 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001913 }
1914 return;
1915}
1916
Steve Naroffb29b4272008-04-14 22:03:09 +00001917Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001918 // Get the start location and compute the semi location.
1919 SourceLocation startLoc = S->getLocStart();
1920 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Steve Naroff75730982007-11-07 04:08:17 +00001922 assert((*startBuf == '@') && "bogus @try location");
1923
1924 std::string buf;
1925 // declare a new scope with two variables, _stack and _rethrow.
1926 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1927 buf += "int buf[18/*32-bit i386*/];\n";
1928 buf += "char *pointers[4];} _stack;\n";
1929 buf += "id volatile _rethrow = 0;\n";
1930 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001931 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001932
Benjamin Kramerd999b372010-02-14 14:14:16 +00001933 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Steve Naroff75730982007-11-07 04:08:17 +00001935 startLoc = S->getTryBody()->getLocEnd();
1936 startBuf = SM->getCharacterData(startLoc);
1937
1938 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Steve Naroff75730982007-11-07 04:08:17 +00001940 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001941 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001942 startLoc = startLoc.getFileLocWithOffset(1);
1943 buf = " /* @catch begin */ else {\n";
1944 buf += " id _caught = objc_exception_extract(&_stack);\n";
1945 buf += " objc_exception_try_enter (&_stack);\n";
1946 buf += " if (_setjmp(_stack.buf))\n";
1947 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1948 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Benjamin Kramerd999b372010-02-14 14:14:16 +00001950 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001951 } else { /* no catch list */
1952 buf = "}\nelse {\n";
1953 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1954 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001955 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001956 }
Steve Naroff75730982007-11-07 04:08:17 +00001957 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001958 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1959 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001960 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001961
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001962 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001963 buf = "if ("; // we are generating code for the first catch clause
1964 else
1965 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001966 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001967 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Steve Naroff75730982007-11-07 04:08:17 +00001969 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Steve Naroff75730982007-11-07 04:08:17 +00001971 const char *lParenLoc = strchr(startBuf, '(');
1972
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001973 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001974 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001975 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001976 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1977 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001978 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001979 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001980 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Steve Naroffe12e6922008-02-01 20:02:07 +00001982 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001983 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001984 } else if (catchDecl) {
1985 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001986 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001987 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001988 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001989 } else if (const ObjCObjectPointerType *Ptr =
1990 t->getAs<ObjCObjectPointerType>()) {
1991 // Should be a pointer to a class.
1992 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1993 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001994 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001995 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001996 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001998 }
1999 }
2000 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002001 lastCatchBody = Catch->getCatchBody();
2002 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002003 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2004 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2005 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2006 assert((*rParenBuf == ')') && "bogus @catch paren location");
2007 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Mike Stump1eb44332009-09-09 15:08:12 +00002009 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002010 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002011 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002012 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002013 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002014 }
Steve Naroff75730982007-11-07 04:08:17 +00002015 }
2016 // Complete the catch list...
2017 if (lastCatchBody) {
2018 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002019 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2020 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Steve Naroff378f47a2008-09-11 15:29:03 +00002022 // Insert the last (implicit) else clause *before* the right curly brace.
2023 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2024 buf = "} /* last catch end */\n";
2025 buf += "else {\n";
2026 buf += " _rethrow = _caught;\n";
2027 buf += " objc_exception_try_exit(&_stack);\n";
2028 buf += "} } /* @catch end */\n";
2029 if (!S->getFinallyStmt())
2030 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002031 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Steve Naroff75730982007-11-07 04:08:17 +00002033 // Set lastCurlyLoc
2034 lastCurlyLoc = lastCatchBody->getLocEnd();
2035 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002036 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002037 startLoc = finalStmt->getLocStart();
2038 startBuf = SM->getCharacterData(startLoc);
2039 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Benjamin Kramerd999b372010-02-14 14:14:16 +00002041 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Steve Naroff75730982007-11-07 04:08:17 +00002043 Stmt *body = finalStmt->getFinallyBody();
2044 SourceLocation startLoc = body->getLocStart();
2045 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002046 assert(*SM->getCharacterData(startLoc) == '{' &&
2047 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002048 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002049 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroff75730982007-11-07 04:08:17 +00002051 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002052 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002053 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002054 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Steve Naroff75730982007-11-07 04:08:17 +00002056 // Set lastCurlyLoc
2057 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Steve Naroff8c565152008-12-05 17:03:39 +00002059 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002060 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002061 } else { /* no finally clause - make sure we synthesize an implicit one */
2062 buf = "{ /* implicit finally clause */\n";
2063 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2064 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2065 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002066 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002067
2068 // Now check for any return/continue/go statements within the @try.
2069 // The implicit finally clause won't called if the @try contains any
2070 // jump statements.
2071 bool hasReturns = false;
2072 HasReturnStmts(S->getTryBody(), hasReturns);
2073 if (hasReturns)
2074 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002075 }
2076 // Now emit the final closing curly brace...
2077 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002078 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002079 return 0;
2080}
2081
Mike Stump1eb44332009-09-09 15:08:12 +00002082// This can't be done with ReplaceStmt(S, ThrowExpr), since
2083// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002084// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002085Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002086 // Get the start location and compute the semi location.
2087 SourceLocation startLoc = S->getLocStart();
2088 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroff2bd03922007-11-07 15:32:26 +00002090 assert((*startBuf == '@') && "bogus @throw location");
2091
2092 std::string buf;
2093 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002094 if (S->getThrowExpr())
2095 buf = "objc_exception_throw(";
2096 else // add an implicit argument
2097 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002099 // handle "@ throw" correctly.
2100 const char *wBuf = strchr(startBuf, 'w');
2101 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002102 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Steve Naroff2bd03922007-11-07 15:32:26 +00002104 const char *semiBuf = strchr(startBuf, ';');
2105 assert((*semiBuf == ';') && "@throw: can't find ';'");
2106 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002107 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002108 return 0;
2109}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002110
Steve Naroffb29b4272008-04-14 22:03:09 +00002111Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002112 // Create a new string expression.
2113 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002114 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002115 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002116 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002117 StringLiteral::Ascii, false,
2118 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002119 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Chris Lattner07506182007-11-30 22:53:43 +00002121 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002122 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002123 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002124}
2125
Steve Naroffb29b4272008-04-14 22:03:09 +00002126Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002127 if (!SelGetUidFunctionDecl)
2128 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002129 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2130 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002131 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002132 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002133 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002134 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002135 StringLiteral::Ascii, false,
2136 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002137 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2138 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002139 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002140 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002141 return SelExp;
2142}
2143
Steve Naroffb29b4272008-04-14 22:03:09 +00002144CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002145 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2146 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002147 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002148 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Steve Naroffebf2b562007-10-23 23:50:29 +00002150 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002151 DeclRefExpr *DRE =
2152 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Steve Naroffebf2b562007-10-23 23:50:29 +00002154 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002155 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002156 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002157 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002158 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002159
John McCall183700f2009-09-21 23:43:11 +00002160 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002162 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002163 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002164 FT->getCallResultType(*Context),
2165 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002166 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002167}
2168
Steve Naroffd5255f52007-11-01 13:24:47 +00002169static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2170 const char *&startRef, const char *&endRef) {
2171 while (startBuf < endBuf) {
2172 if (*startBuf == '<')
2173 startRef = startBuf; // mark the start.
2174 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002175 if (startRef && *startRef == '<') {
2176 endRef = startBuf; // mark the end.
2177 return true;
2178 }
2179 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002180 }
2181 startBuf++;
2182 }
2183 return false;
2184}
2185
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002186static void scanToNextArgument(const char *&argRef) {
2187 int angle = 0;
2188 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2189 if (*argRef == '<')
2190 angle++;
2191 else if (*argRef == '>')
2192 angle--;
2193 argRef++;
2194 }
2195 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2196}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002197
Steve Naroffb29b4272008-04-14 22:03:09 +00002198bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002199 if (T->isObjCQualifiedIdType())
2200 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002201 if (const PointerType *PT = T->getAs<PointerType>()) {
2202 if (PT->getPointeeType()->isObjCQualifiedIdType())
2203 return true;
2204 }
2205 if (T->isObjCObjectPointerType()) {
2206 T = T->getPointeeType();
2207 return T->isObjCQualifiedInterfaceType();
2208 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002209 if (T->isArrayType()) {
2210 QualType ElemTy = Context->getBaseElementType(T);
2211 return needToScanForQualifiers(ElemTy);
2212 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002213 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002214}
2215
Steve Naroff4f95b752008-07-29 18:15:38 +00002216void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2217 QualType Type = E->getType();
2218 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002219 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Steve Naroffcda658e2008-11-19 21:15:47 +00002221 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2222 Loc = ECE->getLParenLoc();
2223 EndLoc = ECE->getRParenLoc();
2224 } else {
2225 Loc = E->getLocStart();
2226 EndLoc = E->getLocEnd();
2227 }
2228 // This will defend against trying to rewrite synthesized expressions.
2229 if (Loc.isInvalid() || EndLoc.isInvalid())
2230 return;
2231
Steve Naroff4f95b752008-07-29 18:15:38 +00002232 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002233 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002234 const char *startRef = 0, *endRef = 0;
2235 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2236 // Get the locations of the startRef, endRef.
2237 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2238 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2239 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002240 InsertText(LessLoc, "/*");
2241 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002242 }
2243 }
2244}
2245
Steve Naroffb29b4272008-04-14 22:03:09 +00002246void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002247 SourceLocation Loc;
2248 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002249 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002250 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2251 Loc = VD->getLocation();
2252 Type = VD->getType();
2253 }
2254 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2255 Loc = FD->getLocation();
2256 // Check for ObjC 'id' and class types that have been adorned with protocol
2257 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002258 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002259 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002260 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002261 if (!proto)
2262 return;
2263 Type = proto->getResultType();
2264 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002265 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2266 Loc = FD->getLocation();
2267 Type = FD->getType();
2268 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002269 else
2270 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002272 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002273 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002274
Steve Naroffd5255f52007-11-01 13:24:47 +00002275 const char *endBuf = SM->getCharacterData(Loc);
2276 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002277 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002278 startBuf--; // scan backward (from the decl location) for return type.
2279 const char *startRef = 0, *endRef = 0;
2280 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2281 // Get the locations of the startRef, endRef.
2282 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2283 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2284 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002285 InsertText(LessLoc, "/*");
2286 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002287 }
2288 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002289 if (!proto)
2290 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002291 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002292 const char *startBuf = SM->getCharacterData(Loc);
2293 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002294 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2295 if (needToScanForQualifiers(proto->getArgType(i))) {
2296 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Steve Naroffd5255f52007-11-01 13:24:47 +00002298 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002299 // scan forward (from the decl location) for argument types.
2300 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002301 const char *startRef = 0, *endRef = 0;
2302 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2303 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002304 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002305 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002306 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002307 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002308 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002309 InsertText(LessLoc, "/*");
2310 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002311 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002312 startBuf = ++endBuf;
2313 }
2314 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002315 // If the function name is derived from a macro expansion, then the
2316 // argument buffer will not follow the name. Need to speak with Chris.
2317 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002318 startBuf++; // scan forward (from the decl location) for argument types.
2319 startBuf++;
2320 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002321 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002322}
2323
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002324void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2325 QualType QT = ND->getType();
2326 const Type* TypePtr = QT->getAs<Type>();
2327 if (!isa<TypeOfExprType>(TypePtr))
2328 return;
2329 while (isa<TypeOfExprType>(TypePtr)) {
2330 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2331 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2332 TypePtr = QT->getAs<Type>();
2333 }
2334 // FIXME. This will not work for multiple declarators; as in:
2335 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002336 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002337 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2338 const char *startBuf = SM->getCharacterData(DeclLoc);
2339 if (ND->getInit()) {
2340 std::string Name(ND->getNameAsString());
2341 TypeAsString += " " + Name + " = ";
2342 Expr *E = ND->getInit();
2343 SourceLocation startLoc;
2344 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2345 startLoc = ECE->getLParenLoc();
2346 else
2347 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002348 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002349 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002350 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002351 }
2352 else {
2353 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002354 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002355 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002356 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002357 }
2358}
2359
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002360// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002361void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002362 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002364 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002365 QualType getFuncType =
2366 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002367 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002368 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002369 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002370 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002371 SC_Extern,
2372 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002373}
2374
Steve Naroffb29b4272008-04-14 22:03:09 +00002375void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002376 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002377 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002378 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002379 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002380 return;
2381 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002382 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002383}
2384
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002385void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2386 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002387 const char *argPtr = TypeString.c_str();
2388 if (!strchr(argPtr, '^')) {
2389 Str += TypeString;
2390 return;
2391 }
2392 while (*argPtr) {
2393 Str += (*argPtr == '^' ? '*' : *argPtr);
2394 argPtr++;
2395 }
2396}
2397
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002398// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002399void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2400 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002401 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002402 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002403 const char *argPtr = TypeString.c_str();
2404 int paren = 0;
2405 while (*argPtr) {
2406 switch (*argPtr) {
2407 case '(':
2408 Str += *argPtr;
2409 paren++;
2410 break;
2411 case ')':
2412 Str += *argPtr;
2413 paren--;
2414 break;
2415 case '^':
2416 Str += '*';
2417 if (paren == 1)
2418 Str += VD->getNameAsString();
2419 break;
2420 default:
2421 Str += *argPtr;
2422 break;
2423 }
2424 argPtr++;
2425 }
2426}
2427
2428
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002429void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2430 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2431 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2432 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2433 if (!proto)
2434 return;
2435 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002436 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002437 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002438 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002439 FdStr += "(";
2440 unsigned numArgs = proto->getNumArgs();
2441 for (unsigned i = 0; i < numArgs; i++) {
2442 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002443 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002444 if (i+1 < numArgs)
2445 FdStr += ", ";
2446 }
2447 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002448 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002449 CurFunctionDeclToDeclareForBlock = 0;
2450}
2451
Steve Naroffc0a123c2008-03-11 17:37:02 +00002452// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002453void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002454 if (SuperContructorFunctionDecl)
2455 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002456 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002457 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002458 QualType argT = Context->getObjCIdType();
2459 assert(!argT.isNull() && "Can't find 'id' type");
2460 ArgTys.push_back(argT);
2461 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002462 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2463 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002464 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002465 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002466 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002467 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002468 SC_Extern,
2469 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002470}
2471
Steve Naroff09b266e2007-10-30 23:14:51 +00002472// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002473void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002474 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002475 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002476 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002477 assert(!argT.isNull() && "Can't find 'id' type");
2478 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002479 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002480 assert(!argT.isNull() && "Can't find 'SEL' type");
2481 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002482 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483 &ArgTys[0], ArgTys.size(),
2484 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002486 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002487 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002488 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002489 SC_Extern,
2490 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002491}
2492
Steve Naroff874e2322007-11-15 10:28:18 +00002493// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002494void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002496 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002497 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002498 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002499 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002500 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2501 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2502 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002503 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002504 assert(!argT.isNull() && "Can't find 'SEL' type");
2505 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002506 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2507 &ArgTys[0], ArgTys.size(),
2508 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002509 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002510 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002511 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002512 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002513 SC_Extern,
2514 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002515}
2516
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002517// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002518void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002519 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002520 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002521 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002522 assert(!argT.isNull() && "Can't find 'id' type");
2523 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002525 assert(!argT.isNull() && "Can't find 'SEL' type");
2526 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2528 &ArgTys[0], ArgTys.size(),
2529 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002530 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002531 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002532 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002533 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002534 SC_Extern,
2535 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002536}
2537
Mike Stump1eb44332009-09-09 15:08:12 +00002538// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002540void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002541 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002544 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002545 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002546 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002547 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2548 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2549 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002550 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002551 assert(!argT.isNull() && "Can't find 'SEL' type");
2552 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002553 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2554 &ArgTys[0], ArgTys.size(),
2555 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002556 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002557 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002559 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002560 SC_Extern,
2561 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562}
2563
Steve Naroff1284db82008-05-08 22:02:18 +00002564// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002565void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002566 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002569 assert(!argT.isNull() && "Can't find 'id' type");
2570 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002571 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002572 assert(!argT.isNull() && "Can't find 'SEL' type");
2573 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002574 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2575 &ArgTys[0], ArgTys.size(),
2576 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002577 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002578 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002579 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002580 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002581 SC_Extern,
2582 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002583}
2584
Steve Naroff09b266e2007-10-30 23:14:51 +00002585// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002586void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002587 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002588 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002589 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002590 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2591 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002592 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002593 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002594 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002595 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002596 SC_Extern,
2597 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002598}
2599
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002600// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2601void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2602 IdentifierInfo *getSuperClassIdent =
2603 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002604 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002605 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002606 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2607 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002608 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002609 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002610 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002611 getSuperClassIdent,
2612 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002613 SC_Extern,
2614 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002615 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002616}
2617
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002618// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002619void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002620 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002621 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002622 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002623 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2624 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002625 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002626 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002627 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002628 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002629 SC_Extern,
2630 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002631}
2632
Steve Naroffb29b4272008-04-14 22:03:09 +00002633Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002634 QualType strType = getConstantStringStructType();
2635
2636 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002637
2638 std::string tmpName = InFileName;
2639 unsigned i;
2640 for (i=0; i < tmpName.length(); i++) {
2641 char c = tmpName.at(i);
2642 // replace any non alphanumeric characters with '_'.
2643 if (!isalpha(c) && (c < '0' || c > '9'))
2644 tmpName[i] = '_';
2645 }
2646 S += tmpName;
2647 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002648 S += utostr(NumObjCStringLiterals++);
2649
Steve Naroffba92b2e2008-03-27 22:29:16 +00002650 Preamble += "static __NSConstantStringImpl " + S;
2651 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2652 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002653 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002654 std::string prettyBufS;
2655 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002656 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2657 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002658 Preamble += prettyBuf.str();
2659 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002660 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002661
2662 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002663 SourceLocation(), &Context->Idents.get(S),
2664 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002665 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2666 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002667 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002668 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002669 VK_RValue, OK_Ordinary,
2670 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002671 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002672 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00002673 CK_BitCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002674 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002675 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002676 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002677}
2678
Steve Naroff874e2322007-11-15 10:28:18 +00002679// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002680QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002681 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002682 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002683 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002684 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002685 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Steve Naroff874e2322007-11-15 10:28:18 +00002687 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002688 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002689 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002690 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002691
Steve Naroff874e2322007-11-15 10:28:18 +00002692 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002693 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002694 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002695 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002696 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002697 FieldTypes[i], 0,
2698 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002699 /*Mutable=*/false,
2700 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002701 }
Mike Stump1eb44332009-09-09 15:08:12 +00002702
Douglas Gregor838db382010-02-11 01:19:42 +00002703 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002704 }
2705 return Context->getTagDeclType(SuperStructDecl);
2706}
2707
Steve Naroffb29b4272008-04-14 22:03:09 +00002708QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002709 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002710 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002711 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002712 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002713 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002714
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002715 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002716 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002717 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002718 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002719 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002720 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002721 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002722 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002723
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002724 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002725 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002726 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2727 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002728 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002729 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002730 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002731 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002732 /*Mutable=*/true,
2733 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002734 }
2735
Douglas Gregor838db382010-02-11 01:19:42 +00002736 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002737 }
2738 return Context->getTagDeclType(ConstantStringDecl);
2739}
2740
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002741Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2742 SourceLocation StartLoc,
2743 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002744 if (!SelGetUidFunctionDecl)
2745 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002746 if (!MsgSendFunctionDecl)
2747 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002748 if (!MsgSendSuperFunctionDecl)
2749 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002750 if (!MsgSendStretFunctionDecl)
2751 SynthMsgSendStretFunctionDecl();
2752 if (!MsgSendSuperStretFunctionDecl)
2753 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002754 if (!MsgSendFpretFunctionDecl)
2755 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002756 if (!GetClassFunctionDecl)
2757 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002758 if (!GetSuperClassFunctionDecl)
2759 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002760 if (!GetMetaClassFunctionDecl)
2761 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Steve Naroff874e2322007-11-15 10:28:18 +00002763 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002764 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2765 // May need to use objc_msgSend_stret() as well.
2766 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002767 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2768 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002769 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002770 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002771 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002772 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002773 }
Mike Stump1eb44332009-09-09 15:08:12 +00002774
Steve Naroff934f2762007-10-24 22:48:43 +00002775 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002776 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 switch (Exp->getReceiverKind()) {
2778 case ObjCMessageExpr::SuperClass: {
2779 MsgSendFlavor = MsgSendSuperFunctionDecl;
2780 if (MsgSendStretFlavor)
2781 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2782 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Douglas Gregor04badcf2010-04-21 00:45:42 +00002784 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002785
Chris Lattner5f9e2722011-07-23 10:55:15 +00002786 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002787
Douglas Gregor04badcf2010-04-21 00:45:42 +00002788 // set the receiver to self, the first argument to all methods.
2789 InitExprs.push_back(
2790 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002791 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002792 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002793 Context->getObjCIdType(),
2794 VK_RValue,
2795 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002796 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002797
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002799 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 QualType argType = Context->getPointerType(Context->CharTy);
2801 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002802 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002803 StringLiteral::Ascii, false,
2804 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2806 &ClsExprs[0],
2807 ClsExprs.size(),
2808 StartLoc,
2809 EndLoc);
2810 // (Class)objc_getClass("CurrentClass")
2811 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2812 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002813 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 ClsExprs.clear();
2815 ClsExprs.push_back(ArgExpr);
2816 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2817 &ClsExprs[0], ClsExprs.size(),
2818 StartLoc, EndLoc);
2819
2820 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2821 // To turn off a warning, type-cast to 'id'
2822 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2823 NoTypeInfoCStyleCastExpr(Context,
2824 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002825 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002826 // struct objc_super
2827 QualType superType = getSuperStructType();
2828 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002829
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830 if (LangOpts.Microsoft) {
2831 SynthSuperContructorFunctionDecl();
2832 // Simulate a contructor call...
2833 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002834 superType, VK_LValue,
2835 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2837 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002838 superType, VK_LValue,
2839 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002840 // The code for super is a little tricky to prevent collision with
2841 // the structure definition in the header. The rewriter has it's own
2842 // internal definition (__rw_objc_super) that is uses. This is why
2843 // we need the cast below. For example:
2844 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2845 //
John McCall2de56d12010-08-25 11:45:40 +00002846 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002848 VK_RValue, OK_Ordinary,
2849 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2851 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002852 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002853 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 // (struct objc_super) { <exprs from above> }
2855 InitListExpr *ILE =
2856 new (Context) InitListExpr(*Context, SourceLocation(),
2857 &InitExprs[0], InitExprs.size(),
2858 SourceLocation());
2859 TypeSourceInfo *superTInfo
2860 = Context->getTrivialTypeSourceInfo(superType);
2861 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002862 superType, VK_LValue,
2863 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002864 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002865 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002866 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002867 VK_RValue, OK_Ordinary,
2868 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002869 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002870 MsgExprs.push_back(SuperRep);
2871 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002872 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002873
2874 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002875 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 QualType argType = Context->getPointerType(Context->CharTy);
2877 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002878 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002879 IdentifierInfo *clsName = Class->getIdentifier();
2880 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002881 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002882 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002883 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002884 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2885 &ClsExprs[0],
2886 ClsExprs.size(),
2887 StartLoc, EndLoc);
2888 MsgExprs.push_back(Cls);
2889 break;
2890 }
2891
2892 case ObjCMessageExpr::SuperInstance:{
2893 MsgSendFlavor = MsgSendSuperFunctionDecl;
2894 if (MsgSendStretFlavor)
2895 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2896 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2897 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002898 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002899
2900 InitExprs.push_back(
2901 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002902 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002904 Context->getObjCIdType(),
2905 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002906 ); // set the 'receiver'.
2907
2908 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002909 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002910 QualType argType = Context->getPointerType(Context->CharTy);
2911 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002912 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002913 StringLiteral::Ascii, false, argType,
2914 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002915 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2916 &ClsExprs[0],
2917 ClsExprs.size(),
2918 StartLoc, EndLoc);
2919 // (Class)objc_getClass("CurrentClass")
2920 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2921 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002922 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 ClsExprs.clear();
2924 ClsExprs.push_back(ArgExpr);
2925 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2926 &ClsExprs[0], ClsExprs.size(),
2927 StartLoc, EndLoc);
2928
2929 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2930 // To turn off a warning, type-cast to 'id'
2931 InitExprs.push_back(
2932 // set 'super class', using class_getSuperclass().
2933 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002934 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002935 // struct objc_super
2936 QualType superType = getSuperStructType();
2937 Expr *SuperRep;
2938
2939 if (LangOpts.Microsoft) {
2940 SynthSuperContructorFunctionDecl();
2941 // Simulate a contructor call...
2942 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002943 superType, VK_LValue,
2944 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002945 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2946 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002947 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002948 // The code for super is a little tricky to prevent collision with
2949 // the structure definition in the header. The rewriter has it's own
2950 // internal definition (__rw_objc_super) that is uses. This is why
2951 // we need the cast below. For example:
2952 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2953 //
John McCall2de56d12010-08-25 11:45:40 +00002954 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002956 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002957 SourceLocation());
2958 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2959 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002960 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002961 } else {
2962 // (struct objc_super) { <exprs from above> }
2963 InitListExpr *ILE =
2964 new (Context) InitListExpr(*Context, SourceLocation(),
2965 &InitExprs[0], InitExprs.size(),
2966 SourceLocation());
2967 TypeSourceInfo *superTInfo
2968 = Context->getTrivialTypeSourceInfo(superType);
2969 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002970 superType, VK_RValue, ILE,
2971 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002972 }
2973 MsgExprs.push_back(SuperRep);
2974 break;
2975 }
2976
2977 case ObjCMessageExpr::Instance: {
2978 // Remove all type-casts because it may contain objc-style types; e.g.
2979 // Foo<Proto> *.
2980 Expr *recExpr = Exp->getInstanceReceiver();
2981 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2982 recExpr = CE->getSubExpr();
2983 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002984 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002985 MsgExprs.push_back(recExpr);
2986 break;
2987 }
2988 }
2989
Steve Naroffbeaf2992007-11-03 11:27:19 +00002990 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002991 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002992 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002993 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002994 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002995 StringLiteral::Ascii, false,
2996 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002997 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002998 &SelExprs[0], SelExprs.size(),
2999 StartLoc,
3000 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003001 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroff934f2762007-10-24 22:48:43 +00003003 // Now push any user supplied arguments.
3004 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003005 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003006 // Make all implicit casts explicit...ICE comes in handy:-)
3007 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3008 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003009 QualType type = ICE->getType();
3010 if (needToScanForQualifiers(type))
3011 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003012 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003013 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003014 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3015 bool integral = SubExpr->getType()->isIntegralType(*Context);
3016 userExpr = NoTypeInfoCStyleCastExpr(Context, type,
3017 (integral && type->isBooleanType())
3018 ? CK_IntegralToBoolean : CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003019 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003020 }
3021 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003022 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003023 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003024 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003025 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00003026 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003027 CK_BitCast, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003028 }
Mike Stump1eb44332009-09-09 15:08:12 +00003029 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003030 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003031 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3032 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003033 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003034 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003035 }
Steve Naroffab972d32007-11-04 22:37:50 +00003036 // Generate the funky cast.
3037 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003038 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003039 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Steve Naroffab972d32007-11-04 22:37:50 +00003041 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003042 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3043 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3044 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003045 ArgTypes.push_back(Context->getObjCIdType());
3046 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003047 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003048 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003049 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3050 E = OMD->param_end(); PI != E; ++PI) {
3051 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003052 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003053 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003054 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003055 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003056 ArgTypes.push_back(t);
3057 }
Chris Lattner89951a82009-02-20 18:43:26 +00003058 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3059 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003060 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003061 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003062 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003063 }
3064 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003065 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Steve Naroffab972d32007-11-04 22:37:50 +00003067 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003068 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003069 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003070
Mike Stump1eb44332009-09-09 15:08:12 +00003071 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003072 // If we don't do this cast, we get the following bizarre warning/note:
3073 // xx.m:13: warning: function called through a non-compatible type
3074 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003075 cast = NoTypeInfoCStyleCastExpr(Context,
3076 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003077 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003078
Steve Naroffab972d32007-11-04 22:37:50 +00003079 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003080 QualType castType =
3081 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3082 // If we don't have a method decl, force a variadic cast.
3083 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003084 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003085 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003086 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003087
3088 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003089 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003090
John McCall183700f2009-09-21 23:43:11 +00003091 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003092 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003093 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003094 FT->getResultType(), VK_RValue,
3095 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003096 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003097 if (MsgSendStretFlavor) {
3098 // We have the method which returns a struct/union. Must also generate
3099 // call to objc_msgSend_stret and hang both varieties on a conditional
3100 // expression which dictate which one to envoke depending on size of
3101 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003103 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003104 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003105 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003106 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003107 cast = NoTypeInfoCStyleCastExpr(Context,
3108 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003109 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003110 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003111 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3112 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003113 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003114 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003115 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003117 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003118 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003119
John McCall183700f2009-09-21 23:43:11 +00003120 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003121 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003122 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003123 FT->getResultType(), VK_RValue,
3124 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003126 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003127 UnaryExprOrTypeTraitExpr *sizeofExpr =
3128 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3129 Context->getTrivialTypeSourceInfo(returnType),
3130 Context->getSizeType(), SourceLocation(),
3131 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003132 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3133 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3134 // For X86 it is more complicated and some kind of target specific routine
3135 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003136 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003137 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003138 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3139 llvm::APInt(IntSize, 8),
3140 Context->IntTy,
3141 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003142 BinaryOperator *lessThanExpr =
3143 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3144 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003145 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003146 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003147 new (Context) ConditionalOperator(lessThanExpr,
3148 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003149 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003150 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003151 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3152 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003153 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003154 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003155 return ReplacingStmt;
3156}
3157
Steve Naroffb29b4272008-04-14 22:03:09 +00003158Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003159 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3160 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Steve Naroff934f2762007-10-24 22:48:43 +00003162 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003163 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003165 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003166 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003167}
3168
Steve Naroff621edce2009-04-29 16:37:50 +00003169// typedef struct objc_object Protocol;
3170QualType RewriteObjC::getProtocolType() {
3171 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003172 TypeSourceInfo *TInfo
3173 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003174 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003175 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003176 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003177 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003178 }
3179 return Context->getTypeDeclType(ProtocolTypeDecl);
3180}
3181
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003182/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003183/// a synthesized/forward data reference (to the protocol's metadata).
3184/// The forward references (and metadata) are generated in
3185/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003186Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003187 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3188 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003189 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003190 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003191 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003192 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3193 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003194 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003195 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003196 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003197 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003198 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003199 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003200 ReplaceStmt(Exp, castExpr);
3201 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003202 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003203 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003205}
3206
Mike Stump1eb44332009-09-09 15:08:12 +00003207bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003208 const char *endBuf) {
3209 while (startBuf < endBuf) {
3210 if (*startBuf == '#') {
3211 // Skip whitespace.
3212 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3213 ;
3214 if (!strncmp(startBuf, "if", strlen("if")) ||
3215 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3216 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3217 !strncmp(startBuf, "define", strlen("define")) ||
3218 !strncmp(startBuf, "undef", strlen("undef")) ||
3219 !strncmp(startBuf, "else", strlen("else")) ||
3220 !strncmp(startBuf, "elif", strlen("elif")) ||
3221 !strncmp(startBuf, "endif", strlen("endif")) ||
3222 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3223 !strncmp(startBuf, "include", strlen("include")) ||
3224 !strncmp(startBuf, "import", strlen("import")) ||
3225 !strncmp(startBuf, "include_next", strlen("include_next")))
3226 return true;
3227 }
3228 startBuf++;
3229 }
3230 return false;
3231}
3232
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003233/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003234/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003235void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003236 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003237 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003238 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003239 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003240 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003241 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003242 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003243 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003244 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003245 SourceLocation LocStart = CDecl->getLocStart();
3246 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003247
Steve Narofffea763e82007-11-14 19:25:57 +00003248 const char *startBuf = SM->getCharacterData(LocStart);
3249 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003250
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003251 // If no ivars and no root or if its root, directly or indirectly,
3252 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003253 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3254 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003255 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003256 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003257 return;
3258 }
Mike Stump1eb44332009-09-09 15:08:12 +00003259
3260 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003261 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003262 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003263 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003264 if (LangOpts.Microsoft)
3265 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003266
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003267 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003268 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003269 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003270 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003271 // If the buffer contains preprocessor directives, we do more fine-grained
3272 // rewrites. This is intended to fix code that looks like (which occurs in
3273 // NSURL.h, for example):
3274 //
3275 // #ifdef XYZ
3276 // @interface Foo : NSObject
3277 // #else
3278 // @interface FooBar : NSObject
3279 // #endif
3280 // {
3281 // int i;
3282 // }
3283 // @end
3284 //
3285 // This clause is segregated to avoid breaking the common case.
3286 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003287 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003288 CDecl->getClassLoc();
3289 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003290 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003291
Chris Lattnercafeb352009-02-20 18:18:36 +00003292 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003293 // advance to the end of the referenced protocols.
3294 while (endHeader < cursor && *endHeader != '>') endHeader++;
3295 endHeader++;
3296 }
3297 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003298 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003299 } else {
3300 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003301 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003302 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003303 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003304 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003305 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003306 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003307 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003308 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Steve Narofffea763e82007-11-14 19:25:57 +00003310 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003311 SourceLocation OnePastCurly =
3312 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003313 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003314 }
3315 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Steve Narofffea763e82007-11-14 19:25:57 +00003317 // Now comment out any visibility specifiers.
3318 while (cursor < endBuf) {
3319 if (*cursor == '@') {
3320 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003321 // Skip whitespace.
3322 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3323 /*scan*/;
3324
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003325 // FIXME: presence of @public, etc. inside comment results in
3326 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003327 if (!strncmp(cursor, "public", strlen("public")) ||
3328 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003329 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003330 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003331 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003332 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003333 // FIXME: If there are cases where '<' is used in ivar declaration part
3334 // of user code, then scan the ivar list and use needToScanForQualifiers
3335 // for type checking.
3336 else if (*cursor == '<') {
3337 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003338 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003339 cursor = strchr(cursor, '>');
3340 cursor++;
3341 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003342 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003343 } else if (*cursor == '^') { // rewrite block specifier.
3344 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003345 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003346 }
Steve Narofffea763e82007-11-14 19:25:57 +00003347 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003348 }
Steve Narofffea763e82007-11-14 19:25:57 +00003349 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003350 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003351 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003352 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003353 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003354 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003355 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003356 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003357 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003358 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003359 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003360 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003361 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003362 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003363}
3364
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003365// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003366/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003367template<typename MethodIterator>
3368void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3369 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003370 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003371 StringRef prefix,
3372 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003373 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003374 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003375
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003376 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003377 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003378 SEL _cmd;
3379 char *method_types;
3380 void *_imp;
3381 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003382 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003383 Result += "\nstruct _objc_method {\n";
3384 Result += "\tSEL _cmd;\n";
3385 Result += "\tchar *method_types;\n";
3386 Result += "\tvoid *_imp;\n";
3387 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003389 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003390 }
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003392 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003393
Steve Naroff946a6932008-03-11 00:12:29 +00003394 /* struct {
3395 struct _objc_method_list *next_method;
3396 int method_count;
3397 struct _objc_method method_list[];
3398 }
3399 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003400 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003401 Result += "\nstatic struct {\n";
3402 Result += "\tstruct _objc_method_list *next_method;\n";
3403 Result += "\tint method_count;\n";
3404 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003405 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003406 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003407 Result += prefix;
3408 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3409 Result += "_METHODS_";
3410 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003411 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003412 Result += IsInstanceMethod ? "inst" : "cls";
3413 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003414 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003415
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003416 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003417 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003418 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003419 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003420 Result += "\", \"";
3421 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003422 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003423 Result += MethodInternalNames[*MethodBegin];
3424 Result += "}\n";
3425 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3426 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003427 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003428 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003429 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003430 Result += "\", \"";
3431 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003432 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003433 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003434 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003435 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003436 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003437}
3438
Steve Naroff621edce2009-04-29 16:37:50 +00003439/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003440void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003441RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3442 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003443 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003444
3445 // Output struct protocol_methods holder of method selector and type.
3446 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3447 /* struct protocol_methods {
3448 SEL _cmd;
3449 char *method_types;
3450 }
3451 */
3452 Result += "\nstruct _protocol_methods {\n";
3453 Result += "\tstruct objc_selector *_cmd;\n";
3454 Result += "\tchar *method_types;\n";
3455 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003456
Steve Naroff621edce2009-04-29 16:37:50 +00003457 objc_protocol_methods = true;
3458 }
3459 // Do not synthesize the protocol more than once.
3460 if (ObjCSynthesizedProtocols.count(PDecl))
3461 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003463 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3464 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3465 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003466 /* struct _objc_protocol_method_list {
3467 int protocol_method_count;
3468 struct protocol_methods protocols[];
3469 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003470 */
Steve Naroff621edce2009-04-29 16:37:50 +00003471 Result += "\nstatic struct {\n";
3472 Result += "\tint protocol_method_count;\n";
3473 Result += "\tstruct _protocol_methods protocol_methods[";
3474 Result += utostr(NumMethods);
3475 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3476 Result += PDecl->getNameAsString();
3477 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3478 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Steve Naroff621edce2009-04-29 16:37:50 +00003480 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003481 for (ObjCProtocolDecl::instmeth_iterator
3482 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003483 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003484 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003485 Result += "\t ,{{(struct objc_selector *)\"";
3486 else
3487 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003488 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003489 std::string MethodTypeString;
3490 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3491 Result += "\", \"";
3492 Result += MethodTypeString;
3493 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003494 }
Steve Naroff621edce2009-04-29 16:37:50 +00003495 Result += "\t }\n};\n";
3496 }
Mike Stump1eb44332009-09-09 15:08:12 +00003497
Steve Naroff621edce2009-04-29 16:37:50 +00003498 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003499 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3500 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003501 if (NumMethods > 0) {
3502 /* struct _objc_protocol_method_list {
3503 int protocol_method_count;
3504 struct protocol_methods protocols[];
3505 }
3506 */
3507 Result += "\nstatic struct {\n";
3508 Result += "\tint protocol_method_count;\n";
3509 Result += "\tstruct _protocol_methods protocol_methods[";
3510 Result += utostr(NumMethods);
3511 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3512 Result += PDecl->getNameAsString();
3513 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3514 "{\n\t";
3515 Result += utostr(NumMethods);
3516 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003517
Steve Naroff621edce2009-04-29 16:37:50 +00003518 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003519 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003520 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003521 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003522 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003523 Result += "\t ,{{(struct objc_selector *)\"";
3524 else
3525 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003526 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003527 std::string MethodTypeString;
3528 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3529 Result += "\", \"";
3530 Result += MethodTypeString;
3531 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003532 }
Steve Naroff621edce2009-04-29 16:37:50 +00003533 Result += "\t }\n};\n";
3534 }
3535
3536 // Output:
3537 /* struct _objc_protocol {
3538 // Objective-C 1.0 extensions
3539 struct _objc_protocol_extension *isa;
3540 char *protocol_name;
3541 struct _objc_protocol **protocol_list;
3542 struct _objc_protocol_method_list *instance_methods;
3543 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003544 };
Steve Naroff621edce2009-04-29 16:37:50 +00003545 */
3546 static bool objc_protocol = false;
3547 if (!objc_protocol) {
3548 Result += "\nstruct _objc_protocol {\n";
3549 Result += "\tstruct _objc_protocol_extension *isa;\n";
3550 Result += "\tchar *protocol_name;\n";
3551 Result += "\tstruct _objc_protocol **protocol_list;\n";
3552 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3553 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003554 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Steve Naroff621edce2009-04-29 16:37:50 +00003556 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003557 }
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Steve Naroff621edce2009-04-29 16:37:50 +00003559 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3560 Result += PDecl->getNameAsString();
3561 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3562 "{\n\t0, \"";
3563 Result += PDecl->getNameAsString();
3564 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003565 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003566 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3567 Result += PDecl->getNameAsString();
3568 Result += ", ";
3569 }
3570 else
3571 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003572 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003573 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3574 Result += PDecl->getNameAsString();
3575 Result += "\n";
3576 }
3577 else
3578 Result += "0\n";
3579 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Steve Naroff621edce2009-04-29 16:37:50 +00003581 // Mark this protocol as having been generated.
3582 if (!ObjCSynthesizedProtocols.insert(PDecl))
3583 assert(false && "protocol already synthesized");
3584
3585}
3586
3587void RewriteObjC::
3588RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003589 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003590 std::string &Result) {
3591 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Steve Naroff621edce2009-04-29 16:37:50 +00003593 for (unsigned i = 0; i != Protocols.size(); i++)
3594 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3595
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003596 // Output the top lovel protocol meta-data for the class.
3597 /* struct _objc_protocol_list {
3598 struct _objc_protocol_list *next;
3599 int protocol_count;
3600 struct _objc_protocol *class_protocols[];
3601 }
3602 */
3603 Result += "\nstatic struct {\n";
3604 Result += "\tstruct _objc_protocol_list *next;\n";
3605 Result += "\tint protocol_count;\n";
3606 Result += "\tstruct _objc_protocol *class_protocols[";
3607 Result += utostr(Protocols.size());
3608 Result += "];\n} _OBJC_";
3609 Result += prefix;
3610 Result += "_PROTOCOLS_";
3611 Result += ClassName;
3612 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3613 "{\n\t0, ";
3614 Result += utostr(Protocols.size());
3615 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003617 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003618 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003619 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003621 for (unsigned i = 1; i != Protocols.size(); i++) {
3622 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003623 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003624 Result += "\n";
3625 }
3626 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003627}
3628
Steve Naroff621edce2009-04-29 16:37:50 +00003629
Mike Stump1eb44332009-09-09 15:08:12 +00003630/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003631/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003632void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003633 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003634 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003635 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003636 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003637 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003638 CDecl = CDecl->getNextClassCategory())
3639 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3640 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003641
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003642 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003643 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003644 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003645
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003646 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003647 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003648 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003649
3650 // If any of our property implementations have associated getters or
3651 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003652 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3653 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003654 Prop != PropEnd; ++Prop) {
3655 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3656 continue;
3657 if (!(*Prop)->getPropertyIvarDecl())
3658 continue;
3659 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3660 if (!PD)
3661 continue;
3662 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3663 InstanceMethods.push_back(Getter);
3664 if (PD->isReadOnly())
3665 continue;
3666 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3667 InstanceMethods.push_back(Setter);
3668 }
3669 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003670 true, "CATEGORY_", FullCategoryName.c_str(),
3671 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003673 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003674 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003675 false, "CATEGORY_", FullCategoryName.c_str(),
3676 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003677
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003678 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003679 // Null CDecl is case of a category implementation with no category interface
3680 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003681 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003682 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003683 /* struct _objc_category {
3684 char *category_name;
3685 char *class_name;
3686 struct _objc_method_list *instance_methods;
3687 struct _objc_method_list *class_methods;
3688 struct _objc_protocol_list *protocols;
3689 // Objective-C 1.0 extensions
3690 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003691 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003692 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003693 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003694 */
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003696 static bool objc_category = false;
3697 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003698 Result += "\nstruct _objc_category {\n";
3699 Result += "\tchar *category_name;\n";
3700 Result += "\tchar *class_name;\n";
3701 Result += "\tstruct _objc_method_list *instance_methods;\n";
3702 Result += "\tstruct _objc_method_list *class_methods;\n";
3703 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003704 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003705 Result += "\tstruct _objc_property_list *instance_properties;\n";
3706 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003707 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003708 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003709 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3710 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003711 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003712 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003713 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003714 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003715 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003717 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003718 Result += "\t, (struct _objc_method_list *)"
3719 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3720 Result += FullCategoryName;
3721 Result += "\n";
3722 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003723 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003724 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003725 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003726 Result += "\t, (struct _objc_method_list *)"
3727 "&_OBJC_CATEGORY_CLASS_METHODS_";
3728 Result += FullCategoryName;
3729 Result += "\n";
3730 }
3731 else
3732 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Chris Lattnercafeb352009-02-20 18:18:36 +00003734 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003735 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003736 Result += FullCategoryName;
3737 Result += "\n";
3738 }
3739 else
3740 Result += "\t, 0\n";
3741 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003742}
3743
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003744/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3745/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003746void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003747 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003748 if (ivar->isBitField()) {
3749 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3750 // place all bitfields at offset 0.
3751 Result += "0";
3752 } else {
3753 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003754 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003755 if (LangOpts.Microsoft)
3756 Result += "_IMPL";
3757 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003758 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003759 Result += ")";
3760 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003761}
3762
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763//===----------------------------------------------------------------------===//
3764// Meta Data Emission
3765//===----------------------------------------------------------------------===//
3766
Steve Naroffb29b4272008-04-14 22:03:09 +00003767void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003768 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003769 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003771 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003772 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003773 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003774 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003775 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003776 }
Mike Stump1eb44332009-09-09 15:08:12 +00003777
Chris Lattnerbe6df082007-12-12 07:56:42 +00003778 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003779 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003780 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003781 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003782 if (NumIvars > 0) {
3783 static bool objc_ivar = false;
3784 if (!objc_ivar) {
3785 /* struct _objc_ivar {
3786 char *ivar_name;
3787 char *ivar_type;
3788 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003789 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003790 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003791 Result += "\nstruct _objc_ivar {\n";
3792 Result += "\tchar *ivar_name;\n";
3793 Result += "\tchar *ivar_type;\n";
3794 Result += "\tint ivar_offset;\n";
3795 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003796
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003797 objc_ivar = true;
3798 }
3799
Steve Naroff946a6932008-03-11 00:12:29 +00003800 /* struct {
3801 int ivar_count;
3802 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003803 };
Steve Naroff946a6932008-03-11 00:12:29 +00003804 */
Mike Stump1eb44332009-09-09 15:08:12 +00003805 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003806 Result += "\tint ivar_count;\n";
3807 Result += "\tstruct _objc_ivar ivar_list[";
3808 Result += utostr(NumIvars);
3809 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003810 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003811 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003812 "{\n\t";
3813 Result += utostr(NumIvars);
3814 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003815
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003816 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003817 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003818 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003819 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003820 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003821 IV != IVEnd; ++IV)
3822 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003823 IVI = IDecl->ivar_begin();
3824 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003825 } else {
3826 IVI = CDecl->ivar_begin();
3827 IVE = CDecl->ivar_end();
3828 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003829 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003830 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003831 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003832 std::string TmpString, StrEncoding;
3833 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3834 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003835 Result += StrEncoding;
3836 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003837 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003838 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003839 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003840 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003841 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003842 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003843 std::string TmpString, StrEncoding;
3844 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3845 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003846 Result += StrEncoding;
3847 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003848 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003849 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003850 }
Mike Stump1eb44332009-09-09 15:08:12 +00003851
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003852 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003853 }
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003855 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003856 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003857 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003858
3859 // If any of our property implementations have associated getters or
3860 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003861 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3862 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003863 Prop != PropEnd; ++Prop) {
3864 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3865 continue;
3866 if (!(*Prop)->getPropertyIvarDecl())
3867 continue;
3868 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3869 if (!PD)
3870 continue;
3871 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003872 if (!Getter->isDefined())
3873 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003874 if (PD->isReadOnly())
3875 continue;
3876 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003877 if (!Setter->isDefined())
3878 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003879 }
3880 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003881 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003883 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003884 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003885 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003887 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003888 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003889 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003891 // Declaration of class/meta-class metadata
3892 /* struct _objc_class {
3893 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003894 const char *super_class_name;
3895 char *name;
3896 long version;
3897 long info;
3898 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003899 struct _objc_ivar_list *ivars;
3900 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003901 struct objc_cache *cache;
3902 struct objc_protocol_list *protocols;
3903 const char *ivar_layout;
3904 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003905 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003906 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003907 static bool objc_class = false;
3908 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003909 Result += "\nstruct _objc_class {\n";
3910 Result += "\tstruct _objc_class *isa;\n";
3911 Result += "\tconst char *super_class_name;\n";
3912 Result += "\tchar *name;\n";
3913 Result += "\tlong version;\n";
3914 Result += "\tlong info;\n";
3915 Result += "\tlong instance_size;\n";
3916 Result += "\tstruct _objc_ivar_list *ivars;\n";
3917 Result += "\tstruct _objc_method_list *methods;\n";
3918 Result += "\tstruct objc_cache *cache;\n";
3919 Result += "\tstruct _objc_protocol_list *protocols;\n";
3920 Result += "\tconst char *ivar_layout;\n";
3921 Result += "\tstruct _objc_class_ext *ext;\n";
3922 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003923 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003924 }
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003926 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003927 ObjCInterfaceDecl *RootClass = 0;
3928 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003929 while (SuperClass) {
3930 RootClass = SuperClass;
3931 SuperClass = SuperClass->getSuperClass();
3932 }
3933 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003935 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003936 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003937 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003938 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003939 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003940 Result += "\"";
3941
3942 if (SuperClass) {
3943 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003944 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003945 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003946 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003947 Result += "\"";
3948 }
3949 else {
3950 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003951 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003952 Result += "\"";
3953 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003954 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003955 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003956 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003957 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003958 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003959 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003960 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003962 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003963 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003964 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003965 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003966 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003967 Result += ",0,0\n";
3968 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003969 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003970 Result += "\t,0,0,0,0\n";
3971 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003973 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003974 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003975 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003976 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003977 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003978 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003979 if (SuperClass) {
3980 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003981 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003983 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 Result += "\"";
3985 }
3986 else {
3987 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003988 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 Result += "\"";
3990 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003991 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003992 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003993 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003994 Result += ",0";
3995 else {
3996 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003997 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003998 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003999 if (LangOpts.Microsoft)
4000 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004001 Result += ")";
4002 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004003 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004004 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004006 Result += "\n\t";
4007 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004008 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004010 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004011 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004012 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004013 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004015 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004017 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004018 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004019 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004020 Result += ", 0,0\n";
4021 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004022 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004023 Result += ",0,0,0\n";
4024 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004025}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004026
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004027/// RewriteImplementations - This routine rewrites all method implementations
4028/// and emits meta-data.
4029
Steve Narofface66252008-11-13 20:07:04 +00004030void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004031 int ClsDefCount = ClassImplementation.size();
4032 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004033
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004034 // Rewrite implemented methods
4035 for (int i = 0; i < ClsDefCount; i++)
4036 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004038 for (int i = 0; i < CatDefCount; i++)
4039 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004040}
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Steve Narofface66252008-11-13 20:07:04 +00004042void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4043 int ClsDefCount = ClassImplementation.size();
4044 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004045
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004046 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004047 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004048 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004050 // For each implemented category, write out all its meta data.
4051 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004052 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004053
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004054 // Write objc_symtab metadata
4055 /*
4056 struct _objc_symtab
4057 {
4058 long sel_ref_cnt;
4059 SEL *refs;
4060 short cls_def_cnt;
4061 short cat_def_cnt;
4062 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004063 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004064 */
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004066 Result += "\nstruct _objc_symtab {\n";
4067 Result += "\tlong sel_ref_cnt;\n";
4068 Result += "\tSEL *refs;\n";
4069 Result += "\tshort cls_def_cnt;\n";
4070 Result += "\tshort cat_def_cnt;\n";
4071 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4072 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004074 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004075 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004076 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004077 + ", " + utostr(CatDefCount) + "\n";
4078 for (int i = 0; i < ClsDefCount; i++) {
4079 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004080 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004081 Result += "\n";
4082 }
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004084 for (int i = 0; i < CatDefCount; i++) {
4085 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004086 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004087 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004088 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004089 Result += "\n";
4090 }
Mike Stump1eb44332009-09-09 15:08:12 +00004091
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004092 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004093
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004094 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004096 /*
4097 struct _objc_module {
4098 long version;
4099 long size;
4100 const char *name;
4101 struct _objc_symtab *symtab;
4102 }
4103 */
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004105 Result += "\nstruct _objc_module {\n";
4106 Result += "\tlong version;\n";
4107 Result += "\tlong size;\n";
4108 Result += "\tconst char *name;\n";
4109 Result += "\tstruct _objc_symtab *symtab;\n";
4110 Result += "};\n\n";
4111 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004112 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004113 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004114 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004115 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004116
4117 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004118 if (ProtocolExprDecls.size()) {
4119 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4120 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004121 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004122 E = ProtocolExprDecls.end(); I != E; ++I) {
4123 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4124 Result += (*I)->getNameAsString();
4125 Result += " = &_OBJC_PROTOCOL_";
4126 Result += (*I)->getNameAsString();
4127 Result += ";\n";
4128 }
4129 Result += "#pragma data_seg(pop)\n\n";
4130 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004131 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004132 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004133 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4134 Result += "&_OBJC_MODULES;\n";
4135 Result += "#pragma data_seg(pop)\n\n";
4136 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004137}
Chris Lattner311ff022007-10-16 22:36:42 +00004138
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004139void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4140 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004141 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004142 assert(BlockByRefDeclNo.count(VD) &&
4143 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004144 if (def)
4145 ResultStr += "struct ";
4146 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004147 "_" + utostr(BlockByRefDeclNo[VD]) ;
4148}
4149
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004150static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4151 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4152 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4153 return false;
4154}
4155
Steve Naroff54055232008-10-27 17:20:55 +00004156std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004157 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004158 std::string Tag) {
4159 const FunctionType *AFT = CE->getFunctionType();
4160 QualType RT = AFT->getResultType();
4161 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004162 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004163 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004164
Steve Naroff54055232008-10-27 17:20:55 +00004165 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Douglas Gregor72564e72009-02-26 23:50:07 +00004167 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004168 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004169 // block (to reference imported block decl refs).
4170 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004171 } else if (BD->param_empty()) {
4172 S += "(" + StructRef + " *__cself)";
4173 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004174 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004175 assert(FT && "SynthesizeBlockFunc: No function proto");
4176 S += '(';
4177 // first add the implicit argument.
4178 S += StructRef + " *__cself, ";
4179 std::string ParamStr;
4180 for (BlockDecl::param_iterator AI = BD->param_begin(),
4181 E = BD->param_end(); AI != E; ++AI) {
4182 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004183 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004184 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004185 if (convertBlockPointerToFunctionPointer(QT))
4186 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004187 else
4188 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004189 S += ParamStr;
4190 }
4191 if (FT->isVariadic()) {
4192 if (!BD->param_empty()) S += ", ";
4193 S += "...";
4194 }
4195 S += ')';
4196 }
4197 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004198
Steve Naroff54055232008-10-27 17:20:55 +00004199 // Create local declarations to avoid rewriting all closure decl ref exprs.
4200 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004201 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004202 E = BlockByRefDecls.end(); I != E; ++I) {
4203 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004204 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004205 std::string TypeString;
4206 RewriteByRefString(TypeString, Name, (*I));
4207 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004208 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004209 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004210 }
Steve Naroff54055232008-10-27 17:20:55 +00004211 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004212 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004213 E = BlockByCopyDecls.end(); I != E; ++I) {
4214 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004215 // Handle nested closure invocation. For example:
4216 //
4217 // void (^myImportedClosure)(void);
4218 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004219 //
Steve Naroff54055232008-10-27 17:20:55 +00004220 // void (^anotherClosure)(void);
4221 // anotherClosure = ^(void) {
4222 // myImportedClosure(); // import and invoke the closure
4223 // };
4224 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004225 if (isTopLevelBlockPointerType((*I)->getType())) {
4226 RewriteBlockPointerTypeVariable(S, (*I));
4227 S += " = (";
4228 RewriteBlockPointerType(S, (*I)->getType());
4229 S += ")";
4230 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4231 }
4232 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004233 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004234 QualType QT = (*I)->getType();
4235 if (HasLocalVariableExternalStorage(*I))
4236 QT = Context->getPointerType(QT);
4237 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004238 S += Name + " = __cself->" +
4239 (*I)->getNameAsString() + "; // bound by copy\n";
4240 }
Steve Naroff54055232008-10-27 17:20:55 +00004241 }
4242 std::string RewrittenStr = RewrittenBlockExprs[CE];
4243 const char *cstr = RewrittenStr.c_str();
4244 while (*cstr++ != '{') ;
4245 S += cstr;
4246 S += "\n";
4247 return S;
4248}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004249
Steve Naroff54055232008-10-27 17:20:55 +00004250std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004251 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004252 std::string Tag) {
4253 std::string StructRef = "struct " + Tag;
4254 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Steve Naroff54055232008-10-27 17:20:55 +00004256 S += funcName;
4257 S += "_block_copy_" + utostr(i);
4258 S += "(" + StructRef;
4259 S += "*dst, " + StructRef;
4260 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004261 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004262 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004263 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004264 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004265 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004266 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004267 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004268 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004269 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004270 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004271 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004272 else
4273 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004274 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004275 S += "}\n";
4276
Steve Naroff54055232008-10-27 17:20:55 +00004277 S += "\nstatic void __";
4278 S += funcName;
4279 S += "_block_dispose_" + utostr(i);
4280 S += "(" + StructRef;
4281 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004282 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004283 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004284 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004285 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004286 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004287 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004288 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004289 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004290 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004291 else
4292 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004293 }
Mike Stump1eb44332009-09-09 15:08:12 +00004294 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004295 return S;
4296}
4297
Steve Naroff01aec112009-12-06 21:14:13 +00004298std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4299 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004300 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004301 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004302
Steve Naroff54055232008-10-27 17:20:55 +00004303 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004304 S += " struct " + Desc;
4305 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004306
Steve Naroff01aec112009-12-06 21:14:13 +00004307 Constructor += "(void *fp, "; // Invoke function pointer.
4308 Constructor += "struct " + Desc; // Descriptor pointer.
4309 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004310
Steve Naroff54055232008-10-27 17:20:55 +00004311 if (BlockDeclRefs.size()) {
4312 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004313 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004314 E = BlockByCopyDecls.end(); I != E; ++I) {
4315 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004316 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004317 std::string ArgName = "_" + FieldName;
4318 // Handle nested closure invocation. For example:
4319 //
4320 // void (^myImportedBlock)(void);
4321 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004322 //
Steve Naroff54055232008-10-27 17:20:55 +00004323 // void (^anotherBlock)(void);
4324 // anotherBlock = ^(void) {
4325 // myImportedBlock(); // import and invoke the closure
4326 // };
4327 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004328 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004329 S += "struct __block_impl *";
4330 Constructor += ", void *" + ArgName;
4331 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004332 QualType QT = (*I)->getType();
4333 if (HasLocalVariableExternalStorage(*I))
4334 QT = Context->getPointerType(QT);
4335 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4336 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004337 Constructor += ", " + ArgName;
4338 }
4339 S += FieldName + ";\n";
4340 }
4341 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004342 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004343 E = BlockByRefDecls.end(); I != E; ++I) {
4344 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004345 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004346 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004347 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004348 std::string TypeString;
4349 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004350 TypeString += " *";
4351 FieldName = TypeString + FieldName;
4352 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004353 Constructor += ", " + ArgName;
4354 }
4355 S += FieldName + "; // by ref\n";
4356 }
4357 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004358 Constructor += ", int flags=0)";
4359 // Initialize all "by copy" arguments.
4360 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004361 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004362 E = BlockByCopyDecls.end(); I != E; ++I) {
4363 std::string Name = (*I)->getNameAsString();
4364 if (firsTime) {
4365 Constructor += " : ";
4366 firsTime = false;
4367 }
4368 else
4369 Constructor += ", ";
4370 if (isTopLevelBlockPointerType((*I)->getType()))
4371 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4372 else
4373 Constructor += Name + "(_" + Name + ")";
4374 }
4375 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004376 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004377 E = BlockByRefDecls.end(); I != E; ++I) {
4378 std::string Name = (*I)->getNameAsString();
4379 if (firsTime) {
4380 Constructor += " : ";
4381 firsTime = false;
4382 }
4383 else
4384 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004385 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004386 }
4387
4388 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004389 if (GlobalVarDecl)
4390 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4391 else
4392 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004393 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004394
Steve Naroff01aec112009-12-06 21:14:13 +00004395 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004396 } else {
4397 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004398 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004399 if (GlobalVarDecl)
4400 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4401 else
4402 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004403 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4404 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004405 }
4406 Constructor += " ";
4407 Constructor += "}\n";
4408 S += Constructor;
4409 S += "};\n";
4410 return S;
4411}
4412
Steve Naroff01aec112009-12-06 21:14:13 +00004413std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4414 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004415 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004416 unsigned hasCopy) {
4417 std::string S = "\nstatic struct " + DescTag;
4418
4419 S += " {\n unsigned long reserved;\n";
4420 S += " unsigned long Block_size;\n";
4421 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004422 S += " void (*copy)(struct ";
4423 S += ImplTag; S += "*, struct ";
4424 S += ImplTag; S += "*);\n";
4425
4426 S += " void (*dispose)(struct ";
4427 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004428 }
4429 S += "} ";
4430
4431 S += DescTag + "_DATA = { 0, sizeof(struct ";
4432 S += ImplTag + ")";
4433 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004434 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4435 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004436 }
4437 S += "};\n";
4438 return S;
4439}
4440
Steve Naroff54055232008-10-27 17:20:55 +00004441void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004442 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004443 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004444 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004445 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004446 bool RewriteSC = (GlobalVarDecl &&
4447 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004448 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004449 GlobalVarDecl->getType().getCVRQualifiers());
4450 if (RewriteSC) {
4451 std::string SC(" void __");
4452 SC += GlobalVarDecl->getNameAsString();
4453 SC += "() {}";
4454 InsertText(FunLocStart, SC);
4455 }
4456
Steve Naroff54055232008-10-27 17:20:55 +00004457 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004458 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4459 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004460 // Need to copy-in the inner copied-in variables not actually used in this
4461 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004462 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4463 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4464 ValueDecl *VD = Exp->getDecl();
4465 BlockDeclRefs.push_back(Exp);
4466 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4467 BlockByCopyDeclsPtrSet.insert(VD);
4468 BlockByCopyDecls.push_back(VD);
4469 }
4470 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4471 BlockByRefDeclsPtrSet.insert(VD);
4472 BlockByRefDecls.push_back(VD);
4473 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004474 // imported objects in the inner blocks not used in the outer
4475 // blocks must be copied/disposed in the outer block as well.
4476 if (Exp->isByRef() ||
4477 VD->getType()->isObjCObjectPointerType() ||
4478 VD->getType()->isBlockPointerType())
4479 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004480 }
Steve Naroff54055232008-10-27 17:20:55 +00004481
Daniel Dunbar4087f272010-08-17 22:39:59 +00004482 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4483 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004484
Steve Naroff01aec112009-12-06 21:14:13 +00004485 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004486
Benjamin Kramerd999b372010-02-14 14:14:16 +00004487 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004488
Steve Naroff01aec112009-12-06 21:14:13 +00004489 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Benjamin Kramerd999b372010-02-14 14:14:16 +00004491 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004492
4493 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004494 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004495 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004496 }
Steve Naroff01aec112009-12-06 21:14:13 +00004497 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4498 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004499 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004500
Steve Naroff54055232008-10-27 17:20:55 +00004501 BlockDeclRefs.clear();
4502 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004503 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004504 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004505 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004506 ImportedBlockDecls.clear();
4507 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004508 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004509 // Must insert any 'const/volatile/static here. Since it has been
4510 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004511 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004512 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004513 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004514 if (GlobalVarDecl->getType().isConstQualified())
4515 SC += "const ";
4516 if (GlobalVarDecl->getType().isVolatileQualified())
4517 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004518 if (GlobalVarDecl->getType().isRestrictQualified())
4519 SC += "restrict ";
4520 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004521 }
4522
Steve Naroff54055232008-10-27 17:20:55 +00004523 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004524 InnerDeclRefsCount.clear();
4525 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004526 RewrittenBlockExprs.clear();
4527}
4528
4529void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4530 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004531 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Steve Naroff54055232008-10-27 17:20:55 +00004533 SynthesizeBlockLiterals(FunLocStart, FuncName);
4534}
4535
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004536static void BuildUniqueMethodName(std::string &Name,
4537 ObjCMethodDecl *MD) {
4538 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004539 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004540 Name += "__" + MD->getSelector().getAsString();
4541 // Convert colons to underscores.
4542 std::string::size_type loc = 0;
4543 while ((loc = Name.find(":", loc)) != std::string::npos)
4544 Name.replace(loc, 1, "_");
4545}
4546
Steve Naroff54055232008-10-27 17:20:55 +00004547void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004548 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4549 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004550 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004551 std::string FuncName;
4552 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004553 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004554}
4555
4556void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004557 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004558 if (*CI) {
4559 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4560 GetBlockDeclRefExprs(CBE->getBody());
4561 else
4562 GetBlockDeclRefExprs(*CI);
4563 }
4564 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004565 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004566 // FIXME: Handle enums.
4567 if (!isa<FunctionDecl>(CDRE->getDecl()))
4568 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004569 }
4570 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4571 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4572 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004573 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4574 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004575 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004576 BlockDeclRefs.push_back(BDRE);
4577 }
4578
Steve Naroff54055232008-10-27 17:20:55 +00004579 return;
4580}
4581
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004582void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004583 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004584 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004585 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004586 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004587 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4588 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004589 GetInnerBlockDeclRefExprs(CBE->getBody(),
4590 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004591 InnerContexts);
4592 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004593 else
4594 GetInnerBlockDeclRefExprs(*CI,
4595 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004596 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004597
4598 }
4599 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004600 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004601 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004602 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004603 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004604 }
4605 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4606 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4607 if (Var->isFunctionOrMethodVarDecl())
4608 ImportedLocalExternalDecls.insert(Var);
4609 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004610
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004611 return;
4612}
4613
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004614/// convertFunctionTypeOfBlocks - This routine converts a function type
4615/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004616/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004617/// all block pointers to function pointers.
4618QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4619 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4620 // FTP will be null for closures that don't take arguments.
4621 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004622 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004623 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004624 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004625
4626 if (FTP) {
4627 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4628 E = FTP->arg_type_end(); I && (I != E); ++I) {
4629 QualType t = *I;
4630 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004631 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004632 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004633 ArgTypes.push_back(t);
4634 }
4635 }
4636 QualType FuncType;
4637 // FIXME. Does this work if block takes no argument but has a return type
4638 // which is of block type?
4639 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004640 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004641 else FuncType = QualType(FT, 0);
4642 return FuncType;
4643}
4644
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004645Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004646 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004647 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004648
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004649 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004650 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004651 } else if (const BlockDeclRefExpr *CDRE =
4652 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004653 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004654 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004655 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004656 }
4657 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4658 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4659 }
4660 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4661 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4662 else if (const ConditionalOperator *CEXPR =
4663 dyn_cast<ConditionalOperator>(BlockExp)) {
4664 Expr *LHSExp = CEXPR->getLHS();
4665 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4666 Expr *RHSExp = CEXPR->getRHS();
4667 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4668 Expr *CONDExp = CEXPR->getCond();
4669 ConditionalOperator *CondExpr =
4670 new (Context) ConditionalOperator(CONDExp,
4671 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004672 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004673 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004674 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004675 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4676 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004677 } else {
4678 assert(1 && "RewriteBlockClass: Bad type");
4679 }
4680 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004681 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004682 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004683 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004684 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004686 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004687 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004688 &Context->Idents.get("__block_impl"));
4689 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004690
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004691 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004692 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004694 // Push the block argument type.
4695 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004696 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004697 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004698 E = FTP->arg_type_end(); I && (I != E); ++I) {
4699 QualType t = *I;
4700 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004701 if (!convertBlockPointerToFunctionPointer(t))
4702 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004703 ArgTypes.push_back(t);
4704 }
Steve Naroff54055232008-10-27 17:20:55 +00004705 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004706 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004707 QualType PtrToFuncCastType
4708 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004710 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004711
John McCall9d125032010-01-15 18:39:57 +00004712 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004713 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004714 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004715 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004716 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4717 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004718 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004719
Douglas Gregor44b43212008-12-11 16:49:14 +00004720 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004721 SourceLocation(),
4722 &Context->Idents.get("FuncPtr"),
4723 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004724 /*BitWidth=*/0, /*Mutable=*/true,
4725 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004726 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004727 FD->getType(), VK_LValue,
4728 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004730
John McCall9d125032010-01-15 18:39:57 +00004731 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004732 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004733 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004734
Chris Lattner5f9e2722011-07-23 10:55:15 +00004735 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004736 // Add the implicit argument.
4737 BlkExprs.push_back(BlkCast);
4738 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004739 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004740 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004741 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004742 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004743 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4744 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004745 Exp->getType(), VK_RValue,
4746 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004747 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004748}
4749
Steve Naroff621edce2009-04-29 16:37:50 +00004750// We need to return the rewritten expression to handle cases where the
4751// BlockDeclRefExpr is embedded in another expression being rewritten.
4752// For example:
4753//
4754// int main() {
4755// __block Foo *f;
4756// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004757//
Steve Naroff621edce2009-04-29 16:37:50 +00004758// void (^myblock)() = ^() {
4759// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4760// i = 77;
4761// };
4762//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004763Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004764 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004765 // for each DeclRefExp where BYREFVAR is name of the variable.
4766 ValueDecl *VD;
4767 bool isArrow = true;
4768 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4769 VD = BDRE->getDecl();
4770 else {
4771 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4772 isArrow = false;
4773 }
4774
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004775 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004776 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004777 &Context->Idents.get("__forwarding"),
4778 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004779 /*BitWidth=*/0, /*Mutable=*/true,
4780 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004781 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4782 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004783 FD->getType(), VK_LValue,
4784 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004785
Chris Lattner5f9e2722011-07-23 10:55:15 +00004786 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004787 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004788 &Context->Idents.get(Name),
4789 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004790 /*BitWidth=*/0, /*Mutable=*/true,
4791 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004792 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004793 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004794
4795
4796
Steve Naroffdf8570d2009-02-02 17:19:26 +00004797 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004798 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4799 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004800 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004801 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004802 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004803}
4804
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004805// Rewrites the imported local variable V with external storage
4806// (static, extern, etc.) as *V
4807//
4808Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4809 ValueDecl *VD = DRE->getDecl();
4810 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4811 if (!ImportedLocalExternalDecls.count(Var))
4812 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004813 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4814 VK_LValue, OK_Ordinary,
4815 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004816 // Need parens to enforce precedence.
4817 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4818 Exp);
4819 ReplaceStmt(DRE, PE);
4820 return PE;
4821}
4822
Steve Naroffb2f9e512008-11-03 23:29:32 +00004823void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4824 SourceLocation LocStart = CE->getLParenLoc();
4825 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004826
4827 // Need to avoid trying to rewrite synthesized casts.
4828 if (LocStart.isInvalid())
4829 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004830 // Need to avoid trying to rewrite casts contained in macros.
4831 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4832 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004833
Steve Naroff54055232008-10-27 17:20:55 +00004834 const char *startBuf = SM->getCharacterData(LocStart);
4835 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004836 QualType QT = CE->getType();
4837 const Type* TypePtr = QT->getAs<Type>();
4838 if (isa<TypeOfExprType>(TypePtr)) {
4839 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4840 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4841 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004842 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004843 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004844 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004845 return;
4846 }
Steve Naroff54055232008-10-27 17:20:55 +00004847 // advance the location to startArgList.
4848 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004849
Steve Naroff54055232008-10-27 17:20:55 +00004850 while (*argPtr++ && (argPtr < endBuf)) {
4851 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004852 case '^':
4853 // Replace the '^' with '*'.
4854 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004855 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004856 break;
Steve Naroff54055232008-10-27 17:20:55 +00004857 }
4858 }
4859 return;
4860}
4861
4862void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4863 SourceLocation DeclLoc = FD->getLocation();
4864 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004865
Steve Naroff54055232008-10-27 17:20:55 +00004866 // We have 1 or more arguments that have closure pointers.
4867 const char *startBuf = SM->getCharacterData(DeclLoc);
4868 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004869
Steve Naroff54055232008-10-27 17:20:55 +00004870 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004871
Steve Naroff54055232008-10-27 17:20:55 +00004872 parenCount++;
4873 // advance the location to startArgList.
4874 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4875 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004876
Steve Naroff54055232008-10-27 17:20:55 +00004877 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Steve Naroff54055232008-10-27 17:20:55 +00004879 while (*argPtr++ && parenCount) {
4880 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004881 case '^':
4882 // Replace the '^' with '*'.
4883 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004884 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004885 break;
4886 case '(':
4887 parenCount++;
4888 break;
4889 case ')':
4890 parenCount--;
4891 break;
Steve Naroff54055232008-10-27 17:20:55 +00004892 }
4893 }
4894 return;
4895}
4896
4897bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004898 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004899 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004900 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004901 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004902 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004903 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004904 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004905 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004906 }
4907 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004908 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004909 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004910 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004911 return true;
4912 }
4913 return false;
4914}
4915
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004916bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4917 const FunctionProtoType *FTP;
4918 const PointerType *PT = QT->getAs<PointerType>();
4919 if (PT) {
4920 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4921 } else {
4922 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4923 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4924 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4925 }
4926 if (FTP) {
4927 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004928 E = FTP->arg_type_end(); I != E; ++I) {
4929 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004930 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004931 if ((*I)->isObjCObjectPointerType() &&
4932 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4933 return true;
4934 }
4935
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004936 }
4937 return false;
4938}
4939
Ted Kremenek8189cde2009-02-07 01:47:29 +00004940void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4941 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004942 const char *argPtr = strchr(Name, '(');
4943 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Steve Naroff54055232008-10-27 17:20:55 +00004945 LParen = argPtr; // output the start.
4946 argPtr++; // skip past the left paren.
4947 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004948
Steve Naroff54055232008-10-27 17:20:55 +00004949 while (*argPtr && parenCount) {
4950 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004951 case '(': parenCount++; break;
4952 case ')': parenCount--; break;
4953 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004954 }
4955 if (parenCount) argPtr++;
4956 }
4957 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4958 RParen = argPtr; // output the end
4959}
4960
4961void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4962 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4963 RewriteBlockPointerFunctionArgs(FD);
4964 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004965 }
Steve Naroff54055232008-10-27 17:20:55 +00004966 // Handle Variables and Typedefs.
4967 SourceLocation DeclLoc = ND->getLocation();
4968 QualType DeclT;
4969 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4970 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004971 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004972 DeclT = TDD->getUnderlyingType();
4973 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4974 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004975 else
Steve Naroff54055232008-10-27 17:20:55 +00004976 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Steve Naroff54055232008-10-27 17:20:55 +00004978 const char *startBuf = SM->getCharacterData(DeclLoc);
4979 const char *endBuf = startBuf;
4980 // scan backward (from the decl location) for the end of the previous decl.
4981 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4982 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004983 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4984 std::string buf;
4985 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004986 // *startBuf != '^' if we are dealing with a pointer to function that
4987 // may take block argument types (which will be handled below).
4988 if (*startBuf == '^') {
4989 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004990 buf = '*';
4991 startBuf++;
4992 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004993 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004994 while (*startBuf != ')') {
4995 buf += *startBuf;
4996 startBuf++;
4997 OrigLength++;
4998 }
4999 buf += ')';
5000 OrigLength++;
5001
5002 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5003 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005004 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005005 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005006 DeclLoc = ND->getLocation();
5007 startBuf = SM->getCharacterData(DeclLoc);
5008 const char *argListBegin, *argListEnd;
5009 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5010 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005011 if (*argListBegin == '^')
5012 buf += '*';
5013 else if (*argListBegin == '<') {
5014 buf += "/*";
5015 buf += *argListBegin++;
5016 OrigLength++;;
5017 while (*argListBegin != '>') {
5018 buf += *argListBegin++;
5019 OrigLength++;
5020 }
5021 buf += *argListBegin;
5022 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005023 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005024 else
5025 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005026 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005027 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005028 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005029 buf += ')';
5030 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005031 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005032 ReplaceText(Start, OrigLength, buf);
5033
Steve Naroff54055232008-10-27 17:20:55 +00005034 return;
5035}
5036
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005037
5038/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5039/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5040/// struct Block_byref_id_object *src) {
5041/// _Block_object_assign (&_dest->object, _src->object,
5042/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5043/// [|BLOCK_FIELD_IS_WEAK]) // object
5044/// _Block_object_assign(&_dest->object, _src->object,
5045/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5046/// [|BLOCK_FIELD_IS_WEAK]) // block
5047/// }
5048/// And:
5049/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5050/// _Block_object_dispose(_src->object,
5051/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5052/// [|BLOCK_FIELD_IS_WEAK]) // object
5053/// _Block_object_dispose(_src->object,
5054/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5055/// [|BLOCK_FIELD_IS_WEAK]) // block
5056/// }
5057
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005058std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5059 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005060 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005061 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005062 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005063 CopyDestroyCache.insert(flag);
5064 S = "static void __Block_byref_id_object_copy_";
5065 S += utostr(flag);
5066 S += "(void *dst, void *src) {\n";
5067
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005068 // offset into the object pointer is computed as:
5069 // void * + void* + int + int + void* + void *
5070 unsigned IntSize =
5071 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5072 unsigned VoidPtrSize =
5073 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5074
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005075 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005076 S += " _Block_object_assign((char*)dst + ";
5077 S += utostr(offset);
5078 S += ", *(void * *) ((char*)src + ";
5079 S += utostr(offset);
5080 S += "), ";
5081 S += utostr(flag);
5082 S += ");\n}\n";
5083
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005084 S += "static void __Block_byref_id_object_dispose_";
5085 S += utostr(flag);
5086 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005087 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5088 S += utostr(offset);
5089 S += "), ";
5090 S += utostr(flag);
5091 S += ");\n}\n";
5092 return S;
5093}
5094
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005095/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5096/// the declaration into:
5097/// struct __Block_byref_ND {
5098/// void *__isa; // NULL for everything except __weak pointers
5099/// struct __Block_byref_ND *__forwarding;
5100/// int32_t __flags;
5101/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005102/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5103/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005104/// typex ND;
5105/// };
5106///
5107/// It then replaces declaration of ND variable with:
5108/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5109/// __size=sizeof(struct __Block_byref_ND),
5110/// ND=initializer-if-any};
5111///
5112///
5113void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005114 // Insert declaration for the function in which block literal is
5115 // used.
5116 if (CurFunctionDeclToDeclareForBlock)
5117 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005118 int flag = 0;
5119 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005120 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005121 if (DeclLoc.isInvalid())
5122 // If type location is missing, it is because of missing type (a warning).
5123 // Use variable's location which is good for this case.
5124 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005125 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005126 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005127 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005128 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005129 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005130 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005131 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005132 ByrefType += " {\n";
5133 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005134 RewriteByRefString(ByrefType, Name, ND);
5135 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005136 ByrefType += " int __flags;\n";
5137 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005138 // Add void *__Block_byref_id_object_copy;
5139 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005140 QualType Ty = ND->getType();
5141 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5142 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005143 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5144 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005145 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005146
5147 QualType T = Ty;
5148 (void)convertBlockPointerToFunctionPointer(T);
5149 T.getAsStringInternal(Name, Context->PrintingPolicy);
5150
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005151 ByrefType += " " + Name + ";\n";
5152 ByrefType += "};\n";
5153 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005154 SourceLocation FunLocStart;
5155 if (CurFunctionDef)
5156 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5157 else {
5158 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5159 FunLocStart = CurMethodDef->getLocStart();
5160 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005161 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005162 if (Ty.isObjCGCWeak()) {
5163 flag |= BLOCK_FIELD_IS_WEAK;
5164 isa = 1;
5165 }
5166
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005167 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005168 flag = BLOCK_BYREF_CALLER;
5169 QualType Ty = ND->getType();
5170 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5171 if (Ty->isBlockPointerType())
5172 flag |= BLOCK_FIELD_IS_BLOCK;
5173 else
5174 flag |= BLOCK_FIELD_IS_OBJECT;
5175 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005176 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005177 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005178 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005179
5180 // struct __Block_byref_ND ND =
5181 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5182 // initializer-if-any};
5183 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005184 unsigned flags = 0;
5185 if (HasCopyAndDispose)
5186 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005187 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005188 ByrefType.clear();
5189 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005190 std::string ForwardingCastType("(");
5191 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005192 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005193 ByrefType += " " + Name + " = {(void*)";
5194 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005195 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005196 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005197 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005198 ByrefType += "sizeof(";
5199 RewriteByRefString(ByrefType, Name, ND);
5200 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005201 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005202 ByrefType += ", __Block_byref_id_object_copy_";
5203 ByrefType += utostr(flag);
5204 ByrefType += ", __Block_byref_id_object_dispose_";
5205 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005206 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005207 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005208 unsigned nameSize = Name.size();
5209 // for block or function pointer declaration. Name is aleady
5210 // part of the declaration.
5211 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5212 nameSize = 1;
5213 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005214 }
5215 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005216 SourceLocation startLoc;
5217 Expr *E = ND->getInit();
5218 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5219 startLoc = ECE->getLParenLoc();
5220 else
5221 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005222 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005223 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005224 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005225 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005226 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005227 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005228 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005229 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005230 ByrefType += "sizeof(";
5231 RewriteByRefString(ByrefType, Name, ND);
5232 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005233 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005234 ByrefType += "__Block_byref_id_object_copy_";
5235 ByrefType += utostr(flag);
5236 ByrefType += ", __Block_byref_id_object_dispose_";
5237 ByrefType += utostr(flag);
5238 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005239 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005240 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005241
5242 // Complete the newly synthesized compound expression by inserting a right
5243 // curly brace before the end of the declaration.
5244 // FIXME: This approach avoids rewriting the initializer expression. It
5245 // also assumes there is only one declarator. For example, the following
5246 // isn't currently supported by this routine (in general):
5247 //
5248 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5249 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005250 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5251 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005252 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5253 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005254 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005255
Benjamin Kramerd999b372010-02-14 14:14:16 +00005256 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005257 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005258 return;
5259}
5260
Mike Stump1eb44332009-09-09 15:08:12 +00005261void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005262 // Add initializers for any closure decl refs.
5263 GetBlockDeclRefExprs(Exp->getBody());
5264 if (BlockDeclRefs.size()) {
5265 // Unique all "by copy" declarations.
5266 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005267 if (!BlockDeclRefs[i]->isByRef()) {
5268 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5269 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5270 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5271 }
5272 }
Steve Naroff54055232008-10-27 17:20:55 +00005273 // Unique all "by ref" declarations.
5274 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5275 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005276 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5277 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5278 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5279 }
Steve Naroff54055232008-10-27 17:20:55 +00005280 }
5281 // Find any imported blocks...they will need special attention.
5282 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005283 if (BlockDeclRefs[i]->isByRef() ||
5284 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005285 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005286 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005287 }
5288}
5289
Chris Lattner5f9e2722011-07-23 10:55:15 +00005290FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005291 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005292 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005293 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5294 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005295 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005296}
5297
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005298Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005299 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005300 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005301 Blocks.push_back(Exp);
5302
5303 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005304
5305 // Add inner imported variables now used in current block.
5306 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005307 if (!InnerBlockDeclRefs.empty()) {
5308 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5309 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5310 ValueDecl *VD = Exp->getDecl();
5311 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005312 // We need to save the copied-in variables in nested
5313 // blocks because it is needed at the end for some of the API generations.
5314 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005315 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5316 BlockDeclRefs.push_back(Exp);
5317 BlockByCopyDeclsPtrSet.insert(VD);
5318 BlockByCopyDecls.push_back(VD);
5319 }
5320 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5321 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5322 BlockDeclRefs.push_back(Exp);
5323 BlockByRefDeclsPtrSet.insert(VD);
5324 BlockByRefDecls.push_back(VD);
5325 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005326 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005327 // Find any imported blocks...they will need special attention.
5328 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5329 if (InnerBlockDeclRefs[i]->isByRef() ||
5330 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5331 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5332 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005333 }
5334 InnerDeclRefsCount.push_back(countOfInnerDecls);
5335
Steve Narofffa15fd92008-10-28 20:29:00 +00005336 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005337
Steve Narofffa15fd92008-10-28 20:29:00 +00005338 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005339 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005340 else if (CurMethodDef)
5341 BuildUniqueMethodName(FuncName, CurMethodDef);
5342 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005343 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005344
Steve Narofffa15fd92008-10-28 20:29:00 +00005345 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005346
Steve Narofffa15fd92008-10-28 20:29:00 +00005347 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5348 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005349
Steve Narofffa15fd92008-10-28 20:29:00 +00005350 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005351 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5352 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005353
5354 FunctionDecl *FD;
5355 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005356
Steve Narofffa15fd92008-10-28 20:29:00 +00005357 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005358 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005359 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5360 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005361
Chris Lattner5f9e2722011-07-23 10:55:15 +00005362 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005363
Steve Narofffdc03722008-10-29 21:23:59 +00005364 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005365 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005366 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005367 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005368 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005369 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005370 InitExprs.push_back(castExpr);
5371
Steve Naroff01aec112009-12-06 21:14:13 +00005372 // Initialize the block descriptor.
5373 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005374
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005375 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5376 SourceLocation(), SourceLocation(),
5377 &Context->Idents.get(DescData.c_str()),
5378 Context->VoidPtrTy, 0,
5379 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005380 UnaryOperator *DescRefExpr =
5381 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5382 Context->VoidPtrTy,
5383 VK_LValue,
5384 SourceLocation()),
5385 UO_AddrOf,
5386 Context->getPointerType(Context->VoidPtrTy),
5387 VK_RValue, OK_Ordinary,
5388 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005389 InitExprs.push_back(DescRefExpr);
5390
Steve Narofffa15fd92008-10-28 20:29:00 +00005391 // Add initializers for any closure decl refs.
5392 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005393 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005394 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005395 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005396 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005397 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005398 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005399 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005400 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5401 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005402 if (HasLocalVariableExternalStorage(*I)) {
5403 QualType QT = (*I)->getType();
5404 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005405 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5406 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005407 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005408 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005409 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005410 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5411 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005412 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005413 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005415 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005416 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5417 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005418 if (HasLocalVariableExternalStorage(*I)) {
5419 QualType QT = (*I)->getType();
5420 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005421 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5422 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005423 }
5424
Steve Narofffa15fd92008-10-28 20:29:00 +00005425 }
Mike Stump1eb44332009-09-09 15:08:12 +00005426 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005427 }
5428 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005429 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005430 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005431 ValueDecl *ND = (*I);
5432 std::string Name(ND->getNameAsString());
5433 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005434 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005435 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5436 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005437 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005438 SourceLocation(), SourceLocation(),
5439 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005440 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5441 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5442
Daniel Dunbar4087f272010-08-17 22:39:59 +00005443 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005444 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5445 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005446 bool isNestedCapturedVar = false;
5447 if (block)
5448 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5449 ce = block->capture_end(); ci != ce; ++ci) {
5450 const VarDecl *variable = ci->getVariable();
5451 if (variable == ND && ci->isNested()) {
5452 assert (ci->isByRef() &&
5453 "SynthBlockInitExpr - captured block variable is not byref");
5454 isNestedCapturedVar = true;
5455 break;
5456 }
5457 }
5458 // captured nested byref variable has its address passed. Do not take
5459 // its address again.
5460 if (!isNestedCapturedVar)
5461 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005462 Context->getPointerType(Exp->getType()),
5463 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005464 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005465 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 }
5467 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005468 if (ImportedBlockDecls.size()) {
5469 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5470 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005471 unsigned IntSize =
5472 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005473 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5474 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005475 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005476 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005477 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005478 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005479 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005480 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005481 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005482 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005483 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005484 BlockDeclRefs.clear();
5485 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005486 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005487 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005488 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005489 ImportedBlockDecls.clear();
5490 return NewRep;
5491}
5492
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005493bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5494 if (const ObjCForCollectionStmt * CS =
5495 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5496 return CS->getElement() == DS;
5497 return false;
5498}
5499
Steve Narofffa15fd92008-10-28 20:29:00 +00005500//===----------------------------------------------------------------------===//
5501// Function Body / Expression rewriting
5502//===----------------------------------------------------------------------===//
5503
Steve Naroffc77a6362008-12-04 16:24:46 +00005504// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5505// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5506// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5507// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5508// Since the rewriter isn't capable of rewriting rewritten code, it's important
5509// we get this right.
5510void RewriteObjC::CollectPropertySetters(Stmt *S) {
5511 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005512 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005513 if (*CI)
5514 CollectPropertySetters(*CI);
5515
5516 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5517 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005518 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5519 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005520 }
5521 }
5522}
5523
Steve Narofffa15fd92008-10-28 20:29:00 +00005524Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005525 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005526 isa<DoStmt>(S) || isa<ForStmt>(S))
5527 Stmts.push_back(S);
5528 else if (isa<ObjCForCollectionStmt>(S)) {
5529 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005530 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005531 }
Mike Stump1eb44332009-09-09 15:08:12 +00005532
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005534
Steve Narofffa15fd92008-10-28 20:29:00 +00005535 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005536 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005537 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005538 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005539 Stmt *ChildStmt = (*CI);
5540 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005541 Expr *OldBase = IvarRefExpr->getBase();
5542 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005543 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005544 if (replaced) {
5545 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5546 ReplaceStmt(OldBase, IRE->getBase());
5547 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005548 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005549 }
5550 }
5551 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005552 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5553 if (newStmt) {
5554 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5555 if (PropSetters[PropOrImplicitRefExpr] == S) {
5556 S = newStmt;
5557 newStmt = 0;
5558 }
5559 if (newStmt)
5560 *CI = newStmt;
5561 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005562 // If dealing with an assignment with LHS being a property reference
5563 // expression, the entire assignment tree is rewritten into a property
5564 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5565 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005566 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005567 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005568 if (PropSetters[Exp]) {
5569 ++CI;
5570 continue;
5571 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005572 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005573 }
Mike Stump1eb44332009-09-09 15:08:12 +00005574
Steve Narofffa15fd92008-10-28 20:29:00 +00005575 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005576 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005577 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5578 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005579 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005580 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005581 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005582 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005583 Stmt *SaveCurrentBody = CurrentBody;
5584 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005585 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005586 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005587 // block literal on rhs of a property-dot-sytax assignment
5588 // must be replaced by its synthesize ast so getRewrittenText
5589 // works as expected. In this case, what actually ends up on RHS
5590 // is the blockTranscribed which is the helper function for the
5591 // block literal; as in: self.c = ^() {[ace ARR];};
5592 bool saveDisableReplaceStmt = DisableReplaceStmt;
5593 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005594 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005595 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005596 CurrentBody = SaveCurrentBody;
5597 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005598 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005599 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005600 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005601 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005602
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005603 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5604
Steve Narofffa15fd92008-10-28 20:29:00 +00005605 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005606 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 return blockTranscribed;
5608 }
5609 // Handle specific things.
5610 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5611 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005612
John McCall12f78a62010-12-02 01:19:52 +00005613 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005614 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5615 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5616
5617 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005618 if (BinOp) {
5619 // Because the rewriter doesn't allow us to rewrite rewritten code,
5620 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005621 DisableReplaceStmt = true;
5622 // Save the source range. Even if we disable the replacement, the
5623 // rewritten node will have been inserted into the tree. If the synthesized
5624 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005625 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005626 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5627 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005628 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005629 // Need to rewrite the ivar access expression if need be.
5630 if (isa<ObjCIvarRefExpr>(newStmt)) {
5631 bool replaced = false;
5632 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5633 }
5634
Steve Naroffb619d952008-12-09 12:56:34 +00005635 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005636 //
5637 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5638 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5639 // to see the original expression). Consider this example:
5640 //
5641 // Foo *obj1, *obj2;
5642 //
5643 // obj1.i = [obj2 rrrr];
5644 //
5645 // 'BinOp' for the previous expression looks like:
5646 //
5647 // (BinaryOperator 0x231ccf0 'int' '='
5648 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5649 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5650 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5651 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5652 //
5653 // 'newStmt' represents the rewritten message expression. For example:
5654 //
5655 // (CallExpr 0x231d300 'id':'struct objc_object *'
5656 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5657 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5658 // (CStyleCastExpr 0x231d220 'void *'
5659 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5660 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005661 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005662 // can be used as the setter argument. ReplaceStmt() will still 'see'
5663 // the original RHS (since we haven't altered BinOp).
5664 //
Mike Stump1eb44332009-09-09 15:08:12 +00005665 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005666 // node. As a result, we now leak the original AST nodes.
5667 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005668 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005669 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005670 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005671 }
5672 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005673
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5675 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005676
Steve Narofffa15fd92008-10-28 20:29:00 +00005677 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5678 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005679
Steve Narofffa15fd92008-10-28 20:29:00 +00005680 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005681#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 // Before we rewrite it, put the original message expression in a comment.
5683 SourceLocation startLoc = MessExpr->getLocStart();
5684 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005685
Steve Narofffa15fd92008-10-28 20:29:00 +00005686 const char *startBuf = SM->getCharacterData(startLoc);
5687 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005688
Steve Narofffa15fd92008-10-28 20:29:00 +00005689 std::string messString;
5690 messString += "// ";
5691 messString.append(startBuf, endBuf-startBuf+1);
5692 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005693
5694 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 // InsertText(clang::SourceLocation, char const*, unsigned int).
5696 // InsertText(startLoc, messString.c_str(), messString.size());
5697 // Tried this, but it didn't work either...
5698 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005699#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005700 return RewriteMessageExpr(MessExpr);
5701 }
Mike Stump1eb44332009-09-09 15:08:12 +00005702
Steve Narofffa15fd92008-10-28 20:29:00 +00005703 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5704 return RewriteObjCTryStmt(StmtTry);
5705
5706 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5707 return RewriteObjCSynchronizedStmt(StmtTry);
5708
5709 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5710 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005711
Steve Narofffa15fd92008-10-28 20:29:00 +00005712 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5713 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005714
5715 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005717 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005718 OrigStmtRange.getEnd());
5719 if (BreakStmt *StmtBreakStmt =
5720 dyn_cast<BreakStmt>(S))
5721 return RewriteBreakStmt(StmtBreakStmt);
5722 if (ContinueStmt *StmtContinueStmt =
5723 dyn_cast<ContinueStmt>(S))
5724 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005725
5726 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005727 // and cast exprs.
5728 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5729 // FIXME: What we're doing here is modifying the type-specifier that
5730 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005731 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005732 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5733 // the context of an ObjCForCollectionStmt. For example:
5734 // NSArray *someArray;
5735 // for (id <FooProtocol> index in someArray) ;
5736 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5737 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005738 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005739 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005740
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 // Blocks rewrite rules.
5742 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5743 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005744 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005745 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005746 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005747 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005748 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005750 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005751 if (VD->hasAttr<BlocksAttr>()) {
5752 static unsigned uniqueByrefDeclCount = 0;
5753 assert(!BlockByRefDeclNo.count(ND) &&
5754 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5755 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005756 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005757 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005758 else
5759 RewriteTypeOfDecl(VD);
5760 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005761 }
Richard Smith162e1c12011-04-15 14:24:37 +00005762 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005763 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005765 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005766 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5767 }
5768 }
5769 }
Mike Stump1eb44332009-09-09 15:08:12 +00005770
Steve Narofffa15fd92008-10-28 20:29:00 +00005771 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5772 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005773
5774 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005775 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5776 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005777 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5778 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005779 && "Statement stack mismatch");
5780 Stmts.pop_back();
5781 }
5782 // Handle blocks rewriting.
5783 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5784 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005785 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005786 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005787 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5788 ValueDecl *VD = DRE->getDecl();
5789 if (VD->hasAttr<BlocksAttr>())
5790 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005791 if (HasLocalVariableExternalStorage(VD))
5792 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005793 }
5794
Steve Narofffa15fd92008-10-28 20:29:00 +00005795 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005796 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005797 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005798 ReplaceStmt(S, BlockCall);
5799 return BlockCall;
5800 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005801 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005802 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005803 RewriteCastExpr(CE);
5804 }
5805#if 0
5806 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005807 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5808 ICE->getSubExpr(),
5809 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005810 // Get the new text.
5811 std::string SStr;
5812 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005813 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005814 const std::string &Str = Buf.str();
5815
5816 printf("CAST = %s\n", &Str[0]);
5817 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5818 delete S;
5819 return Replacement;
5820 }
5821#endif
5822 // Return this stmt unmodified.
5823 return S;
5824}
5825
Steve Naroff3d7e7862009-12-05 15:55:59 +00005826void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5827 for (RecordDecl::field_iterator i = RD->field_begin(),
5828 e = RD->field_end(); i != e; ++i) {
5829 FieldDecl *FD = *i;
5830 if (isTopLevelBlockPointerType(FD->getType()))
5831 RewriteBlockPointerDecl(FD);
5832 if (FD->getType()->isObjCQualifiedIdType() ||
5833 FD->getType()->isObjCQualifiedInterfaceType())
5834 RewriteObjCQualifiedInterfaceTypes(FD);
5835 }
5836}
5837
Steve Narofffa15fd92008-10-28 20:29:00 +00005838/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5839/// main file of the input.
5840void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5841 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005842 if (FD->isOverloadedOperator())
5843 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005844
Steve Narofffa15fd92008-10-28 20:29:00 +00005845 // Since function prototypes don't have ParmDecl's, we check the function
5846 // prototype. This enables us to rewrite function declarations and
5847 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005848 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005849
Sebastian Redld3a413d2009-04-26 20:35:05 +00005850 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005851 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005852 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005853 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005854 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005855 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005856 Body =
5857 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5858 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005859 CurrentBody = 0;
5860 if (PropParentMap) {
5861 delete PropParentMap;
5862 PropParentMap = 0;
5863 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005864 // This synthesizes and inserts the block "impl" struct, invoke function,
5865 // and any copy/dispose helper functions.
5866 InsertBlockLiteralsWithinFunction(FD);
5867 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005868 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005869 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005870 return;
5871 }
5872 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005873 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005874 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005875 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005876 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005877 Body =
5878 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5879 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005880 CurrentBody = 0;
5881 if (PropParentMap) {
5882 delete PropParentMap;
5883 PropParentMap = 0;
5884 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005885 InsertBlockLiteralsWithinMethod(MD);
5886 CurMethodDef = 0;
5887 }
5888 }
5889 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5890 ClassImplementation.push_back(CI);
5891 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5892 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005893 else if (isa<ObjCClassDecl>(D))
5894 assert(false && "RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005895 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5896 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005897 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005898 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005899 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005900 CheckFunctionPointerDecl(VD->getType(), VD);
5901 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005902 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005903 RewriteCastExpr(CE);
5904 }
5905 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005906 } else if (VD->getType()->isRecordType()) {
5907 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5908 if (RD->isDefinition())
5909 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005910 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005911 if (VD->getInit()) {
5912 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005913 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005914 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005915 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005916 CurrentBody = 0;
5917 if (PropParentMap) {
5918 delete PropParentMap;
5919 PropParentMap = 0;
5920 }
Mike Stump1eb44332009-09-09 15:08:12 +00005921 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005922 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005923 GlobalVarDecl = 0;
5924
5925 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005926 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005927 RewriteCastExpr(CE);
5928 }
5929 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005930 return;
5931 }
Richard Smith162e1c12011-04-15 14:24:37 +00005932 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005933 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005934 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005935 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005936 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5937 return;
5938 }
5939 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005940 if (RD->isDefinition())
5941 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005942 return;
5943 }
5944 // Nothing yet.
5945}
5946
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005947void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005948 if (Diags.hasErrorOccurred())
5949 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005950
Steve Narofffa15fd92008-10-28 20:29:00 +00005951 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005952
Steve Naroff621edce2009-04-29 16:37:50 +00005953 // Here's a great place to add any extra declarations that may be needed.
5954 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005955 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005956 E = ProtocolExprDecls.end(); I != E; ++I)
5957 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5958
Benjamin Kramerd999b372010-02-14 14:14:16 +00005959 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005960 if (ClassImplementation.size() || CategoryImplementation.size())
5961 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005962
Steve Narofffa15fd92008-10-28 20:29:00 +00005963 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5964 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005965 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005966 Rewrite.getRewriteBufferFor(MainFileID)) {
5967 //printf("Changed:\n");
5968 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5969 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005970 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005971 }
Steve Narofface66252008-11-13 20:07:04 +00005972
Steve Naroff621edce2009-04-29 16:37:50 +00005973 if (ClassImplementation.size() || CategoryImplementation.size() ||
5974 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005975 // Rewrite Objective-c meta data*
5976 std::string ResultStr;
5977 SynthesizeMetaDataIntoBuffer(ResultStr);
5978 // Emit metadata.
5979 *OutFile << ResultStr;
5980 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005981 OutFile->flush();
5982}