blob: 1b7fb2dfc42214fd0d9bfc259b2b94acf017d39c [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);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000250 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
251 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
252 const std::string &typedefString);
253
Steve Naroffa0876e82008-12-02 17:36:43 +0000254 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
255 ObjCImplementationDecl *IMD,
256 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000258 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000259 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
260 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000264 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000278 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000280 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000281 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000284 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000285 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Steve Naroff8599e7a2008-12-08 16:43:47 +0000287 Stmt *CurrentBody;
288 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnere64b7772007-10-24 16:57:36 +0000290 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000291 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
292 bool &replaced);
293 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000294 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
295 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000296 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000297 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000298 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000299 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000300 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000301 void WarnAboutReturnGotoStmts(Stmt *S);
302 void HasReturnStmts(Stmt *S, bool &hasReturns);
303 void RewriteTryReturnStmts(Stmt *S);
304 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000306 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000310 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000311 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000312 Expr **args, unsigned nargs,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
315 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
316 SourceLocation StartLoc=SourceLocation(),
317 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000320 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Steve Naroff09b266e2007-10-30 23:14:51 +0000322 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000323 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000324 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000325 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000326 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000327 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000328 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000329 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000330 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000331 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerf04da132007-10-24 17:06:59 +0000333 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000337 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000338 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor653f1b12009-04-23 01:02:12 +0000340 template<typename MethodIterator>
341 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
342 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000343 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef prefix,
345 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000346 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff621edce2009-04-29 16:37:50 +0000348 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 StringRef prefix,
350 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000351 std::string &Result);
352 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000353 StringRef prefix,
354 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000355 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000356 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000357 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000358 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000372 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000373 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000374 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000375 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
378 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000382 std::string SynthesizeBlockImpl(BlockExpr *CE,
383 std::string Tag, std::string Desc);
384 std::string SynthesizeBlockDescriptor(std::string DescTag,
385 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000387 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000388 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000389 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000391 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000395 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000397 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Steve Naroff54055232008-10-27 17:20:55 +0000399 // We avoid calling Type::isBlockPointerType(), since it operates on the
400 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 bool isTopLevelBlockPointerType(QualType T) {
402 return isa<BlockPointerType>(T);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000405 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
406 /// to a function pointer type and upon success, returns true; false
407 /// otherwise.
408 bool convertBlockPointerToFunctionPointer(QualType &T) {
409 if (isTopLevelBlockPointerType(T)) {
410 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
411 T = Context->getPointerType(BPT->getPointeeType());
412 return true;
413 }
414 return false;
415 }
416
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000417 void convertToUnqualifiedObjCType(QualType &T) {
418 if (T->isObjCQualifiedIdType())
419 T = Context->getObjCIdType();
420 else if (T->isObjCQualifiedClassType())
421 T = Context->getObjCClassType();
422 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000423 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
424 if (const ObjCObjectPointerType * OBJPT =
425 T->getAsObjCInterfacePointerType()) {
426 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
427 T = QualType(IFaceT, 0);
428 T = Context->getPointerType(T);
429 }
430 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000431 }
432
Steve Naroff54055232008-10-27 17:20:55 +0000433 // FIXME: This predicate seems like it would be useful to add to ASTContext.
434 bool isObjCType(QualType T) {
435 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Steve Naroff54055232008-10-27 17:20:55 +0000438 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Steve Naroff54055232008-10-27 17:20:55 +0000440 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
441 OCT == Context->getCanonicalType(Context->getObjCClassType()))
442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek6217b802009-07-29 21:53:49 +0000444 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000446 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000447 return true;
448 }
449 return false;
450 }
451 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000452 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000453 void GetExtentOfArgList(const char *Name, const char *&LParen,
454 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000455 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000458 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000459 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff621edce2009-04-29 16:37:50 +0000461 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000462 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000463 if (From[i] == '"')
464 To += "\\\"";
465 else
466 To += From[i];
467 }
468 }
John McCalle23cf432010-12-14 08:05:40 +0000469
470 QualType getSimpleFunctionType(QualType result,
471 const QualType *args,
472 unsigned numArgs,
473 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000474 if (result == Context->getObjCInstanceType())
475 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000476 FunctionProtoType::ExtProtoInfo fpi;
477 fpi.Variadic = variadic;
478 return Context->getFunctionType(result, args, numArgs, fpi);
479 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000480 };
John McCall9d125032010-01-15 18:39:57 +0000481
482 // Helper function: create a CStyleCastExpr with trivial type source info.
483 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000484 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000485 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000486 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000487 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000488 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000489}
490
Mike Stump1eb44332009-09-09 15:08:12 +0000491void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
492 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000493 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000494 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000496 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000497 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000498 // All the args are checked/rewritten. Don't call twice!
499 RewriteBlockPointerDecl(D);
500 break;
501 }
502 }
503}
504
505void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000507 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000508 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000509}
510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511static bool IsHeaderFile(const std::string &Filename) {
512 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000514 if (DotPos == std::string::npos) {
515 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000516 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000519 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
520 // C header: .h
521 // C++ header: .hh or .H;
522 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000523}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000526 Diagnostic &D, const LangOptions &LOpts,
527 bool silenceMacroWarn)
528 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
529 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000530 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000531 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000532 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000533 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 "rewriter doesn't support user-specified control flow semantics "
535 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000536}
537
Eli Friedmanbce831b2009-05-18 22:29:17 +0000538ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000539 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000540 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000541 const LangOptions &LOpts,
542 bool SilenceRewriteMacroWarning) {
543 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000544}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000545
Steve Naroffb29b4272008-04-14 22:03:09 +0000546void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000547 Context = &context;
548 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000549 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550 MsgSendFunctionDecl = 0;
551 MsgSendSuperFunctionDecl = 0;
552 MsgSendStretFunctionDecl = 0;
553 MsgSendSuperStretFunctionDecl = 0;
554 MsgSendFpretFunctionDecl = 0;
555 GetClassFunctionDecl = 0;
556 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000557 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 SelGetUidFunctionDecl = 0;
559 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000560 ConstantStringClassReference = 0;
561 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000562 CurMethodDef = 0;
563 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000564 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000565 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000566 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000567 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000568 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000569 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000570 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000571 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000572 PropParentMap = 0;
573 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000574 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000575 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000577 // Get the ID and start/end of the main file.
578 MainFileID = SM->getMainFileID();
579 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
580 MainFileStart = MainBuf->getBufferStart();
581 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000582
Chris Lattner2c78b872009-04-14 23:22:57 +0000583 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000585 // declaring objc_selector outside the parameter list removes a silly
586 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000587 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000588 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000589 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000590 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000592 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000593 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000594 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
595 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000597 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
600 Preamble += "typedef struct objc_object Protocol;\n";
601 Preamble += "#define _REWRITER_typedef_Protocol\n";
602 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000603 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
605 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
606 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000607 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000608 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000611 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000613 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000616 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000617 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000618 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000619 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000620 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
621 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000622 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000623 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000624 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
625 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000629 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000630 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000631 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
632 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000634 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
635 Preamble += "struct __objcFastEnumerationState {\n\t";
636 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000637 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000638 Preamble += "unsigned long *mutationsPtr;\n\t";
639 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000640 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000641 Preamble += "#define __FASTENUMERATIONSTATE\n";
642 Preamble += "#endif\n";
643 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
644 Preamble += "struct __NSConstantStringImpl {\n";
645 Preamble += " int *isa;\n";
646 Preamble += " int flags;\n";
647 Preamble += " char *str;\n";
648 Preamble += " long length;\n";
649 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000650 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
651 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
652 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000653 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000654 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000655 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
656 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000657 // Blocks preamble.
658 Preamble += "#ifndef BLOCK_IMPL\n";
659 Preamble += "#define BLOCK_IMPL\n";
660 Preamble += "struct __block_impl {\n";
661 Preamble += " void *isa;\n";
662 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000663 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000664 Preamble += " void *FuncPtr;\n";
665 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000666 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000667 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000668 Preamble += "extern \"C\" __declspec(dllexport) "
669 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000670 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
671 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
672 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
673 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000674 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
675 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000676 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
677 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
678 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000679 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000680 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000681 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
682 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000683 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000684 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000685 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000686 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000687 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000688 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000689 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000690 Preamble += "#define __weak\n";
691 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000692 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
693 // as this avoids warning in any 64bit/32bit compilation model.
694 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000695}
696
697
Chris Lattnerf04da132007-10-24 17:06:59 +0000698//===----------------------------------------------------------------------===//
699// Top Level Driver Code
700//===----------------------------------------------------------------------===//
701
Chris Lattner682bf922009-03-29 16:50:03 +0000702void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000703 if (Diags.hasErrorOccurred())
704 return;
705
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000706 // Two cases: either the decl could be in the main file, or it could be in a
707 // #included file. If the former, rewrite it now. If the later, check to see
708 // if we rewrote the #include/#import.
709 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000710 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000712 // If this is for a builtin, ignore it.
713 if (Loc.isInvalid()) return;
714
Steve Naroffebf2b562007-10-23 23:50:29 +0000715 // Look for built-in declarations that we need to refer during the rewrite.
716 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000717 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000718 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000719 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000720 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000721 ConstantStringClassReference = FVD;
722 return;
723 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000724 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000725 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000726 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000727 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000728 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000729 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000730 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000731 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000732 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000733 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
734 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000735 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
736 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000737 DI != DIEnd; ) {
738 if (isa<ObjCClassDecl>((*DI))) {
739 SmallVector<Decl *, 8> DG;
740 Decl *D = (*DI);
741 SourceLocation Loc = D->getLocation();
742 while (DI != DIEnd &&
743 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
744 DG.push_back(D);
745 ++DI;
746 D = (*DI);
747 }
748 RewriteForwardClassDecl(DG);
749 continue;
750 }
Chris Lattner682bf922009-03-29 16:50:03 +0000751 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000752 ++DI;
753 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000754 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000755 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000756 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000757 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000758}
759
Chris Lattnerf04da132007-10-24 17:06:59 +0000760//===----------------------------------------------------------------------===//
761// Syntactic (non-AST) Rewriting Code
762//===----------------------------------------------------------------------===//
763
Steve Naroffb29b4272008-04-14 22:03:09 +0000764void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000765 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000766 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000767 const char *MainBufStart = MainBuf.begin();
768 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000769 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000771 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000772 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
773 if (*BufPtr == '#') {
774 if (++BufPtr == MainBufEnd)
775 return;
776 while (*BufPtr == ' ' || *BufPtr == '\t')
777 if (++BufPtr == MainBufEnd)
778 return;
779 if (!strncmp(BufPtr, "import", ImportLen)) {
780 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000781 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000782 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000783 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000784 BufPtr += ImportLen;
785 }
786 }
787 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000788}
789
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000790static std::string getIvarAccessString(ObjCIvarDecl *OID) {
791 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 std::string S;
793 S = "((struct ";
794 S += ClassDecl->getIdentifier()->getName();
795 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000796 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000797 return S;
798}
799
Steve Naroffa0876e82008-12-02 17:36:43 +0000800void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
801 ObjCImplementationDecl *IMD,
802 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000803 static bool objcGetPropertyDefined = false;
804 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000805 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000806 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000807 const char *startBuf = SM->getCharacterData(startLoc);
808 assert((*startBuf == '@') && "bogus @synthesize location");
809 const char *semiBuf = strchr(startBuf, ';');
810 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000811 SourceLocation onePastSemiLoc =
812 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000813
814 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
815 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Steve Naroffeb0646c2008-12-02 15:48:25 +0000817 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000818 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000819 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000821 if (!OID)
822 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000823 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000824 if (!PD->getGetterMethodDecl()->isDefined()) {
825 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
826 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
827 ObjCPropertyDecl::OBJC_PR_copy));
828 std::string Getr;
829 if (GenGetProperty && !objcGetPropertyDefined) {
830 objcGetPropertyDefined = true;
831 // FIXME. Is this attribute correct in all cases?
832 Getr = "\nextern \"C\" __declspec(dllimport) "
833 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000834 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000835 RewriteObjCMethodDecl(OID->getContainingInterface(),
836 PD->getGetterMethodDecl(), Getr);
837 Getr += "{ ";
838 // Synthesize an explicit cast to gain access to the ivar.
839 // See objc-act.c:objc_synthesize_new_getter() for details.
840 if (GenGetProperty) {
841 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
842 Getr += "typedef ";
843 const FunctionType *FPRetType = 0;
844 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
845 FPRetType);
846 Getr += " _TYPE";
847 if (FPRetType) {
848 Getr += ")"; // close the precedence "scope" for "*".
849
850 // Now, emit the argument types (if any).
851 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
852 Getr += "(";
853 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
854 if (i) Getr += ", ";
855 std::string ParamStr = FT->getArgType(i).getAsString(
856 Context->PrintingPolicy);
857 Getr += ParamStr;
858 }
859 if (FT->isVariadic()) {
860 if (FT->getNumArgs()) Getr += ", ";
861 Getr += "...";
862 }
863 Getr += ")";
864 } else
865 Getr += "()";
866 }
867 Getr += ";\n";
868 Getr += "return (_TYPE)";
869 Getr += "objc_getProperty(self, _cmd, ";
870 SynthesizeIvarOffsetComputation(OID, Getr);
871 Getr += ", 1)";
872 }
873 else
874 Getr += "return " + getIvarAccessString(OID);
875 Getr += "; }";
876 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000877 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000878
879 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000880 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Steve Naroffeb0646c2008-12-02 15:48:25 +0000882 // Generate the 'setter' function.
883 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
885 ObjCPropertyDecl::OBJC_PR_copy);
886 if (GenSetProperty && !objcSetPropertyDefined) {
887 objcSetPropertyDefined = true;
888 // FIXME. Is this attribute correct in all cases?
889 Setr = "\nextern \"C\" __declspec(dllimport) "
890 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
891 }
892
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000893 RewriteObjCMethodDecl(OID->getContainingInterface(),
894 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000895 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000896 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000897 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000898 if (GenSetProperty) {
899 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000900 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000901 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000902 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000903 Setr += ", ";
904 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
905 Setr += "0, ";
906 else
907 Setr += "1, ";
908 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
909 Setr += "1)";
910 else
911 Setr += "0)";
912 }
913 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000914 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000915 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000916 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000917 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000918 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000919}
Chris Lattner8a12c272007-10-11 18:38:32 +0000920
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000921static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
922 std::string &typedefString) {
923 typedefString += "#ifndef _REWRITER_typedef_";
924 typedefString += ForwardDecl->getNameAsString();
925 typedefString += "\n";
926 typedefString += "#define _REWRITER_typedef_";
927 typedefString += ForwardDecl->getNameAsString();
928 typedefString += "\n";
929 typedefString += "typedef struct objc_object ";
930 typedefString += ForwardDecl->getNameAsString();
931 typedefString += ";\n#endif\n";
932}
933
934void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
935 const std::string &typedefString) {
936 SourceLocation startLoc = ClassDecl->getLocation();
937 const char *startBuf = SM->getCharacterData(startLoc);
938 const char *semiPtr = strchr(startBuf, ';');
939 // Replace the @class with typedefs corresponding to the classes.
940 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
941}
942
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000943void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000944 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000945 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
946 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
947 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
948 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000949 // Translate to typedef's that forward reference structs with the same name
950 // as the class. As a convenience, we include the original declaration
951 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000952 typedefString += "// @class ";
953 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000954 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000955 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000956 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000957 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000958 DeclGroupRef::iterator I = D.begin();
959 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
960}
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000962void RewriteObjC::RewriteForwardClassDecl(
963 const llvm::SmallVector<Decl*, 8> &D) {
964 std::string typedefString;
965 for (unsigned i = 0; i < D.size(); i++) {
966 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
967 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
968 if (i == 0) {
969 typedefString += "// @class ";
970 typedefString += ForwardDecl->getNameAsString();
971 typedefString += ";\n";
972 }
973 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
974 }
975 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000976}
977
Steve Naroffb29b4272008-04-14 22:03:09 +0000978void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000979 // When method is a synthesized one, such as a getter/setter there is
980 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000981 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000982 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000983 SourceLocation LocStart = Method->getLocStart();
984 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chandler Carruth64211622011-07-25 21:09:52 +0000986 if (SM->getExpansionLineNumber(LocEnd) >
987 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000988 InsertText(LocStart, "#if 0\n");
989 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000990 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000991 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000992 }
993}
994
Mike Stump1eb44332009-09-09 15:08:12 +0000995void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000996 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000999 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001000}
1001
Steve Naroffb29b4272008-04-14 22:03:09 +00001002void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001003 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Steve Naroff423cb562007-10-30 13:30:57 +00001005 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001006 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001008 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1009 E = CatDecl->prop_end(); I != E; ++I)
1010 RewriteProperty(*I);
1011
Mike Stump1eb44332009-09-09 15:08:12 +00001012 for (ObjCCategoryDecl::instmeth_iterator
1013 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001014 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001015 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001016 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001017 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001018 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001019 RewriteMethodDeclaration(*I);
1020
Steve Naroff423cb562007-10-30 13:30:57 +00001021 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001022 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1023 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001024}
1025
Steve Naroffb29b4272008-04-14 22:03:09 +00001026void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001027 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Steve Naroff752d6ef2007-10-30 16:42:30 +00001029 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001030 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001031
1032 for (ObjCProtocolDecl::instmeth_iterator
1033 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001034 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001035 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001036 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001037 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001038 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001039 RewriteMethodDeclaration(*I);
1040
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001041 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1042 E = PDecl->prop_end(); I != E; ++I)
1043 RewriteProperty(*I);
1044
Steve Naroff752d6ef2007-10-30 16:42:30 +00001045 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001046 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001047 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001048
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001049 // Must comment out @optional/@required
1050 const char *startBuf = SM->getCharacterData(LocStart);
1051 const char *endBuf = SM->getCharacterData(LocEnd);
1052 for (const char *p = startBuf; p < endBuf; p++) {
1053 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001054 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001055 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001057 }
1058 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001059 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001060 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001062 }
1063 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001064}
1065
Steve Naroffb29b4272008-04-14 22:03:09 +00001066void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001067 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001068 if (LocStart.isInvalid())
1069 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001070 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001071 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001072}
1073
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001074void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1075 const FunctionType *&FPRetType) {
1076 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001077 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001078 else if (T->isFunctionPointerType() ||
1079 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001080 // needs special handling, since pointer-to-functions have special
1081 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001082 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001083 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001084 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001085 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001086 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001087 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001088 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001089 ResultStr += FPRetType->getResultType().getAsString(
1090 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001091 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001092 }
1093 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001094 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001095}
1096
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001097void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1098 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001099 std::string &ResultStr) {
1100 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1101 const FunctionType *FPRetType = 0;
1102 ResultStr += "\nstatic ";
1103 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001104 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001107 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001109 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001110 NameStr += "_I_";
1111 else
1112 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001114 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001115 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001116
1117 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001118 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001119 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001120 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121 }
Mike Stump1eb44332009-09-09 15:08:12 +00001122 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001123 {
1124 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001125 int len = selString.size();
1126 for (int i = 0; i < len; i++)
1127 if (selString[i] == ':')
1128 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001129 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001131 // Remember this name for metadata emission
1132 MethodInternalNames[OMD] = NameStr;
1133 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001135 // Rewrite arguments
1136 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001138 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001139 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001140 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001142 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001143 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001144 ResultStr += "struct ";
1145 }
1146 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001147 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001148 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001149 }
1150 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001151 ResultStr += Context->getObjCClassType().getAsString(
1152 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001154 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001155 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001159 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1160 E = OMD->param_end(); PI != E; ++PI) {
1161 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001163 if (PDecl->getType()->isObjCQualifiedIdType()) {
1164 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001165 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001166 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001167 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001168 QualType QT = PDecl->getType();
1169 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1170 if (convertBlockPointerToFunctionPointer(QT))
1171 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1172 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001173 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001174 ResultStr += Name;
1175 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001177 if (OMD->isVariadic())
1178 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001179 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Steve Naroff76e429d2008-07-16 14:40:40 +00001181 if (FPRetType) {
1182 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Steve Naroff76e429d2008-07-16 14:40:40 +00001184 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001185 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001186 ResultStr += "(";
1187 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1188 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001189 std::string ParamStr = FT->getArgType(i).getAsString(
1190 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001191 ResultStr += ParamStr;
1192 }
1193 if (FT->isVariadic()) {
1194 if (FT->getNumArgs()) ResultStr += ", ";
1195 ResultStr += "...";
1196 }
1197 ResultStr += ")";
1198 } else {
1199 ResultStr += "()";
1200 }
1201 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001202}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001203void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001204 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1205 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001207 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001209 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001210 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1211 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001212 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001213 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001214 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001215 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001216 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001217 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001218
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001219 const char *startBuf = SM->getCharacterData(LocStart);
1220 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001221 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001224 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001225 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1226 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001227 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001228 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001229 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001230 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001231 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001232 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001234 const char *startBuf = SM->getCharacterData(LocStart);
1235 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001236 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001237 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001238 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001239 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001240 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001241 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001242 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001243 }
1244
Benjamin Kramerd999b372010-02-14 14:14:16 +00001245 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001246}
1247
Steve Naroffb29b4272008-04-14 22:03:09 +00001248void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001249 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001250 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001251 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001252 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001253 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001254 ResultStr += "\n";
1255 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001256 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001257 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001258 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001259 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001260 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001261 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001262 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001263 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001264 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001265
1266 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001267 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001268 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001269 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001270 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001271 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001272 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001273 for (ObjCInterfaceDecl::classmeth_iterator
1274 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001275 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001276 RewriteMethodDeclaration(*I);
1277
Steve Naroff2feac5e2007-10-30 03:43:13 +00001278 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001279 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1280 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001281}
1282
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001283Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001284 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001285 ObjCMethodDecl *OMD = 0;
1286 QualType Ty;
1287 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001288 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001289 bool Super = false;
1290 QualType SuperTy;
1291 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001292 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001293 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001294 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001295 if (ObjCPropertyRefExpr *PropRefExpr =
1296 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001297 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001298 if (PropRefExpr->isExplicitProperty()) {
1299 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1300 OMD = PDecl->getSetterMethodDecl();
1301 Ty = PDecl->getType();
1302 Sel = PDecl->getSetterName();
1303 } else {
1304 OMD = PropRefExpr->getImplicitPropertySetter();
1305 Sel = OMD->getSelector();
1306 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001307 }
John McCall12f78a62010-12-02 01:19:52 +00001308 Super = PropRefExpr->isSuperReceiver();
1309 if (!Super) {
1310 Receiver = PropRefExpr->getBase();
1311 } else {
1312 SuperTy = PropRefExpr->getSuperReceiverType();
1313 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001314 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001315 }
1316
1317 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001318 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001319 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001321 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001322 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001323 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001324 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001325 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001326 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001327 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001328 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001329 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001330 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001331 &ExprVec[0], 1,
1332 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001333 else {
1334 // FIXME. Refactor this into common code with that in
1335 // RewritePropertyOrImplicitGetter
1336 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1337 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1338 if (PropGetters[Exp])
1339 // This allows us to handle chain/nested property/implicit getters.
1340 Receiver = PropGetters[Exp];
1341
Douglas Gregor04badcf2010-04-21 00:45:42 +00001342 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001343 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001344 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001345 /*FIXME: */SourceLocation(),
1346 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001347 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001348 &ExprVec[0], 1,
1349 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001350 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001351 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Steve Naroffc77a6362008-12-04 16:24:46 +00001353 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001354 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001355 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001356 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1357 // to things that stay around.
1358 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001359 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001360}
1361
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001362Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1363 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001364 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001365 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001366 ObjCMethodDecl *OMD = 0;
1367 QualType Ty;
1368 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001369 bool Super = false;
1370 QualType SuperTy;
1371 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001372 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001373 if (ObjCPropertyRefExpr *PropRefExpr =
1374 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001375 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001376 if (PropRefExpr->isExplicitProperty()) {
1377 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1378 OMD = PDecl->getGetterMethodDecl();
1379 Ty = PDecl->getType();
1380 Sel = PDecl->getGetterName();
1381 } else {
1382 OMD = PropRefExpr->getImplicitPropertyGetter();
1383 Sel = OMD->getSelector();
1384 Ty = PropRefExpr->getType();
1385 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001386 Super = PropRefExpr->isSuperReceiver();
1387 if (!Super)
1388 Receiver = PropRefExpr->getBase();
1389 else {
John McCall12f78a62010-12-02 01:19:52 +00001390 SuperTy = PropRefExpr->getSuperReceiverType();
1391 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001392 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001393 }
1394
1395 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1396
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001397 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001398 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001399 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001400 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001401 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001402 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001403 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001404 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001405 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001406 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001407 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001408 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001409 else {
1410 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1411 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1412 if (PropGetters[Exp])
1413 // This allows us to handle chain/nested property/implicit getters.
1414 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001415 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001416 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001417 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001418 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001419 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001420 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001421 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001422 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001423 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001424
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001425 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1426 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001427
1428 if (!PropParentMap)
1429 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001430 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001431 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001432 ImplicitCastExpr*ICE=0;
1433 if (Parent)
1434 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1435 assert((ICE->getCastKind() == CK_GetObjCProperty)
1436 && "RewritePropertyOrImplicitGetter");
1437 Parent = PropParentMap->getParent(Parent);
1438 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1439 }
1440 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001441 // We stash away the ReplacingStmt since actually doing the
1442 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001443 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001444 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1445 // to things that stay around.
1446 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001447 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001448 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001449 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001450 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001451 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1452 // to things that stay around.
1453 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001454 return ReplacingStmt;
1455 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001456}
1457
Mike Stump1eb44332009-09-09 15:08:12 +00001458Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001459 SourceLocation OrigStart,
1460 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001461 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001462 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001463 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001464 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001465 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001466 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001467 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +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 Narofff0757612008-05-08 17:52:16 +00001472 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Steve Narofff0757612008-05-08 17:52:16 +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 Narofff0757612008-05-08 17:52:16 +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 Narofff0757612008-05-08 17:52:16 +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(),
John McCallf89e55a2010-11-18 06:31:45 +00001488 IV->getBase()->getLocEnd(),
1489 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001490 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001491 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001492 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001493 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001494 IV->getLocation(),
1495 D->getType(),
1496 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001497 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001498 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001499 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001500 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001501 // Cannot delete IV->getBase(), since PE points to it.
1502 // Replace the old base with the cast. This is important when doing
1503 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001504 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001505 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001506 }
Steve Naroff84472a82008-04-18 21:55:08 +00001507 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001508 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Steve Naroff9f525972008-05-06 23:20:07 +00001510 // Explicit ivar refs need to have a cast inserted.
1511 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001512 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001513 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001514 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001515 // lookup which class implements the instance variable.
1516 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001517 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001518 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001519 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Steve Naroff9f525972008-05-06 23:20:07 +00001521 // Synthesize an explicit cast to gain access to the ivar.
1522 std::string RecName = clsDeclared->getIdentifier()->getName();
1523 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001524 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001525 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001526 SourceLocation(), SourceLocation(),
1527 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001528 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1529 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001530 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001531 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001532 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001533 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001534 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001535 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001536 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001537 // Cannot delete IV->getBase(), since PE points to it.
1538 // Replace the old base with the cast. This is important when doing
1539 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001540 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001541 return IV;
1542 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001543 }
Steve Naroff84472a82008-04-18 21:55:08 +00001544 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001545}
1546
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001547Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001548 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001549 if (*CI) {
1550 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1551 if (newStmt)
1552 *CI = newStmt;
1553 }
1554 }
1555 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1556 SourceRange OrigStmtRange = S->getSourceRange();
1557 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1558 replaced);
1559 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001560 }
1561 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1562 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1563 return newStmt;
1564 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001565 return S;
1566}
1567
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568/// SynthCountByEnumWithState - To print:
1569/// ((unsigned int (*)
1570/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001571/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001573/// "countByEnumeratingWithState:objects:count:"),
1574/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575/// (id *)items, (unsigned int)16)
1576///
Steve Naroffb29b4272008-04-14 22:03:09 +00001577void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1579 "id *, unsigned int))(void *)objc_msgSend)";
1580 buf += "\n\t\t";
1581 buf += "((id)l_collection,\n\t\t";
1582 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1583 buf += "\n\t\t";
1584 buf += "&enumState, "
1585 "(id *)items, (unsigned int)16)";
1586}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001587
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001588/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1589/// statement to exit to its outer synthesized loop.
1590///
Steve Naroffb29b4272008-04-14 22:03:09 +00001591Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001592 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1593 return S;
1594 // replace break with goto __break_label
1595 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001596
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001597 SourceLocation startLoc = S->getLocStart();
1598 buf = "goto __break_label_";
1599 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001600 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601
1602 return 0;
1603}
1604
1605/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1606/// statement to continue with its inner synthesized loop.
1607///
Steve Naroffb29b4272008-04-14 22:03:09 +00001608Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001609 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1610 return S;
1611 // replace continue with goto __continue_label
1612 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001614 SourceLocation startLoc = S->getLocStart();
1615 buf = "goto __continue_label_";
1616 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001617 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001619 return 0;
1620}
1621
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001622/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001623/// It rewrites:
1624/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001626/// Into:
1627/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001628/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001630/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001631/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001632/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001634/// if (limit) {
1635/// unsigned long startMutations = *enumState.mutationsPtr;
1636/// do {
1637/// unsigned long counter = 0;
1638/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001639/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001640/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001641/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001642/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001643/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001644/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001645/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001646/// objects:items count:16]);
1647/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001648/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001649/// }
1650/// else
1651/// elem = nil;
1652/// }
1653///
Steve Naroffb29b4272008-04-14 22:03:09 +00001654Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001655 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001656 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001657 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001658 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001659 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001660 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001662 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001664 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001665 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001666 std::string buf;
1667 buf = "\n{\n\t";
1668 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1669 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001670 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001671 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001672 if (ElementType->isObjCQualifiedIdType() ||
1673 ElementType->isObjCQualifiedInterfaceType())
1674 // Simply use 'id' for all qualified types.
1675 elementTypeAsString = "id";
1676 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001677 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001678 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001679 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001680 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001681 buf += elementName;
1682 buf += ";\n\t";
1683 }
Chris Lattner06767512008-04-08 05:52:18 +00001684 else {
1685 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001686 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001687 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1688 if (VD->getType()->isObjCQualifiedIdType() ||
1689 VD->getType()->isObjCQualifiedInterfaceType())
1690 // Simply use 'id' for all qualified types.
1691 elementTypeAsString = "id";
1692 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001693 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001694 }
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001696 // struct __objcFastEnumerationState enumState = { 0 };
1697 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1698 // id items[16];
1699 buf += "id items[16];\n\t";
1700 // id l_collection = (id)
1701 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001702 // Find start location of 'collection' the hard way!
1703 const char *startCollectionBuf = startBuf;
1704 startCollectionBuf += 3; // skip 'for'
1705 startCollectionBuf = strchr(startCollectionBuf, '(');
1706 startCollectionBuf++; // skip '('
1707 // find 'in' and skip it.
1708 while (*startCollectionBuf != ' ' ||
1709 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1710 (*(startCollectionBuf+3) != ' ' &&
1711 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1712 startCollectionBuf++;
1713 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001714
1715 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001716 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001717 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001718 SourceLocation rightParenLoc = S->getRParenLoc();
1719 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1720 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001721 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001722
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001723 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1724 // objects:items count:16];
1725 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001726 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001727 // ((unsigned int (*)
1728 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001729 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001730 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001731 // "countByEnumeratingWithState:objects:count:"),
1732 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001733 // (id *)items, (unsigned int)16);
1734 buf += "unsigned long limit =\n\t\t";
1735 SynthCountByEnumWithState(buf);
1736 buf += ";\n\t";
1737 /// if (limit) {
1738 /// unsigned long startMutations = *enumState.mutationsPtr;
1739 /// do {
1740 /// unsigned long counter = 0;
1741 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001742 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001743 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001744 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001745 buf += "if (limit) {\n\t";
1746 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1747 buf += "do {\n\t\t";
1748 buf += "unsigned long counter = 0;\n\t\t";
1749 buf += "do {\n\t\t\t";
1750 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1751 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1752 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001753 buf += " = (";
1754 buf += elementTypeAsString;
1755 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001756 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001757 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001759 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001760 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001761 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001762 /// objects:items count:16]);
1763 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001764 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001765 /// }
1766 /// else
1767 /// elem = nil;
1768 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001769 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001770 buf = ";\n\t";
1771 buf += "__continue_label_";
1772 buf += utostr(ObjCBcLabelNo.back());
1773 buf += ": ;";
1774 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001775 buf += "} while (counter < limit);\n\t";
1776 buf += "} while (limit = ";
1777 SynthCountByEnumWithState(buf);
1778 buf += ");\n\t";
1779 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001780 buf += " = ((";
1781 buf += elementTypeAsString;
1782 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001783 buf += "__break_label_";
1784 buf += utostr(ObjCBcLabelNo.back());
1785 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001786 buf += "}\n\t";
1787 buf += "else\n\t\t";
1788 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001789 buf += " = ((";
1790 buf += elementTypeAsString;
1791 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001792 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001794 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001795 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001796 if (isa<CompoundStmt>(S->getBody())) {
1797 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001798 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001799 } else {
1800 /* Need to treat single statements specially. For example:
1801 *
1802 * for (A *a in b) if (stuff()) break;
1803 * for (A *a in b) xxxyy;
1804 *
1805 * The following code simply scans ahead to the semi to find the actual end.
1806 */
1807 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1808 const char *semiBuf = strchr(stmtBuf, ';');
1809 assert(semiBuf && "Can't find ';'");
1810 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001811 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001812 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001813 Stmts.pop_back();
1814 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001815 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001816}
1817
Mike Stump1eb44332009-09-09 15:08:12 +00001818/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001819/// This routine rewrites @synchronized(expr) stmt;
1820/// into:
1821/// objc_sync_enter(expr);
1822/// @try stmt @finally { objc_sync_exit(expr); }
1823///
Steve Naroffb29b4272008-04-14 22:03:09 +00001824Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001825 // Get the start location and compute the semi location.
1826 SourceLocation startLoc = S->getLocStart();
1827 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001829 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001830
1831 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001832 buf = "objc_sync_enter((id)";
1833 const char *lparenBuf = startBuf;
1834 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001835 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001836 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1837 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001838 // been rewritten! (which implies the SourceLocation's are invalid).
1839 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001840 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001841 while (*endBuf != ')') endBuf--;
1842 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001843 buf = ");\n";
1844 // declare a new scope with two variables, _stack and _rethrow.
1845 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1846 buf += "int buf[18/*32-bit i386*/];\n";
1847 buf += "char *pointers[4];} _stack;\n";
1848 buf += "id volatile _rethrow = 0;\n";
1849 buf += "objc_exception_try_enter(&_stack);\n";
1850 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001851 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001852 startLoc = S->getSynchBody()->getLocEnd();
1853 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Steve Naroffc7089f12008-08-19 13:04:19 +00001855 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001856 SourceLocation lastCurlyLoc = startLoc;
1857 buf = "}\nelse {\n";
1858 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001859 buf += "}\n";
1860 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001861 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001862
1863 std::string syncBuf;
1864 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001865
1866 Expr *syncExpr = S->getSynchExpr();
1867 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1868 ? CK_BitCast :
1869 syncExpr->getType()->isBlockPointerType()
1870 ? CK_BlockPointerToObjCPointerCast
1871 : CK_CPointerToObjCPointerCast;
1872 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1873 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001874 std::string syncExprBufS;
1875 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001876 syncExpr->printPretty(syncExprBuf, *Context, 0,
1877 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001878 syncBuf += syncExprBuf.str();
1879 syncBuf += ");";
1880
1881 buf += syncBuf;
1882 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001883 buf += "}\n";
1884 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Benjamin Kramerd999b372010-02-14 14:14:16 +00001886 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001887
1888 bool hasReturns = false;
1889 HasReturnStmts(S->getSynchBody(), hasReturns);
1890 if (hasReturns)
1891 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1892
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001893 return 0;
1894}
1895
Steve Naroffb85e77a2009-12-05 21:43:12 +00001896void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1897{
Steve Naroff8c565152008-12-05 17:03:39 +00001898 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001899 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001900 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001901 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001902
Steve Naroffb85e77a2009-12-05 21:43:12 +00001903 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001904 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001905 TryFinallyContainsReturnDiag);
1906 }
1907 return;
1908}
1909
Steve Naroffb85e77a2009-12-05 21:43:12 +00001910void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1911{
1912 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001913 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001914 if (*CI)
1915 HasReturnStmts(*CI, hasReturns);
1916
1917 if (isa<ReturnStmt>(S))
1918 hasReturns = true;
1919 return;
1920}
1921
1922void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1923 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001924 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001925 if (*CI) {
1926 RewriteTryReturnStmts(*CI);
1927 }
1928 if (isa<ReturnStmt>(S)) {
1929 SourceLocation startLoc = S->getLocStart();
1930 const char *startBuf = SM->getCharacterData(startLoc);
1931
1932 const char *semiBuf = strchr(startBuf, ';');
1933 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1934 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1935
1936 std::string buf;
1937 buf = "{ objc_exception_try_exit(&_stack); return";
1938
Benjamin Kramerd999b372010-02-14 14:14:16 +00001939 ReplaceText(startLoc, 6, buf);
1940 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001941 }
1942 return;
1943}
1944
1945void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1946 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001947 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001948 if (*CI) {
1949 RewriteSyncReturnStmts(*CI, syncExitBuf);
1950 }
1951 if (isa<ReturnStmt>(S)) {
1952 SourceLocation startLoc = S->getLocStart();
1953 const char *startBuf = SM->getCharacterData(startLoc);
1954
1955 const char *semiBuf = strchr(startBuf, ';');
1956 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1957 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1958
1959 std::string buf;
1960 buf = "{ objc_exception_try_exit(&_stack);";
1961 buf += syncExitBuf;
1962 buf += " return";
1963
Benjamin Kramerd999b372010-02-14 14:14:16 +00001964 ReplaceText(startLoc, 6, buf);
1965 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001966 }
1967 return;
1968}
1969
Steve Naroffb29b4272008-04-14 22:03:09 +00001970Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001971 // Get the start location and compute the semi location.
1972 SourceLocation startLoc = S->getLocStart();
1973 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Steve Naroff75730982007-11-07 04:08:17 +00001975 assert((*startBuf == '@') && "bogus @try location");
1976
1977 std::string buf;
1978 // declare a new scope with two variables, _stack and _rethrow.
1979 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1980 buf += "int buf[18/*32-bit i386*/];\n";
1981 buf += "char *pointers[4];} _stack;\n";
1982 buf += "id volatile _rethrow = 0;\n";
1983 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001984 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001985
Benjamin Kramerd999b372010-02-14 14:14:16 +00001986 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Steve Naroff75730982007-11-07 04:08:17 +00001988 startLoc = S->getTryBody()->getLocEnd();
1989 startBuf = SM->getCharacterData(startLoc);
1990
1991 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Steve Naroff75730982007-11-07 04:08:17 +00001993 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001994 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001995 startLoc = startLoc.getFileLocWithOffset(1);
1996 buf = " /* @catch begin */ else {\n";
1997 buf += " id _caught = objc_exception_extract(&_stack);\n";
1998 buf += " objc_exception_try_enter (&_stack);\n";
1999 buf += " if (_setjmp(_stack.buf))\n";
2000 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2001 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Benjamin Kramerd999b372010-02-14 14:14:16 +00002003 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00002004 } else { /* no catch list */
2005 buf = "}\nelse {\n";
2006 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2007 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002008 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002009 }
Steve Naroff75730982007-11-07 04:08:17 +00002010 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002011 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2012 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002013 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002014
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002015 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002016 buf = "if ("; // we are generating code for the first catch clause
2017 else
2018 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002019 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002020 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Steve Naroff75730982007-11-07 04:08:17 +00002022 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Steve Naroff75730982007-11-07 04:08:17 +00002024 const char *lParenLoc = strchr(startBuf, '(');
2025
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002026 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002027 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002028 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002029 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2030 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002031 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002032 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002033 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Steve Naroffe12e6922008-02-01 20:02:07 +00002035 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002036 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002037 } else if (catchDecl) {
2038 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002039 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002040 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002041 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002042 } else if (const ObjCObjectPointerType *Ptr =
2043 t->getAs<ObjCObjectPointerType>()) {
2044 // Should be a pointer to a class.
2045 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2046 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002047 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002048 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002049 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002050 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002051 }
2052 }
2053 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002054 lastCatchBody = Catch->getCatchBody();
2055 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002056 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2057 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2058 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2059 assert((*rParenBuf == ')') && "bogus @catch paren location");
2060 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Mike Stump1eb44332009-09-09 15:08:12 +00002062 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002063 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002064 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002065 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002066 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002067 }
Steve Naroff75730982007-11-07 04:08:17 +00002068 }
2069 // Complete the catch list...
2070 if (lastCatchBody) {
2071 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002072 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2073 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Steve Naroff378f47a2008-09-11 15:29:03 +00002075 // Insert the last (implicit) else clause *before* the right curly brace.
2076 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2077 buf = "} /* last catch end */\n";
2078 buf += "else {\n";
2079 buf += " _rethrow = _caught;\n";
2080 buf += " objc_exception_try_exit(&_stack);\n";
2081 buf += "} } /* @catch end */\n";
2082 if (!S->getFinallyStmt())
2083 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002084 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Steve Naroff75730982007-11-07 04:08:17 +00002086 // Set lastCurlyLoc
2087 lastCurlyLoc = lastCatchBody->getLocEnd();
2088 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002089 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002090 startLoc = finalStmt->getLocStart();
2091 startBuf = SM->getCharacterData(startLoc);
2092 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002093
Benjamin Kramerd999b372010-02-14 14:14:16 +00002094 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Steve Naroff75730982007-11-07 04:08:17 +00002096 Stmt *body = finalStmt->getFinallyBody();
2097 SourceLocation startLoc = body->getLocStart();
2098 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002099 assert(*SM->getCharacterData(startLoc) == '{' &&
2100 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002101 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002102 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Steve Naroff75730982007-11-07 04:08:17 +00002104 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002105 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002106 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002107 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Steve Naroff75730982007-11-07 04:08:17 +00002109 // Set lastCurlyLoc
2110 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Steve Naroff8c565152008-12-05 17:03:39 +00002112 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002113 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002114 } else { /* no finally clause - make sure we synthesize an implicit one */
2115 buf = "{ /* implicit finally clause */\n";
2116 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2117 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2118 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002119 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002120
2121 // Now check for any return/continue/go statements within the @try.
2122 // The implicit finally clause won't called if the @try contains any
2123 // jump statements.
2124 bool hasReturns = false;
2125 HasReturnStmts(S->getTryBody(), hasReturns);
2126 if (hasReturns)
2127 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002128 }
2129 // Now emit the final closing curly brace...
2130 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002131 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002132 return 0;
2133}
2134
Mike Stump1eb44332009-09-09 15:08:12 +00002135// This can't be done with ReplaceStmt(S, ThrowExpr), since
2136// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002137// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002138Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002139 // Get the start location and compute the semi location.
2140 SourceLocation startLoc = S->getLocStart();
2141 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Steve Naroff2bd03922007-11-07 15:32:26 +00002143 assert((*startBuf == '@') && "bogus @throw location");
2144
2145 std::string buf;
2146 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002147 if (S->getThrowExpr())
2148 buf = "objc_exception_throw(";
2149 else // add an implicit argument
2150 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002151
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002152 // handle "@ throw" correctly.
2153 const char *wBuf = strchr(startBuf, 'w');
2154 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002155 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Steve Naroff2bd03922007-11-07 15:32:26 +00002157 const char *semiBuf = strchr(startBuf, ';');
2158 assert((*semiBuf == ';') && "@throw: can't find ';'");
2159 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002160 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002161 return 0;
2162}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002163
Steve Naroffb29b4272008-04-14 22:03:09 +00002164Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002165 // Create a new string expression.
2166 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002167 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002168 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002169 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002170 StringLiteral::Ascii, false,
2171 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002172 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Chris Lattner07506182007-11-30 22:53:43 +00002174 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002175 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002176 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002177}
2178
Steve Naroffb29b4272008-04-14 22:03:09 +00002179Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002180 if (!SelGetUidFunctionDecl)
2181 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002182 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2183 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002184 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002185 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002186 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002187 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002188 StringLiteral::Ascii, false,
2189 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002190 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2191 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002192 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002193 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002194 return SelExp;
2195}
2196
Steve Naroffb29b4272008-04-14 22:03:09 +00002197CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002198 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2199 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002200 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002201 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Steve Naroffebf2b562007-10-23 23:50:29 +00002203 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002204 DeclRefExpr *DRE =
2205 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Steve Naroffebf2b562007-10-23 23:50:29 +00002207 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002208 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002209 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002210 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002211 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002212
John McCall183700f2009-09-21 23:43:11 +00002213 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002215 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002216 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002217 FT->getCallResultType(*Context),
2218 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002219 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002220}
2221
Steve Naroffd5255f52007-11-01 13:24:47 +00002222static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2223 const char *&startRef, const char *&endRef) {
2224 while (startBuf < endBuf) {
2225 if (*startBuf == '<')
2226 startRef = startBuf; // mark the start.
2227 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002228 if (startRef && *startRef == '<') {
2229 endRef = startBuf; // mark the end.
2230 return true;
2231 }
2232 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002233 }
2234 startBuf++;
2235 }
2236 return false;
2237}
2238
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002239static void scanToNextArgument(const char *&argRef) {
2240 int angle = 0;
2241 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2242 if (*argRef == '<')
2243 angle++;
2244 else if (*argRef == '>')
2245 angle--;
2246 argRef++;
2247 }
2248 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2249}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002250
Steve Naroffb29b4272008-04-14 22:03:09 +00002251bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002252 if (T->isObjCQualifiedIdType())
2253 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002254 if (const PointerType *PT = T->getAs<PointerType>()) {
2255 if (PT->getPointeeType()->isObjCQualifiedIdType())
2256 return true;
2257 }
2258 if (T->isObjCObjectPointerType()) {
2259 T = T->getPointeeType();
2260 return T->isObjCQualifiedInterfaceType();
2261 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002262 if (T->isArrayType()) {
2263 QualType ElemTy = Context->getBaseElementType(T);
2264 return needToScanForQualifiers(ElemTy);
2265 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002266 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002267}
2268
Steve Naroff4f95b752008-07-29 18:15:38 +00002269void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2270 QualType Type = E->getType();
2271 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002272 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Steve Naroffcda658e2008-11-19 21:15:47 +00002274 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2275 Loc = ECE->getLParenLoc();
2276 EndLoc = ECE->getRParenLoc();
2277 } else {
2278 Loc = E->getLocStart();
2279 EndLoc = E->getLocEnd();
2280 }
2281 // This will defend against trying to rewrite synthesized expressions.
2282 if (Loc.isInvalid() || EndLoc.isInvalid())
2283 return;
2284
Steve Naroff4f95b752008-07-29 18:15:38 +00002285 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002286 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002287 const char *startRef = 0, *endRef = 0;
2288 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2289 // Get the locations of the startRef, endRef.
2290 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2291 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2292 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002293 InsertText(LessLoc, "/*");
2294 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002295 }
2296 }
2297}
2298
Steve Naroffb29b4272008-04-14 22:03:09 +00002299void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002300 SourceLocation Loc;
2301 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002302 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002303 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2304 Loc = VD->getLocation();
2305 Type = VD->getType();
2306 }
2307 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2308 Loc = FD->getLocation();
2309 // Check for ObjC 'id' and class types that have been adorned with protocol
2310 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002311 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002312 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002313 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002314 if (!proto)
2315 return;
2316 Type = proto->getResultType();
2317 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002318 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2319 Loc = FD->getLocation();
2320 Type = FD->getType();
2321 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002322 else
2323 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002324
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002325 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002326 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Steve Naroffd5255f52007-11-01 13:24:47 +00002328 const char *endBuf = SM->getCharacterData(Loc);
2329 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002330 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002331 startBuf--; // scan backward (from the decl location) for return type.
2332 const char *startRef = 0, *endRef = 0;
2333 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2334 // Get the locations of the startRef, endRef.
2335 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2336 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2337 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002338 InsertText(LessLoc, "/*");
2339 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002340 }
2341 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002342 if (!proto)
2343 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002344 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002345 const char *startBuf = SM->getCharacterData(Loc);
2346 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002347 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2348 if (needToScanForQualifiers(proto->getArgType(i))) {
2349 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002350
Steve Naroffd5255f52007-11-01 13:24:47 +00002351 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002352 // scan forward (from the decl location) for argument types.
2353 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002354 const char *startRef = 0, *endRef = 0;
2355 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2356 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002357 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002358 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002359 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002360 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002361 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002362 InsertText(LessLoc, "/*");
2363 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002364 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002365 startBuf = ++endBuf;
2366 }
2367 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002368 // If the function name is derived from a macro expansion, then the
2369 // argument buffer will not follow the name. Need to speak with Chris.
2370 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002371 startBuf++; // scan forward (from the decl location) for argument types.
2372 startBuf++;
2373 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002374 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002375}
2376
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002377void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2378 QualType QT = ND->getType();
2379 const Type* TypePtr = QT->getAs<Type>();
2380 if (!isa<TypeOfExprType>(TypePtr))
2381 return;
2382 while (isa<TypeOfExprType>(TypePtr)) {
2383 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2384 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2385 TypePtr = QT->getAs<Type>();
2386 }
2387 // FIXME. This will not work for multiple declarators; as in:
2388 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002389 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002390 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2391 const char *startBuf = SM->getCharacterData(DeclLoc);
2392 if (ND->getInit()) {
2393 std::string Name(ND->getNameAsString());
2394 TypeAsString += " " + Name + " = ";
2395 Expr *E = ND->getInit();
2396 SourceLocation startLoc;
2397 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2398 startLoc = ECE->getLParenLoc();
2399 else
2400 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002401 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002402 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002403 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002404 }
2405 else {
2406 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002407 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002408 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002409 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002410 }
2411}
2412
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002413// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002414void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002415 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002417 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002418 QualType getFuncType =
2419 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002420 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002421 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002422 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002423 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002424 SC_Extern,
2425 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002426}
2427
Steve Naroffb29b4272008-04-14 22:03:09 +00002428void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002429 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002430 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002431 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002432 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002433 return;
2434 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002435 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002436}
2437
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002438void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2439 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002440 const char *argPtr = TypeString.c_str();
2441 if (!strchr(argPtr, '^')) {
2442 Str += TypeString;
2443 return;
2444 }
2445 while (*argPtr) {
2446 Str += (*argPtr == '^' ? '*' : *argPtr);
2447 argPtr++;
2448 }
2449}
2450
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002451// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002452void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2453 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002454 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002455 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002456 const char *argPtr = TypeString.c_str();
2457 int paren = 0;
2458 while (*argPtr) {
2459 switch (*argPtr) {
2460 case '(':
2461 Str += *argPtr;
2462 paren++;
2463 break;
2464 case ')':
2465 Str += *argPtr;
2466 paren--;
2467 break;
2468 case '^':
2469 Str += '*';
2470 if (paren == 1)
2471 Str += VD->getNameAsString();
2472 break;
2473 default:
2474 Str += *argPtr;
2475 break;
2476 }
2477 argPtr++;
2478 }
2479}
2480
2481
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002482void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2483 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2484 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2485 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2486 if (!proto)
2487 return;
2488 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002489 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002490 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002491 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002492 FdStr += "(";
2493 unsigned numArgs = proto->getNumArgs();
2494 for (unsigned i = 0; i < numArgs; i++) {
2495 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002496 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002497 if (i+1 < numArgs)
2498 FdStr += ", ";
2499 }
2500 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002501 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002502 CurFunctionDeclToDeclareForBlock = 0;
2503}
2504
Steve Naroffc0a123c2008-03-11 17:37:02 +00002505// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002506void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002507 if (SuperContructorFunctionDecl)
2508 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002509 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002510 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002511 QualType argT = Context->getObjCIdType();
2512 assert(!argT.isNull() && "Can't find 'id' type");
2513 ArgTys.push_back(argT);
2514 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002515 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2516 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002517 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002518 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002519 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002520 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002521 SC_Extern,
2522 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002523}
2524
Steve Naroff09b266e2007-10-30 23:14:51 +00002525// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002526void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002527 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002528 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002529 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002530 assert(!argT.isNull() && "Can't find 'id' type");
2531 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002532 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002533 assert(!argT.isNull() && "Can't find 'SEL' type");
2534 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002535 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2536 &ArgTys[0], ArgTys.size(),
2537 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002538 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002539 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002540 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002541 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002542 SC_Extern,
2543 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002544}
2545
Steve Naroff874e2322007-11-15 10:28:18 +00002546// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002547void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002548 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002549 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002550 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002551 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002552 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002553 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2554 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2555 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002556 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002557 assert(!argT.isNull() && "Can't find 'SEL' type");
2558 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002559 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2560 &ArgTys[0], ArgTys.size(),
2561 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002562 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002563 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002564 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002565 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002566 SC_Extern,
2567 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002568}
2569
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002571void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002572 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002573 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002574 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002575 assert(!argT.isNull() && "Can't find 'id' type");
2576 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002577 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002578 assert(!argT.isNull() && "Can't find 'SEL' type");
2579 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002580 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2581 &ArgTys[0], ArgTys.size(),
2582 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002583 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002584 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002585 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002586 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002587 SC_Extern,
2588 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002589}
2590
Mike Stump1eb44332009-09-09 15:08:12 +00002591// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002592// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002593void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002594 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002595 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002596 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002597 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002598 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002599 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002600 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2601 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2602 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002603 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002604 assert(!argT.isNull() && "Can't find 'SEL' type");
2605 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002606 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2607 &ArgTys[0], ArgTys.size(),
2608 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002609 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002610 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002611 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002612 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002613 SC_Extern,
2614 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002615}
2616
Steve Naroff1284db82008-05-08 22:02:18 +00002617// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002618void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002619 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002620 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002621 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002622 assert(!argT.isNull() && "Can't find 'id' type");
2623 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002624 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002625 assert(!argT.isNull() && "Can't find 'SEL' type");
2626 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002627 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2628 &ArgTys[0], ArgTys.size(),
2629 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002630 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002631 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002632 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002633 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002634 SC_Extern,
2635 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002636}
2637
Steve Naroff09b266e2007-10-30 23:14:51 +00002638// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002639void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002640 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002641 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002642 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002643 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2644 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002645 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002646 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002647 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002648 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002649 SC_Extern,
2650 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002651}
2652
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002653// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2654void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2655 IdentifierInfo *getSuperClassIdent =
2656 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002657 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002658 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002659 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2660 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002661 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002662 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002663 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002664 getSuperClassIdent,
2665 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002666 SC_Extern,
2667 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002668 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002669}
2670
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002671// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002672void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002673 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002674 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002675 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002676 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2677 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002678 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002679 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002680 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002681 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002682 SC_Extern,
2683 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002684}
2685
Steve Naroffb29b4272008-04-14 22:03:09 +00002686Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002687 QualType strType = getConstantStringStructType();
2688
2689 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002690
2691 std::string tmpName = InFileName;
2692 unsigned i;
2693 for (i=0; i < tmpName.length(); i++) {
2694 char c = tmpName.at(i);
2695 // replace any non alphanumeric characters with '_'.
2696 if (!isalpha(c) && (c < '0' || c > '9'))
2697 tmpName[i] = '_';
2698 }
2699 S += tmpName;
2700 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002701 S += utostr(NumObjCStringLiterals++);
2702
Steve Naroffba92b2e2008-03-27 22:29:16 +00002703 Preamble += "static __NSConstantStringImpl " + S;
2704 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2705 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002706 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002707 std::string prettyBufS;
2708 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002709 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2710 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002711 Preamble += prettyBuf.str();
2712 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002713 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002714
2715 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002716 SourceLocation(), &Context->Idents.get(S),
2717 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002718 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2719 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002720 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002721 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002722 VK_RValue, OK_Ordinary,
2723 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002724 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002725 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002726 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002727 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002728 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002729 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002730}
2731
Steve Naroff874e2322007-11-15 10:28:18 +00002732// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002733QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002734 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002735 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002736 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002737 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002738 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002739
Steve Naroff874e2322007-11-15 10:28:18 +00002740 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002741 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002742 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002743 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002744
Steve Naroff874e2322007-11-15 10:28:18 +00002745 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002746 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002747 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002748 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002749 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002750 FieldTypes[i], 0,
2751 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002752 /*Mutable=*/false,
2753 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002754 }
Mike Stump1eb44332009-09-09 15:08:12 +00002755
Douglas Gregor838db382010-02-11 01:19:42 +00002756 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002757 }
2758 return Context->getTagDeclType(SuperStructDecl);
2759}
2760
Steve Naroffb29b4272008-04-14 22:03:09 +00002761QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002762 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002763 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002764 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002765 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002766 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002767
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002768 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002769 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002770 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002771 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002772 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002773 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002774 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002775 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002776
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002777 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002778 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002779 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2780 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002781 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002782 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002783 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002784 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002785 /*Mutable=*/true,
2786 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002787 }
2788
Douglas Gregor838db382010-02-11 01:19:42 +00002789 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002790 }
2791 return Context->getTagDeclType(ConstantStringDecl);
2792}
2793
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002794Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2795 SourceLocation StartLoc,
2796 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002797 if (!SelGetUidFunctionDecl)
2798 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002799 if (!MsgSendFunctionDecl)
2800 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002801 if (!MsgSendSuperFunctionDecl)
2802 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002803 if (!MsgSendStretFunctionDecl)
2804 SynthMsgSendStretFunctionDecl();
2805 if (!MsgSendSuperStretFunctionDecl)
2806 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002807 if (!MsgSendFpretFunctionDecl)
2808 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002809 if (!GetClassFunctionDecl)
2810 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002811 if (!GetSuperClassFunctionDecl)
2812 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002813 if (!GetMetaClassFunctionDecl)
2814 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Steve Naroff874e2322007-11-15 10:28:18 +00002816 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002817 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2818 // May need to use objc_msgSend_stret() as well.
2819 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002820 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2821 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002822 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002823 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002824 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002825 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002826 }
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Steve Naroff934f2762007-10-24 22:48:43 +00002828 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002829 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002830 switch (Exp->getReceiverKind()) {
2831 case ObjCMessageExpr::SuperClass: {
2832 MsgSendFlavor = MsgSendSuperFunctionDecl;
2833 if (MsgSendStretFlavor)
2834 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2835 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002836
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Chris Lattner5f9e2722011-07-23 10:55:15 +00002839 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002840
Douglas Gregor04badcf2010-04-21 00:45:42 +00002841 // set the receiver to self, the first argument to all methods.
2842 InitExprs.push_back(
2843 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002844 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002846 Context->getObjCIdType(),
2847 VK_RValue,
2848 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002849 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002850
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002852 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002853 QualType argType = Context->getPointerType(Context->CharTy);
2854 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002855 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002856 StringLiteral::Ascii, false,
2857 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2859 &ClsExprs[0],
2860 ClsExprs.size(),
2861 StartLoc,
2862 EndLoc);
2863 // (Class)objc_getClass("CurrentClass")
2864 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2865 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002866 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 ClsExprs.clear();
2868 ClsExprs.push_back(ArgExpr);
2869 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2870 &ClsExprs[0], ClsExprs.size(),
2871 StartLoc, EndLoc);
2872
2873 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2874 // To turn off a warning, type-cast to 'id'
2875 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2876 NoTypeInfoCStyleCastExpr(Context,
2877 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002878 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002879 // struct objc_super
2880 QualType superType = getSuperStructType();
2881 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002882
Francois Pichet62ec1f22011-09-17 17:15:52 +00002883 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002884 SynthSuperContructorFunctionDecl();
2885 // Simulate a contructor call...
2886 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002887 superType, VK_LValue,
2888 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2890 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002891 superType, VK_LValue,
2892 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002893 // The code for super is a little tricky to prevent collision with
2894 // the structure definition in the header. The rewriter has it's own
2895 // internal definition (__rw_objc_super) that is uses. This is why
2896 // we need the cast below. For example:
2897 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2898 //
John McCall2de56d12010-08-25 11:45:40 +00002899 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002900 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002901 VK_RValue, OK_Ordinary,
2902 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002903 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2904 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002905 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002906 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002907 // (struct objc_super) { <exprs from above> }
2908 InitListExpr *ILE =
2909 new (Context) InitListExpr(*Context, SourceLocation(),
2910 &InitExprs[0], InitExprs.size(),
2911 SourceLocation());
2912 TypeSourceInfo *superTInfo
2913 = Context->getTrivialTypeSourceInfo(superType);
2914 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002915 superType, VK_LValue,
2916 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002917 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002918 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002919 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002920 VK_RValue, OK_Ordinary,
2921 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002922 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 MsgExprs.push_back(SuperRep);
2924 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002925 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002926
2927 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002928 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002929 QualType argType = Context->getPointerType(Context->CharTy);
2930 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002931 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002932 IdentifierInfo *clsName = Class->getIdentifier();
2933 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002934 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002935 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002936 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002937 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2938 &ClsExprs[0],
2939 ClsExprs.size(),
2940 StartLoc, EndLoc);
2941 MsgExprs.push_back(Cls);
2942 break;
2943 }
2944
2945 case ObjCMessageExpr::SuperInstance:{
2946 MsgSendFlavor = MsgSendSuperFunctionDecl;
2947 if (MsgSendStretFlavor)
2948 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2949 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2950 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002951 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002952
2953 InitExprs.push_back(
2954 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002955 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002956 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002957 Context->getObjCIdType(),
2958 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002959 ); // set the 'receiver'.
2960
2961 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002962 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002963 QualType argType = Context->getPointerType(Context->CharTy);
2964 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002965 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002966 StringLiteral::Ascii, false, argType,
2967 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002968 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2969 &ClsExprs[0],
2970 ClsExprs.size(),
2971 StartLoc, EndLoc);
2972 // (Class)objc_getClass("CurrentClass")
2973 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2974 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002975 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002976 ClsExprs.clear();
2977 ClsExprs.push_back(ArgExpr);
2978 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2979 &ClsExprs[0], ClsExprs.size(),
2980 StartLoc, EndLoc);
2981
2982 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2983 // To turn off a warning, type-cast to 'id'
2984 InitExprs.push_back(
2985 // set 'super class', using class_getSuperclass().
2986 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002987 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002988 // struct objc_super
2989 QualType superType = getSuperStructType();
2990 Expr *SuperRep;
2991
Francois Pichet62ec1f22011-09-17 17:15:52 +00002992 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002993 SynthSuperContructorFunctionDecl();
2994 // Simulate a contructor call...
2995 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002996 superType, VK_LValue,
2997 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002998 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2999 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003000 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00003001 // The code for super is a little tricky to prevent collision with
3002 // the structure definition in the header. The rewriter has it's own
3003 // internal definition (__rw_objc_super) that is uses. This is why
3004 // we need the cast below. For example:
3005 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3006 //
John McCall2de56d12010-08-25 11:45:40 +00003007 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003008 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003009 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003010 SourceLocation());
3011 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3012 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003013 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003014 } else {
3015 // (struct objc_super) { <exprs from above> }
3016 InitListExpr *ILE =
3017 new (Context) InitListExpr(*Context, SourceLocation(),
3018 &InitExprs[0], InitExprs.size(),
3019 SourceLocation());
3020 TypeSourceInfo *superTInfo
3021 = Context->getTrivialTypeSourceInfo(superType);
3022 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003023 superType, VK_RValue, ILE,
3024 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003025 }
3026 MsgExprs.push_back(SuperRep);
3027 break;
3028 }
3029
3030 case ObjCMessageExpr::Instance: {
3031 // Remove all type-casts because it may contain objc-style types; e.g.
3032 // Foo<Proto> *.
3033 Expr *recExpr = Exp->getInstanceReceiver();
3034 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3035 recExpr = CE->getSubExpr();
3036 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003037 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003038 MsgExprs.push_back(recExpr);
3039 break;
3040 }
3041 }
3042
Steve Naroffbeaf2992007-11-03 11:27:19 +00003043 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003044 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003045 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003046 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003047 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003048 StringLiteral::Ascii, false,
3049 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003050 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003051 &SelExprs[0], SelExprs.size(),
3052 StartLoc,
3053 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003054 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Steve Naroff934f2762007-10-24 22:48:43 +00003056 // Now push any user supplied arguments.
3057 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003058 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003059 // Make all implicit casts explicit...ICE comes in handy:-)
3060 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3061 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003062 QualType type = ICE->getType();
3063 if (needToScanForQualifiers(type))
3064 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003065 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003066 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003067 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003068 CastKind CK;
3069 if (SubExpr->getType()->isIntegralType(*Context) &&
3070 type->isBooleanType()) {
3071 CK = CK_IntegralToBoolean;
3072 } else if (type->isObjCObjectPointerType()) {
3073 if (SubExpr->getType()->isBlockPointerType()) {
3074 CK = CK_BlockPointerToObjCPointerCast;
3075 } else if (SubExpr->getType()->isPointerType()) {
3076 CK = CK_CPointerToObjCPointerCast;
3077 } else {
3078 CK = CK_BitCast;
3079 }
3080 } else {
3081 CK = CK_BitCast;
3082 }
3083
3084 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003085 }
3086 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003087 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003088 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003089 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003090 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003091 CastKind CK;
3092 if (userExpr->getType()->isIntegralType(*Context)) {
3093 CK = CK_IntegralToPointer;
3094 } else if (userExpr->getType()->isBlockPointerType()) {
3095 CK = CK_BlockPointerToObjCPointerCast;
3096 } else if (userExpr->getType()->isPointerType()) {
3097 CK = CK_CPointerToObjCPointerCast;
3098 } else {
3099 CK = CK_BitCast;
3100 }
John McCall9d125032010-01-15 18:39:57 +00003101 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003102 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003103 }
Mike Stump1eb44332009-09-09 15:08:12 +00003104 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003105 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003106 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3107 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003108 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003109 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003110 }
Steve Naroffab972d32007-11-04 22:37:50 +00003111 // Generate the funky cast.
3112 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003113 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003114 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Steve Naroffab972d32007-11-04 22:37:50 +00003116 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003117 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3118 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3119 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003120 ArgTypes.push_back(Context->getObjCIdType());
3121 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003122 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003123 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003124 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3125 E = OMD->param_end(); PI != E; ++PI) {
3126 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003127 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003128 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003129 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003130 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003131 ArgTypes.push_back(t);
3132 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003133 returnType = Exp->getType();
3134 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003135 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003136 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003137 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003138 }
3139 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003140 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Steve Naroffab972d32007-11-04 22:37:50 +00003142 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003143 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003144 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003145
Mike Stump1eb44332009-09-09 15:08:12 +00003146 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003147 // If we don't do this cast, we get the following bizarre warning/note:
3148 // xx.m:13: warning: function called through a non-compatible type
3149 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003150 cast = NoTypeInfoCStyleCastExpr(Context,
3151 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003152 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003153
Steve Naroffab972d32007-11-04 22:37:50 +00003154 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003155 QualType castType =
3156 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3157 // If we don't have a method decl, force a variadic cast.
3158 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003159 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003160 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003161 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003162
3163 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003164 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003165
John McCall183700f2009-09-21 23:43:11 +00003166 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003167 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003168 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003169 FT->getResultType(), VK_RValue,
3170 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003171 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003172 if (MsgSendStretFlavor) {
3173 // We have the method which returns a struct/union. Must also generate
3174 // call to objc_msgSend_stret and hang both varieties on a conditional
3175 // expression which dictate which one to envoke depending on size of
3176 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003178 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003179 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003180 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003181 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003182 cast = NoTypeInfoCStyleCastExpr(Context,
3183 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003184 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003185 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003186 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3187 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003188 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003189 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003190 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003192 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003193 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003194
John McCall183700f2009-09-21 23:43:11 +00003195 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003196 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003197 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003198 FT->getResultType(), VK_RValue,
3199 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003200
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003201 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003202 UnaryExprOrTypeTraitExpr *sizeofExpr =
3203 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3204 Context->getTrivialTypeSourceInfo(returnType),
3205 Context->getSizeType(), SourceLocation(),
3206 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003207 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3208 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3209 // For X86 it is more complicated and some kind of target specific routine
3210 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003211 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003212 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003213 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3214 llvm::APInt(IntSize, 8),
3215 Context->IntTy,
3216 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003217 BinaryOperator *lessThanExpr =
3218 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3219 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003220 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003221 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003222 new (Context) ConditionalOperator(lessThanExpr,
3223 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003224 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003225 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003226 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3227 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003228 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003229 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003230 return ReplacingStmt;
3231}
3232
Steve Naroffb29b4272008-04-14 22:03:09 +00003233Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003234 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3235 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Steve Naroff934f2762007-10-24 22:48:43 +00003237 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003238 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003240 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003241 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003242}
3243
Steve Naroff621edce2009-04-29 16:37:50 +00003244// typedef struct objc_object Protocol;
3245QualType RewriteObjC::getProtocolType() {
3246 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003247 TypeSourceInfo *TInfo
3248 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003249 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003250 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003251 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003252 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003253 }
3254 return Context->getTypeDeclType(ProtocolTypeDecl);
3255}
3256
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003257/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003258/// a synthesized/forward data reference (to the protocol's metadata).
3259/// The forward references (and metadata) are generated in
3260/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003261Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003262 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3263 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003264 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003265 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003266 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003267 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3268 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003269 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003270 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003271 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003272 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003273 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003274 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003275 ReplaceStmt(Exp, castExpr);
3276 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003277 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003278 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003279
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003280}
3281
Mike Stump1eb44332009-09-09 15:08:12 +00003282bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003283 const char *endBuf) {
3284 while (startBuf < endBuf) {
3285 if (*startBuf == '#') {
3286 // Skip whitespace.
3287 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3288 ;
3289 if (!strncmp(startBuf, "if", strlen("if")) ||
3290 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3291 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3292 !strncmp(startBuf, "define", strlen("define")) ||
3293 !strncmp(startBuf, "undef", strlen("undef")) ||
3294 !strncmp(startBuf, "else", strlen("else")) ||
3295 !strncmp(startBuf, "elif", strlen("elif")) ||
3296 !strncmp(startBuf, "endif", strlen("endif")) ||
3297 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3298 !strncmp(startBuf, "include", strlen("include")) ||
3299 !strncmp(startBuf, "import", strlen("import")) ||
3300 !strncmp(startBuf, "include_next", strlen("include_next")))
3301 return true;
3302 }
3303 startBuf++;
3304 }
3305 return false;
3306}
3307
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003308/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003309/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003310void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003311 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003313 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003314 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003315 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003316 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003317 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003318 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003319 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003320 SourceLocation LocStart = CDecl->getLocStart();
3321 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003322
Steve Narofffea763e82007-11-14 19:25:57 +00003323 const char *startBuf = SM->getCharacterData(LocStart);
3324 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003326 // If no ivars and no root or if its root, directly or indirectly,
3327 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003328 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3329 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003330 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003331 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003332 return;
3333 }
Mike Stump1eb44332009-09-09 15:08:12 +00003334
3335 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003336 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003337 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003338 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003339 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003340 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003341
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003342 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003343 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003344 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003345 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003346 // If the buffer contains preprocessor directives, we do more fine-grained
3347 // rewrites. This is intended to fix code that looks like (which occurs in
3348 // NSURL.h, for example):
3349 //
3350 // #ifdef XYZ
3351 // @interface Foo : NSObject
3352 // #else
3353 // @interface FooBar : NSObject
3354 // #endif
3355 // {
3356 // int i;
3357 // }
3358 // @end
3359 //
3360 // This clause is segregated to avoid breaking the common case.
3361 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003362 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003363 CDecl->getClassLoc();
3364 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003365 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003366
Chris Lattnercafeb352009-02-20 18:18:36 +00003367 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003368 // advance to the end of the referenced protocols.
3369 while (endHeader < cursor && *endHeader != '>') endHeader++;
3370 endHeader++;
3371 }
3372 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003373 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003374 } else {
3375 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003376 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003377 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003378 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003379 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003380 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003381 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003382 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003383 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003384
Steve Narofffea763e82007-11-14 19:25:57 +00003385 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003386 SourceLocation OnePastCurly =
3387 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003388 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003389 }
3390 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003391
Steve Narofffea763e82007-11-14 19:25:57 +00003392 // Now comment out any visibility specifiers.
3393 while (cursor < endBuf) {
3394 if (*cursor == '@') {
3395 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003396 // Skip whitespace.
3397 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3398 /*scan*/;
3399
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003400 // FIXME: presence of @public, etc. inside comment results in
3401 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003402 if (!strncmp(cursor, "public", strlen("public")) ||
3403 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003404 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003405 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003406 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003407 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003408 // FIXME: If there are cases where '<' is used in ivar declaration part
3409 // of user code, then scan the ivar list and use needToScanForQualifiers
3410 // for type checking.
3411 else if (*cursor == '<') {
3412 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003413 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003414 cursor = strchr(cursor, '>');
3415 cursor++;
3416 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003417 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003418 } else if (*cursor == '^') { // rewrite block specifier.
3419 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003420 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003421 }
Steve Narofffea763e82007-11-14 19:25:57 +00003422 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003423 }
Steve Narofffea763e82007-11-14 19:25:57 +00003424 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003425 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003426 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003427 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003428 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003429 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003430 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003431 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003432 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003433 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003434 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003435 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003436 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003437 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003438}
3439
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003440// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003441/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003442template<typename MethodIterator>
3443void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3444 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003445 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003446 StringRef prefix,
3447 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003448 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003449 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003450
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003451 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003452 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003453 SEL _cmd;
3454 char *method_types;
3455 void *_imp;
3456 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003457 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003458 Result += "\nstruct _objc_method {\n";
3459 Result += "\tSEL _cmd;\n";
3460 Result += "\tchar *method_types;\n";
3461 Result += "\tvoid *_imp;\n";
3462 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003463
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003464 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003465 }
Mike Stump1eb44332009-09-09 15:08:12 +00003466
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003467 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Steve Naroff946a6932008-03-11 00:12:29 +00003469 /* struct {
3470 struct _objc_method_list *next_method;
3471 int method_count;
3472 struct _objc_method method_list[];
3473 }
3474 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003475 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003476 Result += "\nstatic struct {\n";
3477 Result += "\tstruct _objc_method_list *next_method;\n";
3478 Result += "\tint method_count;\n";
3479 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003480 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003481 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003482 Result += prefix;
3483 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3484 Result += "_METHODS_";
3485 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003486 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003487 Result += IsInstanceMethod ? "inst" : "cls";
3488 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003489 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003490
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003491 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003492 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003493 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003494 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003495 Result += "\", \"";
3496 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003497 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003498 Result += MethodInternalNames[*MethodBegin];
3499 Result += "}\n";
3500 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3501 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003502 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003503 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003504 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003505 Result += "\", \"";
3506 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003507 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003508 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003509 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003510 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003511 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003512}
3513
Steve Naroff621edce2009-04-29 16:37:50 +00003514/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003515void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003516RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3517 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003518 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003519
3520 // Output struct protocol_methods holder of method selector and type.
3521 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3522 /* struct protocol_methods {
3523 SEL _cmd;
3524 char *method_types;
3525 }
3526 */
3527 Result += "\nstruct _protocol_methods {\n";
3528 Result += "\tstruct objc_selector *_cmd;\n";
3529 Result += "\tchar *method_types;\n";
3530 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Steve Naroff621edce2009-04-29 16:37:50 +00003532 objc_protocol_methods = true;
3533 }
3534 // Do not synthesize the protocol more than once.
3535 if (ObjCSynthesizedProtocols.count(PDecl))
3536 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003538 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3539 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3540 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003541 /* struct _objc_protocol_method_list {
3542 int protocol_method_count;
3543 struct protocol_methods protocols[];
3544 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003545 */
Steve Naroff621edce2009-04-29 16:37:50 +00003546 Result += "\nstatic struct {\n";
3547 Result += "\tint protocol_method_count;\n";
3548 Result += "\tstruct _protocol_methods protocol_methods[";
3549 Result += utostr(NumMethods);
3550 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3551 Result += PDecl->getNameAsString();
3552 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3553 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003554
Steve Naroff621edce2009-04-29 16:37:50 +00003555 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003556 for (ObjCProtocolDecl::instmeth_iterator
3557 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003558 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003559 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003560 Result += "\t ,{{(struct objc_selector *)\"";
3561 else
3562 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003563 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003564 std::string MethodTypeString;
3565 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3566 Result += "\", \"";
3567 Result += MethodTypeString;
3568 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003569 }
Steve Naroff621edce2009-04-29 16:37:50 +00003570 Result += "\t }\n};\n";
3571 }
Mike Stump1eb44332009-09-09 15:08:12 +00003572
Steve Naroff621edce2009-04-29 16:37:50 +00003573 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003574 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3575 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003576 if (NumMethods > 0) {
3577 /* struct _objc_protocol_method_list {
3578 int protocol_method_count;
3579 struct protocol_methods protocols[];
3580 }
3581 */
3582 Result += "\nstatic struct {\n";
3583 Result += "\tint protocol_method_count;\n";
3584 Result += "\tstruct _protocol_methods protocol_methods[";
3585 Result += utostr(NumMethods);
3586 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3587 Result += PDecl->getNameAsString();
3588 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3589 "{\n\t";
3590 Result += utostr(NumMethods);
3591 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003592
Steve Naroff621edce2009-04-29 16:37:50 +00003593 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003594 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003595 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003596 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003597 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003598 Result += "\t ,{{(struct objc_selector *)\"";
3599 else
3600 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003601 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003602 std::string MethodTypeString;
3603 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3604 Result += "\", \"";
3605 Result += MethodTypeString;
3606 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003607 }
Steve Naroff621edce2009-04-29 16:37:50 +00003608 Result += "\t }\n};\n";
3609 }
3610
3611 // Output:
3612 /* struct _objc_protocol {
3613 // Objective-C 1.0 extensions
3614 struct _objc_protocol_extension *isa;
3615 char *protocol_name;
3616 struct _objc_protocol **protocol_list;
3617 struct _objc_protocol_method_list *instance_methods;
3618 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003619 };
Steve Naroff621edce2009-04-29 16:37:50 +00003620 */
3621 static bool objc_protocol = false;
3622 if (!objc_protocol) {
3623 Result += "\nstruct _objc_protocol {\n";
3624 Result += "\tstruct _objc_protocol_extension *isa;\n";
3625 Result += "\tchar *protocol_name;\n";
3626 Result += "\tstruct _objc_protocol **protocol_list;\n";
3627 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3628 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003629 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Steve Naroff621edce2009-04-29 16:37:50 +00003631 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003632 }
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Steve Naroff621edce2009-04-29 16:37:50 +00003634 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3635 Result += PDecl->getNameAsString();
3636 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3637 "{\n\t0, \"";
3638 Result += PDecl->getNameAsString();
3639 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003640 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003641 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3642 Result += PDecl->getNameAsString();
3643 Result += ", ";
3644 }
3645 else
3646 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003647 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003648 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3649 Result += PDecl->getNameAsString();
3650 Result += "\n";
3651 }
3652 else
3653 Result += "0\n";
3654 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Steve Naroff621edce2009-04-29 16:37:50 +00003656 // Mark this protocol as having been generated.
3657 if (!ObjCSynthesizedProtocols.insert(PDecl))
3658 assert(false && "protocol already synthesized");
3659
3660}
3661
3662void RewriteObjC::
3663RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003664 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003665 std::string &Result) {
3666 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Steve Naroff621edce2009-04-29 16:37:50 +00003668 for (unsigned i = 0; i != Protocols.size(); i++)
3669 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3670
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003671 // Output the top lovel protocol meta-data for the class.
3672 /* struct _objc_protocol_list {
3673 struct _objc_protocol_list *next;
3674 int protocol_count;
3675 struct _objc_protocol *class_protocols[];
3676 }
3677 */
3678 Result += "\nstatic struct {\n";
3679 Result += "\tstruct _objc_protocol_list *next;\n";
3680 Result += "\tint protocol_count;\n";
3681 Result += "\tstruct _objc_protocol *class_protocols[";
3682 Result += utostr(Protocols.size());
3683 Result += "];\n} _OBJC_";
3684 Result += prefix;
3685 Result += "_PROTOCOLS_";
3686 Result += ClassName;
3687 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3688 "{\n\t0, ";
3689 Result += utostr(Protocols.size());
3690 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003691
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003692 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003693 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003694 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003696 for (unsigned i = 1; i != Protocols.size(); i++) {
3697 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003698 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003699 Result += "\n";
3700 }
3701 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003702}
3703
Steve Naroff621edce2009-04-29 16:37:50 +00003704
Mike Stump1eb44332009-09-09 15:08:12 +00003705/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003706/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003707void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003708 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003709 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003710 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003711 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003712 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003713 CDecl = CDecl->getNextClassCategory())
3714 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3715 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003716
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003717 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003718 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003719 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003721 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003722 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003723 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003724
3725 // If any of our property implementations have associated getters or
3726 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003727 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3728 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003729 Prop != PropEnd; ++Prop) {
3730 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3731 continue;
3732 if (!(*Prop)->getPropertyIvarDecl())
3733 continue;
3734 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3735 if (!PD)
3736 continue;
3737 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3738 InstanceMethods.push_back(Getter);
3739 if (PD->isReadOnly())
3740 continue;
3741 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3742 InstanceMethods.push_back(Setter);
3743 }
3744 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003745 true, "CATEGORY_", FullCategoryName.c_str(),
3746 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003747
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003748 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003749 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003750 false, "CATEGORY_", FullCategoryName.c_str(),
3751 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003752
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003753 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003754 // Null CDecl is case of a category implementation with no category interface
3755 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003756 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003757 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003758 /* struct _objc_category {
3759 char *category_name;
3760 char *class_name;
3761 struct _objc_method_list *instance_methods;
3762 struct _objc_method_list *class_methods;
3763 struct _objc_protocol_list *protocols;
3764 // Objective-C 1.0 extensions
3765 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003766 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003767 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003768 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003769 */
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 static bool objc_category = false;
3772 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003773 Result += "\nstruct _objc_category {\n";
3774 Result += "\tchar *category_name;\n";
3775 Result += "\tchar *class_name;\n";
3776 Result += "\tstruct _objc_method_list *instance_methods;\n";
3777 Result += "\tstruct _objc_method_list *class_methods;\n";
3778 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003779 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003780 Result += "\tstruct _objc_property_list *instance_properties;\n";
3781 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003782 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003783 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3785 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003786 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003787 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003788 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003789 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003790 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003791
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003792 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003793 Result += "\t, (struct _objc_method_list *)"
3794 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3795 Result += FullCategoryName;
3796 Result += "\n";
3797 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003798 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003799 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003800 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003801 Result += "\t, (struct _objc_method_list *)"
3802 "&_OBJC_CATEGORY_CLASS_METHODS_";
3803 Result += FullCategoryName;
3804 Result += "\n";
3805 }
3806 else
3807 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003808
Chris Lattnercafeb352009-02-20 18:18:36 +00003809 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003810 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003811 Result += FullCategoryName;
3812 Result += "\n";
3813 }
3814 else
3815 Result += "\t, 0\n";
3816 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003817}
3818
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003819/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3820/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003821void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003822 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003823 if (ivar->isBitField()) {
3824 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3825 // place all bitfields at offset 0.
3826 Result += "0";
3827 } else {
3828 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003829 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003830 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003831 Result += "_IMPL";
3832 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003833 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003834 Result += ")";
3835 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003836}
3837
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003838//===----------------------------------------------------------------------===//
3839// Meta Data Emission
3840//===----------------------------------------------------------------------===//
3841
Steve Naroffb29b4272008-04-14 22:03:09 +00003842void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003843 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003844 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003846 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003847 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003848 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003849 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003850 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003851 }
Mike Stump1eb44332009-09-09 15:08:12 +00003852
Chris Lattnerbe6df082007-12-12 07:56:42 +00003853 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003854 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003855 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003856 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003857 if (NumIvars > 0) {
3858 static bool objc_ivar = false;
3859 if (!objc_ivar) {
3860 /* struct _objc_ivar {
3861 char *ivar_name;
3862 char *ivar_type;
3863 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003864 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003865 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003866 Result += "\nstruct _objc_ivar {\n";
3867 Result += "\tchar *ivar_name;\n";
3868 Result += "\tchar *ivar_type;\n";
3869 Result += "\tint ivar_offset;\n";
3870 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003872 objc_ivar = true;
3873 }
3874
Steve Naroff946a6932008-03-11 00:12:29 +00003875 /* struct {
3876 int ivar_count;
3877 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003878 };
Steve Naroff946a6932008-03-11 00:12:29 +00003879 */
Mike Stump1eb44332009-09-09 15:08:12 +00003880 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003881 Result += "\tint ivar_count;\n";
3882 Result += "\tstruct _objc_ivar ivar_list[";
3883 Result += utostr(NumIvars);
3884 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003885 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003886 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003887 "{\n\t";
3888 Result += utostr(NumIvars);
3889 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003891 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003892 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003893 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003894 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003895 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003896 IV != IVEnd; ++IV)
3897 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003898 IVI = IDecl->ivar_begin();
3899 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003900 } else {
3901 IVI = CDecl->ivar_begin();
3902 IVE = CDecl->ivar_end();
3903 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003904 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003905 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003906 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003907 std::string TmpString, StrEncoding;
3908 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3909 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003910 Result += StrEncoding;
3911 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003912 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003913 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003914 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003915 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003916 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003917 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003918 std::string TmpString, StrEncoding;
3919 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3920 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003921 Result += StrEncoding;
3922 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003923 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003924 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003927 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003930 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003931 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003932 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003933
3934 // If any of our property implementations have associated getters or
3935 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003936 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3937 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003938 Prop != PropEnd; ++Prop) {
3939 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3940 continue;
3941 if (!(*Prop)->getPropertyIvarDecl())
3942 continue;
3943 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3944 if (!PD)
3945 continue;
3946 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003947 if (!Getter->isDefined())
3948 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003949 if (PD->isReadOnly())
3950 continue;
3951 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003952 if (!Setter->isDefined())
3953 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003954 }
3955 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003956 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003958 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003959 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003960 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003962 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003963 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003964 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003966 // Declaration of class/meta-class metadata
3967 /* struct _objc_class {
3968 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003969 const char *super_class_name;
3970 char *name;
3971 long version;
3972 long info;
3973 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003974 struct _objc_ivar_list *ivars;
3975 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003976 struct objc_cache *cache;
3977 struct objc_protocol_list *protocols;
3978 const char *ivar_layout;
3979 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003980 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003981 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003982 static bool objc_class = false;
3983 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003984 Result += "\nstruct _objc_class {\n";
3985 Result += "\tstruct _objc_class *isa;\n";
3986 Result += "\tconst char *super_class_name;\n";
3987 Result += "\tchar *name;\n";
3988 Result += "\tlong version;\n";
3989 Result += "\tlong info;\n";
3990 Result += "\tlong instance_size;\n";
3991 Result += "\tstruct _objc_ivar_list *ivars;\n";
3992 Result += "\tstruct _objc_method_list *methods;\n";
3993 Result += "\tstruct objc_cache *cache;\n";
3994 Result += "\tstruct _objc_protocol_list *protocols;\n";
3995 Result += "\tconst char *ivar_layout;\n";
3996 Result += "\tstruct _objc_class_ext *ext;\n";
3997 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003998 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003999 }
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004001 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004002 ObjCInterfaceDecl *RootClass = 0;
4003 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004004 while (SuperClass) {
4005 RootClass = SuperClass;
4006 SuperClass = SuperClass->getSuperClass();
4007 }
4008 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004009
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004010 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004011 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004012 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004013 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004014 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004015 Result += "\"";
4016
4017 if (SuperClass) {
4018 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004019 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004020 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004021 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004022 Result += "\"";
4023 }
4024 else {
4025 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004026 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004027 Result += "\"";
4028 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004029 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004030 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004031 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004032 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004033 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004034 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004035 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004036 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004037 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004038 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004039 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004040 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004041 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004042 Result += ",0,0\n";
4043 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004044 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004045 Result += "\t,0,0,0,0\n";
4046 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004048 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004050 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004051 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004052 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004053 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 if (SuperClass) {
4055 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004056 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004058 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004059 Result += "\"";
4060 }
4061 else {
4062 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004063 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += "\"";
4065 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004066 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004067 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004068 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004069 Result += ",0";
4070 else {
4071 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004072 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004073 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004074 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004075 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004076 Result += ")";
4077 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004078 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004079 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004080 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004081 Result += "\n\t";
4082 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004083 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004084 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004085 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004086 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004087 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004088 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004089 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004090 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004091 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004092 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004093 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004094 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004095 Result += ", 0,0\n";
4096 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004097 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004098 Result += ",0,0,0\n";
4099 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004100}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004101
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004102/// RewriteImplementations - This routine rewrites all method implementations
4103/// and emits meta-data.
4104
Steve Narofface66252008-11-13 20:07:04 +00004105void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004106 int ClsDefCount = ClassImplementation.size();
4107 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004109 // Rewrite implemented methods
4110 for (int i = 0; i < ClsDefCount; i++)
4111 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004113 for (int i = 0; i < CatDefCount; i++)
4114 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004115}
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Steve Narofface66252008-11-13 20:07:04 +00004117void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4118 int ClsDefCount = ClassImplementation.size();
4119 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004120
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004121 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004122 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004123 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004125 // For each implemented category, write out all its meta data.
4126 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004127 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004128
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004129 // Write objc_symtab metadata
4130 /*
4131 struct _objc_symtab
4132 {
4133 long sel_ref_cnt;
4134 SEL *refs;
4135 short cls_def_cnt;
4136 short cat_def_cnt;
4137 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004138 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004139 */
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004141 Result += "\nstruct _objc_symtab {\n";
4142 Result += "\tlong sel_ref_cnt;\n";
4143 Result += "\tSEL *refs;\n";
4144 Result += "\tshort cls_def_cnt;\n";
4145 Result += "\tshort cat_def_cnt;\n";
4146 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4147 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004149 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004150 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004151 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004152 + ", " + utostr(CatDefCount) + "\n";
4153 for (int i = 0; i < ClsDefCount; i++) {
4154 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004155 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004156 Result += "\n";
4157 }
Mike Stump1eb44332009-09-09 15:08:12 +00004158
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004159 for (int i = 0; i < CatDefCount; i++) {
4160 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004161 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004162 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004163 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004164 Result += "\n";
4165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004167 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004168
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004169 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004171 /*
4172 struct _objc_module {
4173 long version;
4174 long size;
4175 const char *name;
4176 struct _objc_symtab *symtab;
4177 }
4178 */
Mike Stump1eb44332009-09-09 15:08:12 +00004179
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004180 Result += "\nstruct _objc_module {\n";
4181 Result += "\tlong version;\n";
4182 Result += "\tlong size;\n";
4183 Result += "\tconst char *name;\n";
4184 Result += "\tstruct _objc_symtab *symtab;\n";
4185 Result += "};\n\n";
4186 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004187 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004188 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004189 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004190 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004191
Francois Pichet62ec1f22011-09-17 17:15:52 +00004192 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004193 if (ProtocolExprDecls.size()) {
4194 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4195 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004196 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004197 E = ProtocolExprDecls.end(); I != E; ++I) {
4198 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4199 Result += (*I)->getNameAsString();
4200 Result += " = &_OBJC_PROTOCOL_";
4201 Result += (*I)->getNameAsString();
4202 Result += ";\n";
4203 }
4204 Result += "#pragma data_seg(pop)\n\n";
4205 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004206 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004207 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004208 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4209 Result += "&_OBJC_MODULES;\n";
4210 Result += "#pragma data_seg(pop)\n\n";
4211 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004212}
Chris Lattner311ff022007-10-16 22:36:42 +00004213
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004214void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4215 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004216 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004217 assert(BlockByRefDeclNo.count(VD) &&
4218 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004219 if (def)
4220 ResultStr += "struct ";
4221 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004222 "_" + utostr(BlockByRefDeclNo[VD]) ;
4223}
4224
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004225static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4226 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4227 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4228 return false;
4229}
4230
Steve Naroff54055232008-10-27 17:20:55 +00004231std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004232 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004233 std::string Tag) {
4234 const FunctionType *AFT = CE->getFunctionType();
4235 QualType RT = AFT->getResultType();
4236 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004237 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004238 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004239
Steve Naroff54055232008-10-27 17:20:55 +00004240 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004241
Douglas Gregor72564e72009-02-26 23:50:07 +00004242 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004243 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004244 // block (to reference imported block decl refs).
4245 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004246 } else if (BD->param_empty()) {
4247 S += "(" + StructRef + " *__cself)";
4248 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004249 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004250 assert(FT && "SynthesizeBlockFunc: No function proto");
4251 S += '(';
4252 // first add the implicit argument.
4253 S += StructRef + " *__cself, ";
4254 std::string ParamStr;
4255 for (BlockDecl::param_iterator AI = BD->param_begin(),
4256 E = BD->param_end(); AI != E; ++AI) {
4257 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004258 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004259 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004260 if (convertBlockPointerToFunctionPointer(QT))
4261 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004262 else
4263 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004264 S += ParamStr;
4265 }
4266 if (FT->isVariadic()) {
4267 if (!BD->param_empty()) S += ", ";
4268 S += "...";
4269 }
4270 S += ')';
4271 }
4272 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Steve Naroff54055232008-10-27 17:20:55 +00004274 // Create local declarations to avoid rewriting all closure decl ref exprs.
4275 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004276 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004277 E = BlockByRefDecls.end(); I != E; ++I) {
4278 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004279 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004280 std::string TypeString;
4281 RewriteByRefString(TypeString, Name, (*I));
4282 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004283 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004284 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004285 }
Steve Naroff54055232008-10-27 17:20:55 +00004286 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004287 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004288 E = BlockByCopyDecls.end(); I != E; ++I) {
4289 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004290 // Handle nested closure invocation. For example:
4291 //
4292 // void (^myImportedClosure)(void);
4293 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004294 //
Steve Naroff54055232008-10-27 17:20:55 +00004295 // void (^anotherClosure)(void);
4296 // anotherClosure = ^(void) {
4297 // myImportedClosure(); // import and invoke the closure
4298 // };
4299 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004300 if (isTopLevelBlockPointerType((*I)->getType())) {
4301 RewriteBlockPointerTypeVariable(S, (*I));
4302 S += " = (";
4303 RewriteBlockPointerType(S, (*I)->getType());
4304 S += ")";
4305 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4306 }
4307 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004308 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004309 QualType QT = (*I)->getType();
4310 if (HasLocalVariableExternalStorage(*I))
4311 QT = Context->getPointerType(QT);
4312 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004313 S += Name + " = __cself->" +
4314 (*I)->getNameAsString() + "; // bound by copy\n";
4315 }
Steve Naroff54055232008-10-27 17:20:55 +00004316 }
4317 std::string RewrittenStr = RewrittenBlockExprs[CE];
4318 const char *cstr = RewrittenStr.c_str();
4319 while (*cstr++ != '{') ;
4320 S += cstr;
4321 S += "\n";
4322 return S;
4323}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004324
Steve Naroff54055232008-10-27 17:20:55 +00004325std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004326 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004327 std::string Tag) {
4328 std::string StructRef = "struct " + Tag;
4329 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004330
Steve Naroff54055232008-10-27 17:20:55 +00004331 S += funcName;
4332 S += "_block_copy_" + utostr(i);
4333 S += "(" + StructRef;
4334 S += "*dst, " + StructRef;
4335 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004336 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004337 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004338 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004339 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004340 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004341 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004342 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004343 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004344 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004345 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004346 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004347 else
4348 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004349 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004350 S += "}\n";
4351
Steve Naroff54055232008-10-27 17:20:55 +00004352 S += "\nstatic void __";
4353 S += funcName;
4354 S += "_block_dispose_" + utostr(i);
4355 S += "(" + StructRef;
4356 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004357 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004358 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004359 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004360 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004361 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004362 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004363 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004364 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004365 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004366 else
4367 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004368 }
Mike Stump1eb44332009-09-09 15:08:12 +00004369 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004370 return S;
4371}
4372
Steve Naroff01aec112009-12-06 21:14:13 +00004373std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4374 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004375 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004376 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Steve Naroff54055232008-10-27 17:20:55 +00004378 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004379 S += " struct " + Desc;
4380 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Steve Naroff01aec112009-12-06 21:14:13 +00004382 Constructor += "(void *fp, "; // Invoke function pointer.
4383 Constructor += "struct " + Desc; // Descriptor pointer.
4384 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Steve Naroff54055232008-10-27 17:20:55 +00004386 if (BlockDeclRefs.size()) {
4387 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004388 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004389 E = BlockByCopyDecls.end(); I != E; ++I) {
4390 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004391 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004392 std::string ArgName = "_" + FieldName;
4393 // Handle nested closure invocation. For example:
4394 //
4395 // void (^myImportedBlock)(void);
4396 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004397 //
Steve Naroff54055232008-10-27 17:20:55 +00004398 // void (^anotherBlock)(void);
4399 // anotherBlock = ^(void) {
4400 // myImportedBlock(); // import and invoke the closure
4401 // };
4402 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004403 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004404 S += "struct __block_impl *";
4405 Constructor += ", void *" + ArgName;
4406 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004407 QualType QT = (*I)->getType();
4408 if (HasLocalVariableExternalStorage(*I))
4409 QT = Context->getPointerType(QT);
4410 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4411 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004412 Constructor += ", " + ArgName;
4413 }
4414 S += FieldName + ";\n";
4415 }
4416 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004417 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004418 E = BlockByRefDecls.end(); I != E; ++I) {
4419 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004420 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004421 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004422 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004423 std::string TypeString;
4424 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004425 TypeString += " *";
4426 FieldName = TypeString + FieldName;
4427 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004428 Constructor += ", " + ArgName;
4429 }
4430 S += FieldName + "; // by ref\n";
4431 }
4432 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004433 Constructor += ", int flags=0)";
4434 // Initialize all "by copy" arguments.
4435 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004436 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004437 E = BlockByCopyDecls.end(); I != E; ++I) {
4438 std::string Name = (*I)->getNameAsString();
4439 if (firsTime) {
4440 Constructor += " : ";
4441 firsTime = false;
4442 }
4443 else
4444 Constructor += ", ";
4445 if (isTopLevelBlockPointerType((*I)->getType()))
4446 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4447 else
4448 Constructor += Name + "(_" + Name + ")";
4449 }
4450 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004451 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004452 E = BlockByRefDecls.end(); I != E; ++I) {
4453 std::string Name = (*I)->getNameAsString();
4454 if (firsTime) {
4455 Constructor += " : ";
4456 firsTime = false;
4457 }
4458 else
4459 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004460 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004461 }
4462
4463 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004464 if (GlobalVarDecl)
4465 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4466 else
4467 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004468 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Steve Naroff01aec112009-12-06 21:14:13 +00004470 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004471 } else {
4472 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004473 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004474 if (GlobalVarDecl)
4475 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4476 else
4477 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004478 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4479 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004480 }
4481 Constructor += " ";
4482 Constructor += "}\n";
4483 S += Constructor;
4484 S += "};\n";
4485 return S;
4486}
4487
Steve Naroff01aec112009-12-06 21:14:13 +00004488std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4489 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004490 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004491 unsigned hasCopy) {
4492 std::string S = "\nstatic struct " + DescTag;
4493
4494 S += " {\n unsigned long reserved;\n";
4495 S += " unsigned long Block_size;\n";
4496 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004497 S += " void (*copy)(struct ";
4498 S += ImplTag; S += "*, struct ";
4499 S += ImplTag; S += "*);\n";
4500
4501 S += " void (*dispose)(struct ";
4502 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004503 }
4504 S += "} ";
4505
4506 S += DescTag + "_DATA = { 0, sizeof(struct ";
4507 S += ImplTag + ")";
4508 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004509 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4510 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004511 }
4512 S += "};\n";
4513 return S;
4514}
4515
Steve Naroff54055232008-10-27 17:20:55 +00004516void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004517 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004518 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004519 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004520 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004521 bool RewriteSC = (GlobalVarDecl &&
4522 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004523 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004524 GlobalVarDecl->getType().getCVRQualifiers());
4525 if (RewriteSC) {
4526 std::string SC(" void __");
4527 SC += GlobalVarDecl->getNameAsString();
4528 SC += "() {}";
4529 InsertText(FunLocStart, SC);
4530 }
4531
Steve Naroff54055232008-10-27 17:20:55 +00004532 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004533 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4534 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004535 // Need to copy-in the inner copied-in variables not actually used in this
4536 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004537 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4538 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4539 ValueDecl *VD = Exp->getDecl();
4540 BlockDeclRefs.push_back(Exp);
4541 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4542 BlockByCopyDeclsPtrSet.insert(VD);
4543 BlockByCopyDecls.push_back(VD);
4544 }
4545 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4546 BlockByRefDeclsPtrSet.insert(VD);
4547 BlockByRefDecls.push_back(VD);
4548 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004549 // imported objects in the inner blocks not used in the outer
4550 // blocks must be copied/disposed in the outer block as well.
4551 if (Exp->isByRef() ||
4552 VD->getType()->isObjCObjectPointerType() ||
4553 VD->getType()->isBlockPointerType())
4554 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004555 }
Steve Naroff54055232008-10-27 17:20:55 +00004556
Daniel Dunbar4087f272010-08-17 22:39:59 +00004557 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4558 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Steve Naroff01aec112009-12-06 21:14:13 +00004560 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004561
Benjamin Kramerd999b372010-02-14 14:14:16 +00004562 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004563
Steve Naroff01aec112009-12-06 21:14:13 +00004564 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Benjamin Kramerd999b372010-02-14 14:14:16 +00004566 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004567
4568 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004569 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004570 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004571 }
Steve Naroff01aec112009-12-06 21:14:13 +00004572 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4573 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004574 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Steve Naroff54055232008-10-27 17:20:55 +00004576 BlockDeclRefs.clear();
4577 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004578 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004579 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004580 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004581 ImportedBlockDecls.clear();
4582 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004583 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004584 // Must insert any 'const/volatile/static here. Since it has been
4585 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004586 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004587 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004588 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004589 if (GlobalVarDecl->getType().isConstQualified())
4590 SC += "const ";
4591 if (GlobalVarDecl->getType().isVolatileQualified())
4592 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004593 if (GlobalVarDecl->getType().isRestrictQualified())
4594 SC += "restrict ";
4595 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004596 }
4597
Steve Naroff54055232008-10-27 17:20:55 +00004598 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004599 InnerDeclRefsCount.clear();
4600 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004601 RewrittenBlockExprs.clear();
4602}
4603
4604void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4605 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004606 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004607
Steve Naroff54055232008-10-27 17:20:55 +00004608 SynthesizeBlockLiterals(FunLocStart, FuncName);
4609}
4610
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004611static void BuildUniqueMethodName(std::string &Name,
4612 ObjCMethodDecl *MD) {
4613 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004614 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004615 Name += "__" + MD->getSelector().getAsString();
4616 // Convert colons to underscores.
4617 std::string::size_type loc = 0;
4618 while ((loc = Name.find(":", loc)) != std::string::npos)
4619 Name.replace(loc, 1, "_");
4620}
4621
Steve Naroff54055232008-10-27 17:20:55 +00004622void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004623 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4624 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004625 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004626 std::string FuncName;
4627 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004628 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004629}
4630
4631void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004632 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004633 if (*CI) {
4634 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4635 GetBlockDeclRefExprs(CBE->getBody());
4636 else
4637 GetBlockDeclRefExprs(*CI);
4638 }
4639 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004640 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004641 // FIXME: Handle enums.
4642 if (!isa<FunctionDecl>(CDRE->getDecl()))
4643 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004644 }
4645 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4646 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4647 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004648 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4649 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004650 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004651 BlockDeclRefs.push_back(BDRE);
4652 }
4653
Steve Naroff54055232008-10-27 17:20:55 +00004654 return;
4655}
4656
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004657void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004658 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004659 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004660 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004661 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004662 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4663 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004664 GetInnerBlockDeclRefExprs(CBE->getBody(),
4665 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004666 InnerContexts);
4667 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004668 else
4669 GetInnerBlockDeclRefExprs(*CI,
4670 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004671 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004672
4673 }
4674 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004675 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004676 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004677 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004678 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004679 }
4680 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4681 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4682 if (Var->isFunctionOrMethodVarDecl())
4683 ImportedLocalExternalDecls.insert(Var);
4684 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004685
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004686 return;
4687}
4688
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004689/// convertFunctionTypeOfBlocks - This routine converts a function type
4690/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004691/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004692/// all block pointers to function pointers.
4693QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4694 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4695 // FTP will be null for closures that don't take arguments.
4696 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004697 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004698 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004699 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004700
4701 if (FTP) {
4702 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4703 E = FTP->arg_type_end(); I && (I != E); ++I) {
4704 QualType t = *I;
4705 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004706 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004707 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004708 ArgTypes.push_back(t);
4709 }
4710 }
4711 QualType FuncType;
4712 // FIXME. Does this work if block takes no argument but has a return type
4713 // which is of block type?
4714 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004715 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004716 else FuncType = QualType(FT, 0);
4717 return FuncType;
4718}
4719
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004720Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004721 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004722 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004724 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004725 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004726 } else if (const BlockDeclRefExpr *CDRE =
4727 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004728 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004729 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004730 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004731 }
4732 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4733 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4734 }
4735 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4736 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4737 else if (const ConditionalOperator *CEXPR =
4738 dyn_cast<ConditionalOperator>(BlockExp)) {
4739 Expr *LHSExp = CEXPR->getLHS();
4740 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4741 Expr *RHSExp = CEXPR->getRHS();
4742 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4743 Expr *CONDExp = CEXPR->getCond();
4744 ConditionalOperator *CondExpr =
4745 new (Context) ConditionalOperator(CONDExp,
4746 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004747 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004748 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004749 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004750 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4751 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004752 } else {
4753 assert(1 && "RewriteBlockClass: Bad type");
4754 }
4755 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004756 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004757 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004758 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004759 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004761 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004762 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004763 &Context->Idents.get("__block_impl"));
4764 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004765
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004766 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004767 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004768
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004769 // Push the block argument type.
4770 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004771 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004772 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004773 E = FTP->arg_type_end(); I && (I != E); ++I) {
4774 QualType t = *I;
4775 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004776 if (!convertBlockPointerToFunctionPointer(t))
4777 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004778 ArgTypes.push_back(t);
4779 }
Steve Naroff54055232008-10-27 17:20:55 +00004780 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004781 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004782 QualType PtrToFuncCastType
4783 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004785 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004786
John McCall9d125032010-01-15 18:39:57 +00004787 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004788 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004789 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004790 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004791 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4792 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004793 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Douglas Gregor44b43212008-12-11 16:49:14 +00004795 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004796 SourceLocation(),
4797 &Context->Idents.get("FuncPtr"),
4798 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004799 /*BitWidth=*/0, /*Mutable=*/true,
4800 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004801 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004802 FD->getType(), VK_LValue,
4803 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004804
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004805
John McCall9d125032010-01-15 18:39:57 +00004806 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004807 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004808 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004809
Chris Lattner5f9e2722011-07-23 10:55:15 +00004810 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004811 // Add the implicit argument.
4812 BlkExprs.push_back(BlkCast);
4813 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004814 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004815 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004816 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004817 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004818 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4819 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004820 Exp->getType(), VK_RValue,
4821 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004822 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004823}
4824
Steve Naroff621edce2009-04-29 16:37:50 +00004825// We need to return the rewritten expression to handle cases where the
4826// BlockDeclRefExpr is embedded in another expression being rewritten.
4827// For example:
4828//
4829// int main() {
4830// __block Foo *f;
4831// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004832//
Steve Naroff621edce2009-04-29 16:37:50 +00004833// void (^myblock)() = ^() {
4834// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4835// i = 77;
4836// };
4837//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004838Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004839 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004840 // for each DeclRefExp where BYREFVAR is name of the variable.
4841 ValueDecl *VD;
4842 bool isArrow = true;
4843 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4844 VD = BDRE->getDecl();
4845 else {
4846 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4847 isArrow = false;
4848 }
4849
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004850 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004851 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004852 &Context->Idents.get("__forwarding"),
4853 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004854 /*BitWidth=*/0, /*Mutable=*/true,
4855 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004856 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4857 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004858 FD->getType(), VK_LValue,
4859 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004860
Chris Lattner5f9e2722011-07-23 10:55:15 +00004861 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004862 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004863 &Context->Idents.get(Name),
4864 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004865 /*BitWidth=*/0, /*Mutable=*/true,
4866 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004867 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004868 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004869
4870
4871
Steve Naroffdf8570d2009-02-02 17:19:26 +00004872 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004873 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4874 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004875 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004876 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004877 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004878}
4879
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004880// Rewrites the imported local variable V with external storage
4881// (static, extern, etc.) as *V
4882//
4883Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4884 ValueDecl *VD = DRE->getDecl();
4885 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4886 if (!ImportedLocalExternalDecls.count(Var))
4887 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004888 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4889 VK_LValue, OK_Ordinary,
4890 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004891 // Need parens to enforce precedence.
4892 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4893 Exp);
4894 ReplaceStmt(DRE, PE);
4895 return PE;
4896}
4897
Steve Naroffb2f9e512008-11-03 23:29:32 +00004898void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4899 SourceLocation LocStart = CE->getLParenLoc();
4900 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004901
4902 // Need to avoid trying to rewrite synthesized casts.
4903 if (LocStart.isInvalid())
4904 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004905 // Need to avoid trying to rewrite casts contained in macros.
4906 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4907 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004908
Steve Naroff54055232008-10-27 17:20:55 +00004909 const char *startBuf = SM->getCharacterData(LocStart);
4910 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004911 QualType QT = CE->getType();
4912 const Type* TypePtr = QT->getAs<Type>();
4913 if (isa<TypeOfExprType>(TypePtr)) {
4914 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4915 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4916 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004917 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004918 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004919 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004920 return;
4921 }
Steve Naroff54055232008-10-27 17:20:55 +00004922 // advance the location to startArgList.
4923 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Steve Naroff54055232008-10-27 17:20:55 +00004925 while (*argPtr++ && (argPtr < endBuf)) {
4926 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004927 case '^':
4928 // Replace the '^' with '*'.
4929 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004930 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004931 break;
Steve Naroff54055232008-10-27 17:20:55 +00004932 }
4933 }
4934 return;
4935}
4936
4937void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4938 SourceLocation DeclLoc = FD->getLocation();
4939 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Steve Naroff54055232008-10-27 17:20:55 +00004941 // We have 1 or more arguments that have closure pointers.
4942 const char *startBuf = SM->getCharacterData(DeclLoc);
4943 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Steve Naroff54055232008-10-27 17:20:55 +00004945 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004946
Steve Naroff54055232008-10-27 17:20:55 +00004947 parenCount++;
4948 // advance the location to startArgList.
4949 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4950 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004951
Steve Naroff54055232008-10-27 17:20:55 +00004952 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Steve Naroff54055232008-10-27 17:20:55 +00004954 while (*argPtr++ && parenCount) {
4955 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004956 case '^':
4957 // Replace the '^' with '*'.
4958 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004959 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004960 break;
4961 case '(':
4962 parenCount++;
4963 break;
4964 case ')':
4965 parenCount--;
4966 break;
Steve Naroff54055232008-10-27 17:20:55 +00004967 }
4968 }
4969 return;
4970}
4971
4972bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004973 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004974 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004975 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004976 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004977 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004978 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004979 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004980 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004981 }
4982 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004983 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004984 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004985 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004986 return true;
4987 }
4988 return false;
4989}
4990
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004991bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4992 const FunctionProtoType *FTP;
4993 const PointerType *PT = QT->getAs<PointerType>();
4994 if (PT) {
4995 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4996 } else {
4997 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4998 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4999 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5000 }
5001 if (FTP) {
5002 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005003 E = FTP->arg_type_end(); I != E; ++I) {
5004 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005005 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005006 if ((*I)->isObjCObjectPointerType() &&
5007 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5008 return true;
5009 }
5010
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005011 }
5012 return false;
5013}
5014
Ted Kremenek8189cde2009-02-07 01:47:29 +00005015void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5016 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005017 const char *argPtr = strchr(Name, '(');
5018 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005019
Steve Naroff54055232008-10-27 17:20:55 +00005020 LParen = argPtr; // output the start.
5021 argPtr++; // skip past the left paren.
5022 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Naroff54055232008-10-27 17:20:55 +00005024 while (*argPtr && parenCount) {
5025 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005026 case '(': parenCount++; break;
5027 case ')': parenCount--; break;
5028 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005029 }
5030 if (parenCount) argPtr++;
5031 }
5032 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5033 RParen = argPtr; // output the end
5034}
5035
5036void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5038 RewriteBlockPointerFunctionArgs(FD);
5039 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005040 }
Steve Naroff54055232008-10-27 17:20:55 +00005041 // Handle Variables and Typedefs.
5042 SourceLocation DeclLoc = ND->getLocation();
5043 QualType DeclT;
5044 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5045 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005046 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005047 DeclT = TDD->getUnderlyingType();
5048 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5049 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005050 else
Steve Naroff54055232008-10-27 17:20:55 +00005051 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005052
Steve Naroff54055232008-10-27 17:20:55 +00005053 const char *startBuf = SM->getCharacterData(DeclLoc);
5054 const char *endBuf = startBuf;
5055 // scan backward (from the decl location) for the end of the previous decl.
5056 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5057 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005058 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
5059 std::string buf;
5060 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005061 // *startBuf != '^' if we are dealing with a pointer to function that
5062 // may take block argument types (which will be handled below).
5063 if (*startBuf == '^') {
5064 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005065 buf = '*';
5066 startBuf++;
5067 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005068 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005069 while (*startBuf != ')') {
5070 buf += *startBuf;
5071 startBuf++;
5072 OrigLength++;
5073 }
5074 buf += ')';
5075 OrigLength++;
5076
5077 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5078 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005079 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005080 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005081 DeclLoc = ND->getLocation();
5082 startBuf = SM->getCharacterData(DeclLoc);
5083 const char *argListBegin, *argListEnd;
5084 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5085 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005086 if (*argListBegin == '^')
5087 buf += '*';
5088 else if (*argListBegin == '<') {
5089 buf += "/*";
5090 buf += *argListBegin++;
5091 OrigLength++;;
5092 while (*argListBegin != '>') {
5093 buf += *argListBegin++;
5094 OrigLength++;
5095 }
5096 buf += *argListBegin;
5097 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005098 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005099 else
5100 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005101 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005102 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005103 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005104 buf += ')';
5105 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005106 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005107 ReplaceText(Start, OrigLength, buf);
5108
Steve Naroff54055232008-10-27 17:20:55 +00005109 return;
5110}
5111
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005112
5113/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5114/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5115/// struct Block_byref_id_object *src) {
5116/// _Block_object_assign (&_dest->object, _src->object,
5117/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5118/// [|BLOCK_FIELD_IS_WEAK]) // object
5119/// _Block_object_assign(&_dest->object, _src->object,
5120/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5121/// [|BLOCK_FIELD_IS_WEAK]) // block
5122/// }
5123/// And:
5124/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5125/// _Block_object_dispose(_src->object,
5126/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5127/// [|BLOCK_FIELD_IS_WEAK]) // object
5128/// _Block_object_dispose(_src->object,
5129/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5130/// [|BLOCK_FIELD_IS_WEAK]) // block
5131/// }
5132
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005133std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5134 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005135 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005136 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005137 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005138 CopyDestroyCache.insert(flag);
5139 S = "static void __Block_byref_id_object_copy_";
5140 S += utostr(flag);
5141 S += "(void *dst, void *src) {\n";
5142
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005143 // offset into the object pointer is computed as:
5144 // void * + void* + int + int + void* + void *
5145 unsigned IntSize =
5146 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5147 unsigned VoidPtrSize =
5148 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5149
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005150 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005151 S += " _Block_object_assign((char*)dst + ";
5152 S += utostr(offset);
5153 S += ", *(void * *) ((char*)src + ";
5154 S += utostr(offset);
5155 S += "), ";
5156 S += utostr(flag);
5157 S += ");\n}\n";
5158
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005159 S += "static void __Block_byref_id_object_dispose_";
5160 S += utostr(flag);
5161 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005162 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5163 S += utostr(offset);
5164 S += "), ";
5165 S += utostr(flag);
5166 S += ");\n}\n";
5167 return S;
5168}
5169
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005170/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5171/// the declaration into:
5172/// struct __Block_byref_ND {
5173/// void *__isa; // NULL for everything except __weak pointers
5174/// struct __Block_byref_ND *__forwarding;
5175/// int32_t __flags;
5176/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005177/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5178/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005179/// typex ND;
5180/// };
5181///
5182/// It then replaces declaration of ND variable with:
5183/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5184/// __size=sizeof(struct __Block_byref_ND),
5185/// ND=initializer-if-any};
5186///
5187///
5188void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005189 // Insert declaration for the function in which block literal is
5190 // used.
5191 if (CurFunctionDeclToDeclareForBlock)
5192 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005193 int flag = 0;
5194 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005195 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005196 if (DeclLoc.isInvalid())
5197 // If type location is missing, it is because of missing type (a warning).
5198 // Use variable's location which is good for this case.
5199 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005200 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005201 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005202 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005203 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005204 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005205 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005206 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005207 ByrefType += " {\n";
5208 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005209 RewriteByRefString(ByrefType, Name, ND);
5210 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005211 ByrefType += " int __flags;\n";
5212 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005213 // Add void *__Block_byref_id_object_copy;
5214 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005215 QualType Ty = ND->getType();
5216 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5217 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005218 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5219 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005220 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005221
5222 QualType T = Ty;
5223 (void)convertBlockPointerToFunctionPointer(T);
5224 T.getAsStringInternal(Name, Context->PrintingPolicy);
5225
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005226 ByrefType += " " + Name + ";\n";
5227 ByrefType += "};\n";
5228 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005229 SourceLocation FunLocStart;
5230 if (CurFunctionDef)
5231 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5232 else {
5233 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5234 FunLocStart = CurMethodDef->getLocStart();
5235 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005236 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005237 if (Ty.isObjCGCWeak()) {
5238 flag |= BLOCK_FIELD_IS_WEAK;
5239 isa = 1;
5240 }
5241
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005242 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005243 flag = BLOCK_BYREF_CALLER;
5244 QualType Ty = ND->getType();
5245 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5246 if (Ty->isBlockPointerType())
5247 flag |= BLOCK_FIELD_IS_BLOCK;
5248 else
5249 flag |= BLOCK_FIELD_IS_OBJECT;
5250 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005251 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005252 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005253 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005254
5255 // struct __Block_byref_ND ND =
5256 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5257 // initializer-if-any};
5258 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005259 unsigned flags = 0;
5260 if (HasCopyAndDispose)
5261 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005262 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005263 ByrefType.clear();
5264 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005265 std::string ForwardingCastType("(");
5266 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005267 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005268 ByrefType += " " + Name + " = {(void*)";
5269 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005270 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005271 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005272 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005273 ByrefType += "sizeof(";
5274 RewriteByRefString(ByrefType, Name, ND);
5275 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005276 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005277 ByrefType += ", __Block_byref_id_object_copy_";
5278 ByrefType += utostr(flag);
5279 ByrefType += ", __Block_byref_id_object_dispose_";
5280 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005281 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005282 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005283 unsigned nameSize = Name.size();
5284 // for block or function pointer declaration. Name is aleady
5285 // part of the declaration.
5286 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5287 nameSize = 1;
5288 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005289 }
5290 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005291 SourceLocation startLoc;
5292 Expr *E = ND->getInit();
5293 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5294 startLoc = ECE->getLParenLoc();
5295 else
5296 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005297 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005298 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005299 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005300 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005301 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005302 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005303 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005304 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005305 ByrefType += "sizeof(";
5306 RewriteByRefString(ByrefType, Name, ND);
5307 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005308 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005309 ByrefType += "__Block_byref_id_object_copy_";
5310 ByrefType += utostr(flag);
5311 ByrefType += ", __Block_byref_id_object_dispose_";
5312 ByrefType += utostr(flag);
5313 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005314 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005315 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005316
5317 // Complete the newly synthesized compound expression by inserting a right
5318 // curly brace before the end of the declaration.
5319 // FIXME: This approach avoids rewriting the initializer expression. It
5320 // also assumes there is only one declarator. For example, the following
5321 // isn't currently supported by this routine (in general):
5322 //
5323 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5324 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005325 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5326 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005327 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5328 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005329 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005330
Benjamin Kramerd999b372010-02-14 14:14:16 +00005331 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005332 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005333 return;
5334}
5335
Mike Stump1eb44332009-09-09 15:08:12 +00005336void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005337 // Add initializers for any closure decl refs.
5338 GetBlockDeclRefExprs(Exp->getBody());
5339 if (BlockDeclRefs.size()) {
5340 // Unique all "by copy" declarations.
5341 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005342 if (!BlockDeclRefs[i]->isByRef()) {
5343 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5344 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5345 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5346 }
5347 }
Steve Naroff54055232008-10-27 17:20:55 +00005348 // Unique all "by ref" declarations.
5349 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5350 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005351 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5352 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5353 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5354 }
Steve Naroff54055232008-10-27 17:20:55 +00005355 }
5356 // Find any imported blocks...they will need special attention.
5357 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005358 if (BlockDeclRefs[i]->isByRef() ||
5359 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005360 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005361 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005362 }
5363}
5364
Chris Lattner5f9e2722011-07-23 10:55:15 +00005365FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005366 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005367 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005368 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5369 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005370 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005371}
5372
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005373Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005374 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005375 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005376 Blocks.push_back(Exp);
5377
5378 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005379
5380 // Add inner imported variables now used in current block.
5381 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005382 if (!InnerBlockDeclRefs.empty()) {
5383 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5384 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5385 ValueDecl *VD = Exp->getDecl();
5386 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005387 // We need to save the copied-in variables in nested
5388 // blocks because it is needed at the end for some of the API generations.
5389 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005390 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5391 BlockDeclRefs.push_back(Exp);
5392 BlockByCopyDeclsPtrSet.insert(VD);
5393 BlockByCopyDecls.push_back(VD);
5394 }
5395 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5396 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5397 BlockDeclRefs.push_back(Exp);
5398 BlockByRefDeclsPtrSet.insert(VD);
5399 BlockByRefDecls.push_back(VD);
5400 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005401 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005402 // Find any imported blocks...they will need special attention.
5403 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5404 if (InnerBlockDeclRefs[i]->isByRef() ||
5405 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5406 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5407 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005408 }
5409 InnerDeclRefsCount.push_back(countOfInnerDecls);
5410
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005412
Steve Narofffa15fd92008-10-28 20:29:00 +00005413 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005414 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005415 else if (CurMethodDef)
5416 BuildUniqueMethodName(FuncName, CurMethodDef);
5417 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005418 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005419
Steve Narofffa15fd92008-10-28 20:29:00 +00005420 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005421
Steve Narofffa15fd92008-10-28 20:29:00 +00005422 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5423 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Steve Narofffa15fd92008-10-28 20:29:00 +00005425 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005426 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5427 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005428
5429 FunctionDecl *FD;
5430 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005431
Steve Narofffa15fd92008-10-28 20:29:00 +00005432 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005433 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005434 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5435 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005436
Chris Lattner5f9e2722011-07-23 10:55:15 +00005437 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005438
Steve Narofffdc03722008-10-29 21:23:59 +00005439 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005440 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005441 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005442 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005443 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005444 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005445 InitExprs.push_back(castExpr);
5446
Steve Naroff01aec112009-12-06 21:14:13 +00005447 // Initialize the block descriptor.
5448 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005449
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005450 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5451 SourceLocation(), SourceLocation(),
5452 &Context->Idents.get(DescData.c_str()),
5453 Context->VoidPtrTy, 0,
5454 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005455 UnaryOperator *DescRefExpr =
5456 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5457 Context->VoidPtrTy,
5458 VK_LValue,
5459 SourceLocation()),
5460 UO_AddrOf,
5461 Context->getPointerType(Context->VoidPtrTy),
5462 VK_RValue, OK_Ordinary,
5463 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005464 InitExprs.push_back(DescRefExpr);
5465
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 // Add initializers for any closure decl refs.
5467 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005468 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005469 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005470 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005472 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005473 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005474 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005475 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5476 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005477 if (HasLocalVariableExternalStorage(*I)) {
5478 QualType QT = (*I)->getType();
5479 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005480 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5481 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005482 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005483 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005484 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005485 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5486 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005487 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005488 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005489 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005490 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005491 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5492 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005493 if (HasLocalVariableExternalStorage(*I)) {
5494 QualType QT = (*I)->getType();
5495 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005496 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5497 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005498 }
5499
Steve Narofffa15fd92008-10-28 20:29:00 +00005500 }
Mike Stump1eb44332009-09-09 15:08:12 +00005501 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005502 }
5503 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005504 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005505 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005506 ValueDecl *ND = (*I);
5507 std::string Name(ND->getNameAsString());
5508 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005509 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005510 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5511 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005512 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005513 SourceLocation(), SourceLocation(),
5514 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005515 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5516 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5517
Daniel Dunbar4087f272010-08-17 22:39:59 +00005518 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005519 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5520 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005521 bool isNestedCapturedVar = false;
5522 if (block)
5523 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5524 ce = block->capture_end(); ci != ce; ++ci) {
5525 const VarDecl *variable = ci->getVariable();
5526 if (variable == ND && ci->isNested()) {
5527 assert (ci->isByRef() &&
5528 "SynthBlockInitExpr - captured block variable is not byref");
5529 isNestedCapturedVar = true;
5530 break;
5531 }
5532 }
5533 // captured nested byref variable has its address passed. Do not take
5534 // its address again.
5535 if (!isNestedCapturedVar)
5536 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005537 Context->getPointerType(Exp->getType()),
5538 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005539 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005540 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005541 }
5542 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005543 if (ImportedBlockDecls.size()) {
5544 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5545 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005546 unsigned IntSize =
5547 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005548 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5549 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005550 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005551 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005552 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005553 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005554 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005555 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005556 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005557 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005558 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005559 BlockDeclRefs.clear();
5560 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005561 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005562 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005563 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005564 ImportedBlockDecls.clear();
5565 return NewRep;
5566}
5567
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005568bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5569 if (const ObjCForCollectionStmt * CS =
5570 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5571 return CS->getElement() == DS;
5572 return false;
5573}
5574
Steve Narofffa15fd92008-10-28 20:29:00 +00005575//===----------------------------------------------------------------------===//
5576// Function Body / Expression rewriting
5577//===----------------------------------------------------------------------===//
5578
Steve Naroffc77a6362008-12-04 16:24:46 +00005579// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5580// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5581// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5582// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5583// Since the rewriter isn't capable of rewriting rewritten code, it's important
5584// we get this right.
5585void RewriteObjC::CollectPropertySetters(Stmt *S) {
5586 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005587 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005588 if (*CI)
5589 CollectPropertySetters(*CI);
5590
5591 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5592 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005593 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5594 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005595 }
5596 }
5597}
5598
Steve Narofffa15fd92008-10-28 20:29:00 +00005599Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005600 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005601 isa<DoStmt>(S) || isa<ForStmt>(S))
5602 Stmts.push_back(S);
5603 else if (isa<ObjCForCollectionStmt>(S)) {
5604 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005605 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 }
Mike Stump1eb44332009-09-09 15:08:12 +00005607
Steve Narofffa15fd92008-10-28 20:29:00 +00005608 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005609
Steve Narofffa15fd92008-10-28 20:29:00 +00005610 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005611 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005612 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005613 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005614 Stmt *ChildStmt = (*CI);
5615 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005616 Expr *OldBase = IvarRefExpr->getBase();
5617 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005618 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005619 if (replaced) {
5620 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5621 ReplaceStmt(OldBase, IRE->getBase());
5622 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005623 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005624 }
5625 }
5626 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005627 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5628 if (newStmt) {
5629 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5630 if (PropSetters[PropOrImplicitRefExpr] == S) {
5631 S = newStmt;
5632 newStmt = 0;
5633 }
5634 if (newStmt)
5635 *CI = newStmt;
5636 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005637 // If dealing with an assignment with LHS being a property reference
5638 // expression, the entire assignment tree is rewritten into a property
5639 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5640 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005641 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005642 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005643 if (PropSetters[Exp]) {
5644 ++CI;
5645 continue;
5646 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005647 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005648 }
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005651 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005652 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5653 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005654 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005655 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005656 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005657 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005658 Stmt *SaveCurrentBody = CurrentBody;
5659 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005660 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005661 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005662 // block literal on rhs of a property-dot-sytax assignment
5663 // must be replaced by its synthesize ast so getRewrittenText
5664 // works as expected. In this case, what actually ends up on RHS
5665 // is the blockTranscribed which is the helper function for the
5666 // block literal; as in: self.c = ^() {[ace ARR];};
5667 bool saveDisableReplaceStmt = DisableReplaceStmt;
5668 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005669 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005670 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005671 CurrentBody = SaveCurrentBody;
5672 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005673 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005675 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005676 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005677
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005678 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5679
Steve Narofffa15fd92008-10-28 20:29:00 +00005680 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005681 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005682 return blockTranscribed;
5683 }
5684 // Handle specific things.
5685 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5686 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005687
John McCall12f78a62010-12-02 01:19:52 +00005688 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005689 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5690 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5691
5692 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005693 if (BinOp) {
5694 // Because the rewriter doesn't allow us to rewrite rewritten code,
5695 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005696 DisableReplaceStmt = true;
5697 // Save the source range. Even if we disable the replacement, the
5698 // rewritten node will have been inserted into the tree. If the synthesized
5699 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005700 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005701 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5702 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005703 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005704 // Need to rewrite the ivar access expression if need be.
5705 if (isa<ObjCIvarRefExpr>(newStmt)) {
5706 bool replaced = false;
5707 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5708 }
5709
Steve Naroffb619d952008-12-09 12:56:34 +00005710 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005711 //
5712 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5713 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5714 // to see the original expression). Consider this example:
5715 //
5716 // Foo *obj1, *obj2;
5717 //
5718 // obj1.i = [obj2 rrrr];
5719 //
5720 // 'BinOp' for the previous expression looks like:
5721 //
5722 // (BinaryOperator 0x231ccf0 'int' '='
5723 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5724 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5725 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5726 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5727 //
5728 // 'newStmt' represents the rewritten message expression. For example:
5729 //
5730 // (CallExpr 0x231d300 'id':'struct objc_object *'
5731 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5732 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5733 // (CStyleCastExpr 0x231d220 'void *'
5734 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5735 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005736 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005737 // can be used as the setter argument. ReplaceStmt() will still 'see'
5738 // the original RHS (since we haven't altered BinOp).
5739 //
Mike Stump1eb44332009-09-09 15:08:12 +00005740 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005741 // node. As a result, we now leak the original AST nodes.
5742 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005743 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005744 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005745 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005746 }
5747 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005748
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5750 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005751
Steve Narofffa15fd92008-10-28 20:29:00 +00005752 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5753 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005754
Steve Narofffa15fd92008-10-28 20:29:00 +00005755 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005756#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005757 // Before we rewrite it, put the original message expression in a comment.
5758 SourceLocation startLoc = MessExpr->getLocStart();
5759 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005760
Steve Narofffa15fd92008-10-28 20:29:00 +00005761 const char *startBuf = SM->getCharacterData(startLoc);
5762 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005763
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 std::string messString;
5765 messString += "// ";
5766 messString.append(startBuf, endBuf-startBuf+1);
5767 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005768
5769 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005770 // InsertText(clang::SourceLocation, char const*, unsigned int).
5771 // InsertText(startLoc, messString.c_str(), messString.size());
5772 // Tried this, but it didn't work either...
5773 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005774#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005775 return RewriteMessageExpr(MessExpr);
5776 }
Mike Stump1eb44332009-09-09 15:08:12 +00005777
Steve Narofffa15fd92008-10-28 20:29:00 +00005778 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5779 return RewriteObjCTryStmt(StmtTry);
5780
5781 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5782 return RewriteObjCSynchronizedStmt(StmtTry);
5783
5784 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5785 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005786
Steve Narofffa15fd92008-10-28 20:29:00 +00005787 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5788 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005789
5790 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005791 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005792 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005793 OrigStmtRange.getEnd());
5794 if (BreakStmt *StmtBreakStmt =
5795 dyn_cast<BreakStmt>(S))
5796 return RewriteBreakStmt(StmtBreakStmt);
5797 if (ContinueStmt *StmtContinueStmt =
5798 dyn_cast<ContinueStmt>(S))
5799 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005800
5801 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005802 // and cast exprs.
5803 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5804 // FIXME: What we're doing here is modifying the type-specifier that
5805 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005806 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005807 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5808 // the context of an ObjCForCollectionStmt. For example:
5809 // NSArray *someArray;
5810 // for (id <FooProtocol> index in someArray) ;
5811 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5812 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005813 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005814 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005815
Steve Narofffa15fd92008-10-28 20:29:00 +00005816 // Blocks rewrite rules.
5817 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5818 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005819 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005820 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005821 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005822 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005823 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005824 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005825 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005826 if (VD->hasAttr<BlocksAttr>()) {
5827 static unsigned uniqueByrefDeclCount = 0;
5828 assert(!BlockByRefDeclNo.count(ND) &&
5829 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5830 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005831 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005832 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005833 else
5834 RewriteTypeOfDecl(VD);
5835 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005836 }
Richard Smith162e1c12011-04-15 14:24:37 +00005837 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005838 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005839 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005840 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005841 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5842 }
5843 }
5844 }
Mike Stump1eb44332009-09-09 15:08:12 +00005845
Steve Narofffa15fd92008-10-28 20:29:00 +00005846 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5847 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005848
5849 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005850 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5851 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005852 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5853 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005854 && "Statement stack mismatch");
5855 Stmts.pop_back();
5856 }
5857 // Handle blocks rewriting.
5858 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5859 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005860 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005861 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005862 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5863 ValueDecl *VD = DRE->getDecl();
5864 if (VD->hasAttr<BlocksAttr>())
5865 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005866 if (HasLocalVariableExternalStorage(VD))
5867 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005868 }
5869
Steve Narofffa15fd92008-10-28 20:29:00 +00005870 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005871 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005872 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005873 ReplaceStmt(S, BlockCall);
5874 return BlockCall;
5875 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005876 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005877 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005878 RewriteCastExpr(CE);
5879 }
5880#if 0
5881 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005882 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5883 ICE->getSubExpr(),
5884 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005885 // Get the new text.
5886 std::string SStr;
5887 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005888 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 const std::string &Str = Buf.str();
5890
5891 printf("CAST = %s\n", &Str[0]);
5892 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5893 delete S;
5894 return Replacement;
5895 }
5896#endif
5897 // Return this stmt unmodified.
5898 return S;
5899}
5900
Steve Naroff3d7e7862009-12-05 15:55:59 +00005901void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5902 for (RecordDecl::field_iterator i = RD->field_begin(),
5903 e = RD->field_end(); i != e; ++i) {
5904 FieldDecl *FD = *i;
5905 if (isTopLevelBlockPointerType(FD->getType()))
5906 RewriteBlockPointerDecl(FD);
5907 if (FD->getType()->isObjCQualifiedIdType() ||
5908 FD->getType()->isObjCQualifiedInterfaceType())
5909 RewriteObjCQualifiedInterfaceTypes(FD);
5910 }
5911}
5912
Steve Narofffa15fd92008-10-28 20:29:00 +00005913/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5914/// main file of the input.
5915void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5916 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005917 if (FD->isOverloadedOperator())
5918 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005919
Steve Narofffa15fd92008-10-28 20:29:00 +00005920 // Since function prototypes don't have ParmDecl's, we check the function
5921 // prototype. This enables us to rewrite function declarations and
5922 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005923 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005924
Sebastian Redld3a413d2009-04-26 20:35:05 +00005925 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005926 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005927 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005928 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005929 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005930 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005931 Body =
5932 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5933 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005934 CurrentBody = 0;
5935 if (PropParentMap) {
5936 delete PropParentMap;
5937 PropParentMap = 0;
5938 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005939 // This synthesizes and inserts the block "impl" struct, invoke function,
5940 // and any copy/dispose helper functions.
5941 InsertBlockLiteralsWithinFunction(FD);
5942 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005943 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005944 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005945 return;
5946 }
5947 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005948 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005949 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005950 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005951 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005952 Body =
5953 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5954 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005955 CurrentBody = 0;
5956 if (PropParentMap) {
5957 delete PropParentMap;
5958 PropParentMap = 0;
5959 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005960 InsertBlockLiteralsWithinMethod(MD);
5961 CurMethodDef = 0;
5962 }
5963 }
5964 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5965 ClassImplementation.push_back(CI);
5966 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5967 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005968 else if (isa<ObjCClassDecl>(D))
5969 assert(false && "RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005970 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5971 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005972 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005973 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005974 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005975 CheckFunctionPointerDecl(VD->getType(), VD);
5976 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005977 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005978 RewriteCastExpr(CE);
5979 }
5980 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005981 } else if (VD->getType()->isRecordType()) {
5982 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5983 if (RD->isDefinition())
5984 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005985 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005986 if (VD->getInit()) {
5987 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005988 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005989 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005990 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005991 CurrentBody = 0;
5992 if (PropParentMap) {
5993 delete PropParentMap;
5994 PropParentMap = 0;
5995 }
Mike Stump1eb44332009-09-09 15:08:12 +00005996 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005997 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005998 GlobalVarDecl = 0;
5999
6000 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00006001 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00006002 RewriteCastExpr(CE);
6003 }
6004 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006005 return;
6006 }
Richard Smith162e1c12011-04-15 14:24:37 +00006007 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006008 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006009 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006010 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006011 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6012 return;
6013 }
6014 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00006015 if (RD->isDefinition())
6016 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006017 return;
6018 }
6019 // Nothing yet.
6020}
6021
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006022void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006023 if (Diags.hasErrorOccurred())
6024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006025
Steve Narofffa15fd92008-10-28 20:29:00 +00006026 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006027
Steve Naroff621edce2009-04-29 16:37:50 +00006028 // Here's a great place to add any extra declarations that may be needed.
6029 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006030 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006031 E = ProtocolExprDecls.end(); I != E; ++I)
6032 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6033
Benjamin Kramerd999b372010-02-14 14:14:16 +00006034 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006035 if (ClassImplementation.size() || CategoryImplementation.size())
6036 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006037
Steve Narofffa15fd92008-10-28 20:29:00 +00006038 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6039 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006040 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006041 Rewrite.getRewriteBufferFor(MainFileID)) {
6042 //printf("Changed:\n");
6043 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6044 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006045 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006046 }
Steve Narofface66252008-11-13 20:07:04 +00006047
Steve Naroff621edce2009-04-29 16:37:50 +00006048 if (ClassImplementation.size() || CategoryImplementation.size() ||
6049 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006050 // Rewrite Objective-c meta data*
6051 std::string ResultStr;
6052 SynthesizeMetaDataIntoBuffer(ResultStr);
6053 // Emit metadata.
6054 *OutFile << ResultStr;
6055 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006056 OutFile->flush();
6057}