blob: f02e77e92b782fdebd8f652914e24a4db213f11b [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;
David Blaikied6471f72011-09-25 23:23:43 +000058 DiagnosticsEngine &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 Naroff4c3580e2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000145
Steve Naroff54055232008-10-27 17:20:55 +0000146 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000147 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000148 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Steve Naroffb619d952008-12-09 12:56:34 +0000150 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000151 class DisableReplaceStmtScope {
152 RewriteObjC &R;
153 bool SavedValue;
154
155 public:
156 DisableReplaceStmtScope(RewriteObjC &R)
157 : R(R), SavedValue(R.DisableReplaceStmt) {
158 R.DisableReplaceStmt = true;
159 }
160 ~DisableReplaceStmtScope() {
161 R.DisableReplaceStmt = SavedValue;
162 }
163 };
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Nick Lewycky7e749242010-10-31 21:07:24 +0000165 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000166 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000167 virtual void Initialize(ASTContext &context);
168
Chris Lattnerf04da132007-10-24 17:06:59 +0000169 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000170 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172 if (isa<ObjCClassDecl>((*I))) {
173 RewriteForwardClassDecl(D);
174 break;
175 }
Chris Lattner682bf922009-03-29 16:50:03 +0000176 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000177 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000178 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000179 }
180 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000181 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000182 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000183 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000184 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000185
186 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000188 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000190 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000191 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 if (ReplacingStmt)
194 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195
Steve Naroffb619d952008-12-09 12:56:34 +0000196 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000197 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000198
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000200 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000201 ReplacedNodes[Old] = New;
202 return;
203 }
204 if (SilenceRewriteMacroWarning)
205 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000206 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
207 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000208 }
Steve Naroffb619d952008-12-09 12:56:34 +0000209
210 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000211 if (DisableReplaceStmt)
212 return;
213
Nick Lewycky7e749242010-10-31 21:07:24 +0000214 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000215 int Size = Rewrite.getRangeSize(SrcRange);
216 if (Size == -1) {
217 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
218 << Old->getSourceRange();
219 return;
220 }
221 // Get the new text.
222 std::string SStr;
223 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000224 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000225 const std::string &Str = S.str();
226
227 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000228 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000229 ReplacedNodes[Old] = New;
230 return;
231 }
232 if (SilenceRewriteMacroWarning)
233 return;
234 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
235 << Old->getSourceRange();
236 }
237
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000239 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000245 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattneraadaf782008-01-31 19:51:04 +0000248 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000250 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000251 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000252 SilenceRewriteMacroWarning)
253 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattneraadaf782008-01-31 19:51:04 +0000255 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
256 }
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattnerf04da132007-10-24 17:06:59 +0000258 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000259 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000260 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000261 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
262 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
263 const std::string &typedefString);
264
Steve Naroffa0876e82008-12-02 17:36:43 +0000265 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
266 ObjCImplementationDecl *IMD,
267 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000269 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000270 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
271 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000272 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
273 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000274 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000275 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
277 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
278 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
279 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000280 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000281 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000282 void RewriteBlockPointerType(std::string& Str, QualType Type);
283 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000284 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000286 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000287 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000288 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000289 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000290 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000291 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000292 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Chris Lattnerf04da132007-10-24 17:06:59 +0000294 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000295 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Steve Naroff8599e7a2008-12-08 16:43:47 +0000297 Stmt *CurrentBody;
298 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Chris Lattnere64b7772007-10-24 16:57:36 +0000300 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000301 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
302 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
303 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000304 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000305 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000306 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000307 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000308 void WarnAboutReturnGotoStmts(Stmt *S);
309 void HasReturnStmts(Stmt *S, bool &hasReturns);
310 void RewriteTryReturnStmts(Stmt *S);
311 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000312 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000313 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000314 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000315 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
316 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000317 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000318 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000319 Expr **args, unsigned nargs,
320 SourceLocation StartLoc=SourceLocation(),
321 SourceLocation EndLoc=SourceLocation());
322 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
323 SourceLocation StartLoc=SourceLocation(),
324 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000325 Stmt *RewriteBreakStmt(BreakStmt *S);
326 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000327 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000328
Steve Naroff09b266e2007-10-30 23:14:51 +0000329 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000330 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000331 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000332 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000333 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000334 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000335 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000336 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000337 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000338 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Chris Lattnerf04da132007-10-24 17:06:59 +0000340 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000341 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000342 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000344 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000345 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Douglas Gregor653f1b12009-04-23 01:02:12 +0000347 template<typename MethodIterator>
348 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
349 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000350 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 StringRef prefix,
352 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000353 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Steve Naroff621edce2009-04-29 16:37:50 +0000355 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000356 StringRef prefix,
357 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000358 std::string &Result);
359 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000360 StringRef prefix,
361 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000362 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000363 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000364 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000365 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000366 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000367 void RewriteImplementations();
368 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Steve Naroff54055232008-10-27 17:20:55 +0000370 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000371 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000372 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Steve Naroff54055232008-10-27 17:20:55 +0000374 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
375 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000376
377 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000378 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000379 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000380 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000381 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000382 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000383 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
385 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000387 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000389 std::string SynthesizeBlockImpl(BlockExpr *CE,
390 std::string Tag, std::string Desc);
391 std::string SynthesizeBlockDescriptor(std::string DescTag,
392 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000394 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000395 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000396 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000397 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000398 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000401 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000402 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000403 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000404 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 // We avoid calling Type::isBlockPointerType(), since it operates on the
407 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000408 bool isTopLevelBlockPointerType(QualType T) {
409 return isa<BlockPointerType>(T);
410 }
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000412 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
413 /// to a function pointer type and upon success, returns true; false
414 /// otherwise.
415 bool convertBlockPointerToFunctionPointer(QualType &T) {
416 if (isTopLevelBlockPointerType(T)) {
417 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
418 T = Context->getPointerType(BPT->getPointeeType());
419 return true;
420 }
421 return false;
422 }
423
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000424 void convertToUnqualifiedObjCType(QualType &T) {
425 if (T->isObjCQualifiedIdType())
426 T = Context->getObjCIdType();
427 else if (T->isObjCQualifiedClassType())
428 T = Context->getObjCClassType();
429 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000430 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
431 if (const ObjCObjectPointerType * OBJPT =
432 T->getAsObjCInterfacePointerType()) {
433 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
434 T = QualType(IFaceT, 0);
435 T = Context->getPointerType(T);
436 }
437 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000438 }
439
Steve Naroff54055232008-10-27 17:20:55 +0000440 // FIXME: This predicate seems like it would be useful to add to ASTContext.
441 bool isObjCType(QualType T) {
442 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
443 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Steve Naroff54055232008-10-27 17:20:55 +0000445 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Steve Naroff54055232008-10-27 17:20:55 +0000447 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
448 OCT == Context->getCanonicalType(Context->getObjCClassType()))
449 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Ted Kremenek6217b802009-07-29 21:53:49 +0000451 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000453 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000454 return true;
455 }
456 return false;
457 }
458 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000459 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000460 void GetExtentOfArgList(const char *Name, const char *&LParen,
461 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000462 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner5f9e2722011-07-23 10:55:15 +0000464 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000465 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000466 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Steve Naroff621edce2009-04-29 16:37:50 +0000468 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000469 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000470 if (From[i] == '"')
471 To += "\\\"";
472 else
473 To += From[i];
474 }
475 }
John McCalle23cf432010-12-14 08:05:40 +0000476
477 QualType getSimpleFunctionType(QualType result,
478 const QualType *args,
479 unsigned numArgs,
480 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000481 if (result == Context->getObjCInstanceType())
482 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000483 FunctionProtoType::ExtProtoInfo fpi;
484 fpi.Variadic = variadic;
485 return Context->getFunctionType(result, args, numArgs, fpi);
486 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000487 };
John McCall9d125032010-01-15 18:39:57 +0000488
489 // Helper function: create a CStyleCastExpr with trivial type source info.
490 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000491 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000492 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000493 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000494 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000495 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000496}
497
Mike Stump1eb44332009-09-09 15:08:12 +0000498void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
499 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000500 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000501 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000502 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000503 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000504 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000505 // All the args are checked/rewritten. Don't call twice!
506 RewriteBlockPointerDecl(D);
507 break;
508 }
509 }
510}
511
512void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000513 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000514 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000515 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000516}
517
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000518static bool IsHeaderFile(const std::string &Filename) {
519 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000521 if (DotPos == std::string::npos) {
522 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000523 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000526 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
527 // C header: .h
528 // C++ header: .hh or .H;
529 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000530}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000531
Chris Lattner5f9e2722011-07-23 10:55:15 +0000532RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000533 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000534 bool silenceMacroWarn)
535 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
536 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000537 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000538 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000539 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000540 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
541 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000542 "rewriter doesn't support user-specified control flow semantics "
543 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000544}
545
Eli Friedmanbce831b2009-05-18 22:29:17 +0000546ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000547 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000548 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000549 const LangOptions &LOpts,
550 bool SilenceRewriteMacroWarning) {
551 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000552}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000553
Steve Naroffb29b4272008-04-14 22:03:09 +0000554void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000555 Context = &context;
556 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000557 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 MsgSendFunctionDecl = 0;
559 MsgSendSuperFunctionDecl = 0;
560 MsgSendStretFunctionDecl = 0;
561 MsgSendSuperStretFunctionDecl = 0;
562 MsgSendFpretFunctionDecl = 0;
563 GetClassFunctionDecl = 0;
564 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000565 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000566 SelGetUidFunctionDecl = 0;
567 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000568 ConstantStringClassReference = 0;
569 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000570 CurMethodDef = 0;
571 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000572 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000573 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000574 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000575 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000576 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000577 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000578 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000579 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000580 PropParentMap = 0;
581 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000582 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000583 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000585 // Get the ID and start/end of the main file.
586 MainFileID = SM->getMainFileID();
587 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
588 MainFileStart = MainBuf->getBufferStart();
589 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner2c78b872009-04-14 23:22:57 +0000591 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000593 // declaring objc_selector outside the parameter list removes a silly
594 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000596 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000598 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000600 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000601 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000602 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
603 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000604 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000605 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
608 Preamble += "typedef struct objc_object Protocol;\n";
609 Preamble += "#define _REWRITER_typedef_Protocol\n";
610 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000611 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
613 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
614 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000615 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000616 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
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_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000619 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000620 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000621 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000622 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000623 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000624 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000625 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000626 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000627 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000628 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
629 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000630 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000631 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
634 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
636 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000637 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000638 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000639 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
640 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
641 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000642 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
643 Preamble += "struct __objcFastEnumerationState {\n\t";
644 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000645 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000646 Preamble += "unsigned long *mutationsPtr;\n\t";
647 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000648 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000649 Preamble += "#define __FASTENUMERATIONSTATE\n";
650 Preamble += "#endif\n";
651 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
652 Preamble += "struct __NSConstantStringImpl {\n";
653 Preamble += " int *isa;\n";
654 Preamble += " int flags;\n";
655 Preamble += " char *str;\n";
656 Preamble += " long length;\n";
657 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000658 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
659 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
660 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000661 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000662 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000663 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
664 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000665 // Blocks preamble.
666 Preamble += "#ifndef BLOCK_IMPL\n";
667 Preamble += "#define BLOCK_IMPL\n";
668 Preamble += "struct __block_impl {\n";
669 Preamble += " void *isa;\n";
670 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000671 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000672 Preamble += " void *FuncPtr;\n";
673 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000674 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000675 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000676 Preamble += "extern \"C\" __declspec(dllexport) "
677 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000678 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
679 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
680 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
681 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000682 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
683 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000684 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
685 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
686 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000687 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000688 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000689 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
690 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000691 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000692 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000693 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000694 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000695 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000696 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000697 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000698 Preamble += "#define __weak\n";
699 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000700 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
701 // as this avoids warning in any 64bit/32bit compilation model.
702 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000703}
704
705
Chris Lattnerf04da132007-10-24 17:06:59 +0000706//===----------------------------------------------------------------------===//
707// Top Level Driver Code
708//===----------------------------------------------------------------------===//
709
Chris Lattner682bf922009-03-29 16:50:03 +0000710void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000711 if (Diags.hasErrorOccurred())
712 return;
713
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000714 // Two cases: either the decl could be in the main file, or it could be in a
715 // #included file. If the former, rewrite it now. If the later, check to see
716 // if we rewrote the #include/#import.
717 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000718 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000719
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000720 // If this is for a builtin, ignore it.
721 if (Loc.isInvalid()) return;
722
Steve Naroffebf2b562007-10-23 23:50:29 +0000723 // Look for built-in declarations that we need to refer during the rewrite.
724 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000725 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000726 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000727 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000728 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000729 ConstantStringClassReference = FVD;
730 return;
731 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000733 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000734 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000735 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000737 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000738 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000739 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000740 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000741 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
742 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000743 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
744 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000745 DI != DIEnd; ) {
746 if (isa<ObjCClassDecl>((*DI))) {
747 SmallVector<Decl *, 8> DG;
748 Decl *D = (*DI);
749 SourceLocation Loc = D->getLocation();
750 while (DI != DIEnd &&
751 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
752 DG.push_back(D);
753 ++DI;
754 D = (*DI);
755 }
756 RewriteForwardClassDecl(DG);
757 continue;
758 }
Chris Lattner682bf922009-03-29 16:50:03 +0000759 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000760 ++DI;
761 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000762 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000763 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000764 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000765 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000766}
767
Chris Lattnerf04da132007-10-24 17:06:59 +0000768//===----------------------------------------------------------------------===//
769// Syntactic (non-AST) Rewriting Code
770//===----------------------------------------------------------------------===//
771
Steve Naroffb29b4272008-04-14 22:03:09 +0000772void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000773 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000774 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000775 const char *MainBufStart = MainBuf.begin();
776 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000777 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000779 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000780 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
781 if (*BufPtr == '#') {
782 if (++BufPtr == MainBufEnd)
783 return;
784 while (*BufPtr == ' ' || *BufPtr == '\t')
785 if (++BufPtr == MainBufEnd)
786 return;
787 if (!strncmp(BufPtr, "import", ImportLen)) {
788 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000789 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000790 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000791 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000792 BufPtr += ImportLen;
793 }
794 }
795 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000796}
797
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000798static std::string getIvarAccessString(ObjCIvarDecl *OID) {
799 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000800 std::string S;
801 S = "((struct ";
802 S += ClassDecl->getIdentifier()->getName();
803 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000804 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000805 return S;
806}
807
Steve Naroffa0876e82008-12-02 17:36:43 +0000808void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
809 ObjCImplementationDecl *IMD,
810 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000811 static bool objcGetPropertyDefined = false;
812 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000813 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000814 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000815 const char *startBuf = SM->getCharacterData(startLoc);
816 assert((*startBuf == '@') && "bogus @synthesize location");
817 const char *semiBuf = strchr(startBuf, ';');
818 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000819 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000820 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000821
822 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
823 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Steve Naroffeb0646c2008-12-02 15:48:25 +0000825 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000826 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000827 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000829 if (!OID)
830 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000831 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000832 if (!PD->getGetterMethodDecl()->isDefined()) {
833 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
834 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
835 ObjCPropertyDecl::OBJC_PR_copy));
836 std::string Getr;
837 if (GenGetProperty && !objcGetPropertyDefined) {
838 objcGetPropertyDefined = true;
839 // FIXME. Is this attribute correct in all cases?
840 Getr = "\nextern \"C\" __declspec(dllimport) "
841 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000842 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000843 RewriteObjCMethodDecl(OID->getContainingInterface(),
844 PD->getGetterMethodDecl(), Getr);
845 Getr += "{ ";
846 // Synthesize an explicit cast to gain access to the ivar.
847 // See objc-act.c:objc_synthesize_new_getter() for details.
848 if (GenGetProperty) {
849 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
850 Getr += "typedef ";
851 const FunctionType *FPRetType = 0;
852 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
853 FPRetType);
854 Getr += " _TYPE";
855 if (FPRetType) {
856 Getr += ")"; // close the precedence "scope" for "*".
857
858 // Now, emit the argument types (if any).
859 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
860 Getr += "(";
861 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
862 if (i) Getr += ", ";
863 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000864 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000865 Getr += ParamStr;
866 }
867 if (FT->isVariadic()) {
868 if (FT->getNumArgs()) Getr += ", ";
869 Getr += "...";
870 }
871 Getr += ")";
872 } else
873 Getr += "()";
874 }
875 Getr += ";\n";
876 Getr += "return (_TYPE)";
877 Getr += "objc_getProperty(self, _cmd, ";
878 SynthesizeIvarOffsetComputation(OID, Getr);
879 Getr += ", 1)";
880 }
881 else
882 Getr += "return " + getIvarAccessString(OID);
883 Getr += "; }";
884 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000885 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000886
887 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000888 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Steve Naroffeb0646c2008-12-02 15:48:25 +0000890 // Generate the 'setter' function.
891 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000892 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
893 ObjCPropertyDecl::OBJC_PR_copy);
894 if (GenSetProperty && !objcSetPropertyDefined) {
895 objcSetPropertyDefined = true;
896 // FIXME. Is this attribute correct in all cases?
897 Setr = "\nextern \"C\" __declspec(dllimport) "
898 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
899 }
900
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000901 RewriteObjCMethodDecl(OID->getContainingInterface(),
902 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000903 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000904 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000905 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000906 if (GenSetProperty) {
907 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000908 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000909 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000910 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000911 Setr += ", ";
912 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
913 Setr += "0, ";
914 else
915 Setr += "1, ";
916 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
917 Setr += "1)";
918 else
919 Setr += "0)";
920 }
921 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000922 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000923 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000924 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000925 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000926 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000927}
Chris Lattner8a12c272007-10-11 18:38:32 +0000928
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000929static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
930 std::string &typedefString) {
931 typedefString += "#ifndef _REWRITER_typedef_";
932 typedefString += ForwardDecl->getNameAsString();
933 typedefString += "\n";
934 typedefString += "#define _REWRITER_typedef_";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += "\n";
937 typedefString += "typedef struct objc_object ";
938 typedefString += ForwardDecl->getNameAsString();
939 typedefString += ";\n#endif\n";
940}
941
942void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
943 const std::string &typedefString) {
944 SourceLocation startLoc = ClassDecl->getLocation();
945 const char *startBuf = SM->getCharacterData(startLoc);
946 const char *semiPtr = strchr(startBuf, ';');
947 // Replace the @class with typedefs corresponding to the classes.
948 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
949}
950
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000951void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000952 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000953 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
954 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
955 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
956 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000957 // Translate to typedef's that forward reference structs with the same name
958 // as the class. As a convenience, we include the original declaration
959 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000960 typedefString += "// @class ";
961 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000962 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000963 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000964 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000965 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000966 DeclGroupRef::iterator I = D.begin();
967 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
968}
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000970void RewriteObjC::RewriteForwardClassDecl(
971 const llvm::SmallVector<Decl*, 8> &D) {
972 std::string typedefString;
973 for (unsigned i = 0; i < D.size(); i++) {
974 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
975 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
976 if (i == 0) {
977 typedefString += "// @class ";
978 typedefString += ForwardDecl->getNameAsString();
979 typedefString += ";\n";
980 }
981 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
982 }
983 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000984}
985
Steve Naroffb29b4272008-04-14 22:03:09 +0000986void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000987 // When method is a synthesized one, such as a getter/setter there is
988 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000989 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000990 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000991 SourceLocation LocStart = Method->getLocStart();
992 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chandler Carruth64211622011-07-25 21:09:52 +0000994 if (SM->getExpansionLineNumber(LocEnd) >
995 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000996 InsertText(LocStart, "#if 0\n");
997 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000998 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +00001000 }
1001}
1002
Mike Stump1eb44332009-09-09 15:08:12 +00001003void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +00001004 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Benjamin Kramerd999b372010-02-14 14:14:16 +00001006 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001007 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001008}
1009
Steve Naroffb29b4272008-04-14 22:03:09 +00001010void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001011 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Steve Naroff423cb562007-10-30 13:30:57 +00001013 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001014 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001016 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1017 E = CatDecl->prop_end(); I != E; ++I)
1018 RewriteProperty(*I);
1019
Mike Stump1eb44332009-09-09 15:08:12 +00001020 for (ObjCCategoryDecl::instmeth_iterator
1021 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001022 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001023 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001024 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001025 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001026 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001027 RewriteMethodDeclaration(*I);
1028
Steve Naroff423cb562007-10-30 13:30:57 +00001029 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001030 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1031 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001032}
1033
Steve Naroffb29b4272008-04-14 22:03:09 +00001034void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001035 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Steve Naroff752d6ef2007-10-30 16:42:30 +00001037 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001038 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001039
1040 for (ObjCProtocolDecl::instmeth_iterator
1041 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001042 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001043 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001044 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001045 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001046 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001047 RewriteMethodDeclaration(*I);
1048
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001049 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1050 E = PDecl->prop_end(); I != E; ++I)
1051 RewriteProperty(*I);
1052
Steve Naroff752d6ef2007-10-30 16:42:30 +00001053 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001054 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001055 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001056
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001057 // Must comment out @optional/@required
1058 const char *startBuf = SM->getCharacterData(LocStart);
1059 const char *endBuf = SM->getCharacterData(LocEnd);
1060 for (const char *p = startBuf; p < endBuf; p++) {
1061 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001062 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001063 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001065 }
1066 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001067 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001068 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001070 }
1071 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001072}
1073
Steve Naroffb29b4272008-04-14 22:03:09 +00001074void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001075 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001076 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001077 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001078 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001079 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001080}
1081
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001082void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1083 const FunctionType *&FPRetType) {
1084 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001085 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001086 else if (T->isFunctionPointerType() ||
1087 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001088 // needs special handling, since pointer-to-functions have special
1089 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001090 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001091 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001092 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001093 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001094 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001095 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001096 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001097 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001098 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001099 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001100 }
1101 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001102 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001103}
1104
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001105void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1106 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001107 std::string &ResultStr) {
1108 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1109 const FunctionType *FPRetType = 0;
1110 ResultStr += "\nstatic ";
1111 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001112 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001114 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001115 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001117 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001118 NameStr += "_I_";
1119 else
1120 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001122 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001123 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001124
1125 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001126 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001127 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001128 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 }
Mike Stump1eb44332009-09-09 15:08:12 +00001130 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001131 {
1132 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 int len = selString.size();
1134 for (int i = 0; i < len; i++)
1135 if (selString[i] == ':')
1136 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001137 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001138 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001139 // Remember this name for metadata emission
1140 MethodInternalNames[OMD] = NameStr;
1141 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001143 // Rewrite arguments
1144 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001147 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001148 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001149 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001150 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001151 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001152 ResultStr += "struct ";
1153 }
1154 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001155 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001156 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 }
1158 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001159 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001160 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001162 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001163 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001164 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001167 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1168 E = OMD->param_end(); PI != E; ++PI) {
1169 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001171 if (PDecl->getType()->isObjCQualifiedIdType()) {
1172 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001173 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001174 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001175 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001176 QualType QT = PDecl->getType();
1177 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1178 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001179 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001180 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001181 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001182 ResultStr += Name;
1183 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001184 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001185 if (OMD->isVariadic())
1186 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001187 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Steve Naroff76e429d2008-07-16 14:40:40 +00001189 if (FPRetType) {
1190 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Steve Naroff76e429d2008-07-16 14:40:40 +00001192 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001193 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001194 ResultStr += "(";
1195 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1196 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001197 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001198 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001199 ResultStr += ParamStr;
1200 }
1201 if (FT->isVariadic()) {
1202 if (FT->getNumArgs()) ResultStr += ", ";
1203 ResultStr += "...";
1204 }
1205 ResultStr += ")";
1206 } else {
1207 ResultStr += "()";
1208 }
1209 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001210}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001211void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001212 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1213 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001215 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001217 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001218 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1219 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001220 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001221 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001222 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001223 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001224 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001225 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001226
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001227 const char *startBuf = SM->getCharacterData(LocStart);
1228 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001229 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001230 }
Mike Stump1eb44332009-09-09 15:08:12 +00001231
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001232 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001233 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1234 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001235 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001236 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001237 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001238 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001239 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001240 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001242 const char *startBuf = SM->getCharacterData(LocStart);
1243 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001244 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001245 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001246 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001247 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001248 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001249 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001250 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001251 }
1252
Benjamin Kramerd999b372010-02-14 14:14:16 +00001253 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001254}
1255
Steve Naroffb29b4272008-04-14 22:03:09 +00001256void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001257 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001258 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001259 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001260 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001261 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001262 ResultStr += "\n";
1263 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001264 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001265 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001266 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001267 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001268 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001269 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001270 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001271 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001272 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001273
1274 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001275 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001276 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001277 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001278 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001279 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001280 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001281 for (ObjCInterfaceDecl::classmeth_iterator
1282 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001283 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001284 RewriteMethodDeclaration(*I);
1285
Steve Naroff2feac5e2007-10-30 03:43:13 +00001286 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001287 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1288 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001289}
1290
John McCall4b9c2d22011-11-06 09:01:30 +00001291Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1292 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCall4b9c2d22011-11-06 09:01:30 +00001294 // We just magically know some things about the structure of this
1295 // expression.
1296 ObjCMessageExpr *OldMsg =
1297 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1298 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001299
John McCall4b9c2d22011-11-06 09:01:30 +00001300 // Because the rewriter doesn't allow us to rewrite rewritten code,
1301 // we need to suppress rewriting the sub-statements.
1302 Expr *Base, *RHS;
1303 {
1304 DisableReplaceStmtScope S(*this);
1305
1306 // Rebuild the base expression if we have one.
1307 Base = 0;
1308 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1309 Base = OldMsg->getInstanceReceiver();
1310 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1311 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1312 }
1313
1314 // Rebuild the RHS.
1315 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1316 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1317 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1318 }
1319
1320 // TODO: avoid this copy.
1321 SmallVector<SourceLocation, 1> SelLocs;
1322 OldMsg->getSelectorLocs(SelLocs);
1323
1324 ObjCMessageExpr *NewMsg;
1325 switch (OldMsg->getReceiverKind()) {
1326 case ObjCMessageExpr::Class:
1327 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1328 OldMsg->getValueKind(),
1329 OldMsg->getLeftLoc(),
1330 OldMsg->getClassReceiverTypeInfo(),
1331 OldMsg->getSelector(),
1332 SelLocs,
1333 OldMsg->getMethodDecl(),
1334 RHS,
1335 OldMsg->getRightLoc());
1336 break;
1337
1338 case ObjCMessageExpr::Instance:
1339 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1340 OldMsg->getValueKind(),
1341 OldMsg->getLeftLoc(),
1342 Base,
1343 OldMsg->getSelector(),
1344 SelLocs,
1345 OldMsg->getMethodDecl(),
1346 RHS,
1347 OldMsg->getRightLoc());
1348 break;
1349
1350 case ObjCMessageExpr::SuperClass:
1351 case ObjCMessageExpr::SuperInstance:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1355 OldMsg->getSuperLoc(),
1356 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1357 OldMsg->getSuperType(),
1358 OldMsg->getSelector(),
1359 SelLocs,
1360 OldMsg->getMethodDecl(),
1361 RHS,
1362 OldMsg->getRightLoc());
1363 break;
1364 }
1365
1366 Stmt *Replacement = SynthMessageExpr(NewMsg);
1367 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1368 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001369}
1370
John McCall4b9c2d22011-11-06 09:01:30 +00001371Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1372 SourceRange OldRange = PseudoOp->getSourceRange();
1373
1374 // We just magically know some things about the structure of this
1375 // expression.
1376 ObjCMessageExpr *OldMsg =
1377 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1378
1379 // Because the rewriter doesn't allow us to rewrite rewritten code,
1380 // we need to suppress rewriting the sub-statements.
1381 Expr *Base = 0;
1382 {
1383 DisableReplaceStmtScope S(*this);
1384
1385 // Rebuild the base expression if we have one.
1386 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1387 Base = OldMsg->getInstanceReceiver();
1388 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1389 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001390 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001391 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001392
John McCall4b9c2d22011-11-06 09:01:30 +00001393 // Intentionally empty.
1394 SmallVector<SourceLocation, 1> SelLocs;
1395 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001396
John McCall4b9c2d22011-11-06 09:01:30 +00001397 ObjCMessageExpr *NewMsg;
1398 switch (OldMsg->getReceiverKind()) {
1399 case ObjCMessageExpr::Class:
1400 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1401 OldMsg->getValueKind(),
1402 OldMsg->getLeftLoc(),
1403 OldMsg->getClassReceiverTypeInfo(),
1404 OldMsg->getSelector(),
1405 SelLocs,
1406 OldMsg->getMethodDecl(),
1407 Args,
1408 OldMsg->getRightLoc());
1409 break;
1410
1411 case ObjCMessageExpr::Instance:
1412 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1413 OldMsg->getValueKind(),
1414 OldMsg->getLeftLoc(),
1415 Base,
1416 OldMsg->getSelector(),
1417 SelLocs,
1418 OldMsg->getMethodDecl(),
1419 Args,
1420 OldMsg->getRightLoc());
1421 break;
1422
1423 case ObjCMessageExpr::SuperClass:
1424 case ObjCMessageExpr::SuperInstance:
1425 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1426 OldMsg->getValueKind(),
1427 OldMsg->getLeftLoc(),
1428 OldMsg->getSuperLoc(),
1429 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1430 OldMsg->getSuperType(),
1431 OldMsg->getSelector(),
1432 SelLocs,
1433 OldMsg->getMethodDecl(),
1434 Args,
1435 OldMsg->getRightLoc());
1436 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001437 }
John McCall4b9c2d22011-11-06 09:01:30 +00001438
1439 Stmt *Replacement = SynthMessageExpr(NewMsg);
1440 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1441 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001442}
1443
John McCall4b9c2d22011-11-06 09:01:30 +00001444Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
1445 SourceRange OldRange = IV->getSourceRange();
1446 Expr *BaseExpr = IV->getBase();
1447
1448 // Rewrite the base, but without actually doing replaces.
1449 {
1450 DisableReplaceStmtScope S(*this);
1451 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
1452 IV->setBase(BaseExpr);
1453 }
1454
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001455 ObjCIvarDecl *D = IV->getDecl();
John McCall4b9c2d22011-11-06 09:01:30 +00001456
1457 Expr *Replacement = IV;
Steve Naroff54055232008-10-27 17:20:55 +00001458 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001459 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001460 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001461 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001462 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001463 // lookup which class implements the instance variable.
1464 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001465 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001466 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001467 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Steve Narofff0757612008-05-08 17:52:16 +00001469 // Synthesize an explicit cast to gain access to the ivar.
1470 std::string RecName = clsDeclared->getIdentifier()->getName();
1471 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001472 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001473 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001474 SourceLocation(), SourceLocation(),
1475 II);
Steve Narofff0757612008-05-08 17:52:16 +00001476 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1477 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001478 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001479 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001480 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001481 // Don't forget the parens to enforce the proper binding.
John McCall4b9c2d22011-11-06 09:01:30 +00001482 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
1483 OldRange.getEnd(),
John McCallf89e55a2010-11-18 06:31:45 +00001484 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001485 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001486 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001487 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001488 IV->getLocation(),
1489 D->getType(),
1490 VK_LValue, OK_Ordinary);
John McCall4b9c2d22011-11-06 09:01:30 +00001491 Replacement = ME;
1492 } else {
1493 IV->setBase(PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +00001494 }
1495 }
Steve Naroff84472a82008-04-18 21:55:08 +00001496 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001497 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001498
Steve Naroff9f525972008-05-06 23:20:07 +00001499 // Explicit ivar refs need to have a cast inserted.
1500 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001501 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001502 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001503 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001504 // lookup which class implements the instance variable.
1505 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001506 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001507 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001508 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Steve Naroff9f525972008-05-06 23:20:07 +00001510 // Synthesize an explicit cast to gain access to the ivar.
1511 std::string RecName = clsDeclared->getIdentifier()->getName();
1512 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001513 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001514 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001515 SourceLocation(), SourceLocation(),
1516 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001517 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1518 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001519 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001520 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001521 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001522 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001523 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001524 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001525 // Cannot delete IV->getBase(), since PE points to it.
1526 // Replace the old base with the cast. This is important when doing
1527 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001528 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001529 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001530 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001531
John McCall4b9c2d22011-11-06 09:01:30 +00001532 ReplaceStmtWithRange(IV, Replacement, OldRange);
1533 return Replacement;
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001534}
1535
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001536/// SynthCountByEnumWithState - To print:
1537/// ((unsigned int (*)
1538/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001539/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001540/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001541/// "countByEnumeratingWithState:objects:count:"),
1542/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001543/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544///
Steve Naroffb29b4272008-04-14 22:03:09 +00001545void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001546 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1547 "id *, unsigned int))(void *)objc_msgSend)";
1548 buf += "\n\t\t";
1549 buf += "((id)l_collection,\n\t\t";
1550 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1551 buf += "\n\t\t";
1552 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001553 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001554}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001555
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001556/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1557/// statement to exit to its outer synthesized loop.
1558///
Steve Naroffb29b4272008-04-14 22:03:09 +00001559Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001560 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1561 return S;
1562 // replace break with goto __break_label
1563 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001565 SourceLocation startLoc = S->getLocStart();
1566 buf = "goto __break_label_";
1567 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001568 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001569
1570 return 0;
1571}
1572
1573/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1574/// statement to continue with its inner synthesized loop.
1575///
Steve Naroffb29b4272008-04-14 22:03:09 +00001576Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001577 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1578 return S;
1579 // replace continue with goto __continue_label
1580 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001582 SourceLocation startLoc = S->getLocStart();
1583 buf = "goto __continue_label_";
1584 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001585 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001587 return 0;
1588}
1589
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001590/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001591/// It rewrites:
1592/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001594/// Into:
1595/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001596/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001597/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001598/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001600/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001601/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001602/// if (limit) {
1603/// unsigned long startMutations = *enumState.mutationsPtr;
1604/// do {
1605/// unsigned long counter = 0;
1606/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001607/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001609/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001610/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001612/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001613/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001614/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001616/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001617/// }
1618/// else
1619/// elem = nil;
1620/// }
1621///
Steve Naroffb29b4272008-04-14 22:03:09 +00001622Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001623 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001624 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001625 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001626 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001627 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001628 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001629
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001631 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001632 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001633 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 std::string buf;
1635 buf = "\n{\n\t";
1636 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1637 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001638 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001639 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001640 if (ElementType->isObjCQualifiedIdType() ||
1641 ElementType->isObjCQualifiedInterfaceType())
1642 // Simply use 'id' for all qualified types.
1643 elementTypeAsString = "id";
1644 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001645 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001646 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001647 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001648 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001649 buf += elementName;
1650 buf += ";\n\t";
1651 }
Chris Lattner06767512008-04-08 05:52:18 +00001652 else {
1653 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001654 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001655 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1656 if (VD->getType()->isObjCQualifiedIdType() ||
1657 VD->getType()->isObjCQualifiedInterfaceType())
1658 // Simply use 'id' for all qualified types.
1659 elementTypeAsString = "id";
1660 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001661 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001662 }
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001664 // struct __objcFastEnumerationState enumState = { 0 };
1665 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001666 // id __rw_items[16];
1667 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001668 // id l_collection = (id)
1669 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001670 // Find start location of 'collection' the hard way!
1671 const char *startCollectionBuf = startBuf;
1672 startCollectionBuf += 3; // skip 'for'
1673 startCollectionBuf = strchr(startCollectionBuf, '(');
1674 startCollectionBuf++; // skip '('
1675 // find 'in' and skip it.
1676 while (*startCollectionBuf != ' ' ||
1677 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1678 (*(startCollectionBuf+3) != ' ' &&
1679 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1680 startCollectionBuf++;
1681 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
1683 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001684 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001685 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001686 SourceLocation rightParenLoc = S->getRParenLoc();
1687 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001688 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001689 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001690
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001691 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001692 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001693 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001694 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001695 // ((unsigned int (*)
1696 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001697 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001698 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001699 // "countByEnumeratingWithState:objects:count:"),
1700 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001701 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001702 buf += "unsigned long limit =\n\t\t";
1703 SynthCountByEnumWithState(buf);
1704 buf += ";\n\t";
1705 /// if (limit) {
1706 /// unsigned long startMutations = *enumState.mutationsPtr;
1707 /// do {
1708 /// unsigned long counter = 0;
1709 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001710 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001711 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001712 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001713 buf += "if (limit) {\n\t";
1714 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1715 buf += "do {\n\t\t";
1716 buf += "unsigned long counter = 0;\n\t\t";
1717 buf += "do {\n\t\t\t";
1718 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1719 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1720 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001721 buf += " = (";
1722 buf += elementTypeAsString;
1723 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001724 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001725 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001727 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001728 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001729 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001730 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001731 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001732 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001733 /// }
1734 /// else
1735 /// elem = nil;
1736 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001737 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001738 buf = ";\n\t";
1739 buf += "__continue_label_";
1740 buf += utostr(ObjCBcLabelNo.back());
1741 buf += ": ;";
1742 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001743 buf += "} while (counter < limit);\n\t";
1744 buf += "} while (limit = ";
1745 SynthCountByEnumWithState(buf);
1746 buf += ");\n\t";
1747 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001748 buf += " = ((";
1749 buf += elementTypeAsString;
1750 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001751 buf += "__break_label_";
1752 buf += utostr(ObjCBcLabelNo.back());
1753 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001754 buf += "}\n\t";
1755 buf += "else\n\t\t";
1756 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001757 buf += " = ((";
1758 buf += elementTypeAsString;
1759 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001760 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001762 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001763 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001764 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001765 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001766 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001767 } else {
1768 /* Need to treat single statements specially. For example:
1769 *
1770 * for (A *a in b) if (stuff()) break;
1771 * for (A *a in b) xxxyy;
1772 *
1773 * The following code simply scans ahead to the semi to find the actual end.
1774 */
1775 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1776 const char *semiBuf = strchr(stmtBuf, ';');
1777 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001778 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001779 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001780 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001781 Stmts.pop_back();
1782 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001783 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001784}
1785
Mike Stump1eb44332009-09-09 15:08:12 +00001786/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001787/// This routine rewrites @synchronized(expr) stmt;
1788/// into:
1789/// objc_sync_enter(expr);
1790/// @try stmt @finally { objc_sync_exit(expr); }
1791///
Steve Naroffb29b4272008-04-14 22:03:09 +00001792Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001793 // Get the start location and compute the semi location.
1794 SourceLocation startLoc = S->getLocStart();
1795 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001796
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001797 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001798
1799 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001800 buf = "objc_sync_enter((id)";
1801 const char *lparenBuf = startBuf;
1802 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001804 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1805 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001806 // been rewritten! (which implies the SourceLocation's are invalid).
1807 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001808 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001809 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001810 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811 buf = ");\n";
1812 // declare a new scope with two variables, _stack and _rethrow.
1813 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1814 buf += "int buf[18/*32-bit i386*/];\n";
1815 buf += "char *pointers[4];} _stack;\n";
1816 buf += "id volatile _rethrow = 0;\n";
1817 buf += "objc_exception_try_enter(&_stack);\n";
1818 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001819 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001820 startLoc = S->getSynchBody()->getLocEnd();
1821 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Steve Naroffc7089f12008-08-19 13:04:19 +00001823 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001824 SourceLocation lastCurlyLoc = startLoc;
1825 buf = "}\nelse {\n";
1826 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001827 buf += "}\n";
1828 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001829 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001830
1831 std::string syncBuf;
1832 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001833
1834 Expr *syncExpr = S->getSynchExpr();
1835 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1836 ? CK_BitCast :
1837 syncExpr->getType()->isBlockPointerType()
1838 ? CK_BlockPointerToObjCPointerCast
1839 : CK_CPointerToObjCPointerCast;
1840 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1841 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001842 std::string syncExprBufS;
1843 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001844 syncExpr->printPretty(syncExprBuf, *Context, 0,
1845 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001846 syncBuf += syncExprBuf.str();
1847 syncBuf += ");";
1848
1849 buf += syncBuf;
1850 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001851 buf += "}\n";
1852 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001855
1856 bool hasReturns = false;
1857 HasReturnStmts(S->getSynchBody(), hasReturns);
1858 if (hasReturns)
1859 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1860
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001861 return 0;
1862}
1863
Steve Naroffb85e77a2009-12-05 21:43:12 +00001864void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1865{
Steve Naroff8c565152008-12-05 17:03:39 +00001866 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001867 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001868 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001869 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001870
Steve Naroffb85e77a2009-12-05 21:43:12 +00001871 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001873 TryFinallyContainsReturnDiag);
1874 }
1875 return;
1876}
1877
Steve Naroffb85e77a2009-12-05 21:43:12 +00001878void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1879{
1880 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001881 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001882 if (*CI)
1883 HasReturnStmts(*CI, hasReturns);
1884
1885 if (isa<ReturnStmt>(S))
1886 hasReturns = true;
1887 return;
1888}
1889
1890void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1891 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001892 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001893 if (*CI) {
1894 RewriteTryReturnStmts(*CI);
1895 }
1896 if (isa<ReturnStmt>(S)) {
1897 SourceLocation startLoc = S->getLocStart();
1898 const char *startBuf = SM->getCharacterData(startLoc);
1899
1900 const char *semiBuf = strchr(startBuf, ';');
1901 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001902 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001903
1904 std::string buf;
1905 buf = "{ objc_exception_try_exit(&_stack); return";
1906
Benjamin Kramerd999b372010-02-14 14:14:16 +00001907 ReplaceText(startLoc, 6, buf);
1908 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001909 }
1910 return;
1911}
1912
1913void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1914 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001915 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001916 if (*CI) {
1917 RewriteSyncReturnStmts(*CI, syncExitBuf);
1918 }
1919 if (isa<ReturnStmt>(S)) {
1920 SourceLocation startLoc = S->getLocStart();
1921 const char *startBuf = SM->getCharacterData(startLoc);
1922
1923 const char *semiBuf = strchr(startBuf, ';');
1924 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001925 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001926
1927 std::string buf;
1928 buf = "{ objc_exception_try_exit(&_stack);";
1929 buf += syncExitBuf;
1930 buf += " return";
1931
Benjamin Kramerd999b372010-02-14 14:14:16 +00001932 ReplaceText(startLoc, 6, buf);
1933 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001934 }
1935 return;
1936}
1937
Steve Naroffb29b4272008-04-14 22:03:09 +00001938Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001939 // Get the start location and compute the semi location.
1940 SourceLocation startLoc = S->getLocStart();
1941 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Steve Naroff75730982007-11-07 04:08:17 +00001943 assert((*startBuf == '@') && "bogus @try location");
1944
1945 std::string buf;
1946 // declare a new scope with two variables, _stack and _rethrow.
1947 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1948 buf += "int buf[18/*32-bit i386*/];\n";
1949 buf += "char *pointers[4];} _stack;\n";
1950 buf += "id volatile _rethrow = 0;\n";
1951 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001952 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001953
Benjamin Kramerd999b372010-02-14 14:14:16 +00001954 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff75730982007-11-07 04:08:17 +00001956 startLoc = S->getTryBody()->getLocEnd();
1957 startBuf = SM->getCharacterData(startLoc);
1958
1959 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Steve Naroff75730982007-11-07 04:08:17 +00001961 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001962 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001963 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001964 buf = " /* @catch begin */ else {\n";
1965 buf += " id _caught = objc_exception_extract(&_stack);\n";
1966 buf += " objc_exception_try_enter (&_stack);\n";
1967 buf += " if (_setjmp(_stack.buf))\n";
1968 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1969 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Benjamin Kramerd999b372010-02-14 14:14:16 +00001971 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001972 } else { /* no catch list */
1973 buf = "}\nelse {\n";
1974 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1975 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001976 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001977 }
Steve Naroff75730982007-11-07 04:08:17 +00001978 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001979 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1980 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001981 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001982
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001983 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001984 buf = "if ("; // we are generating code for the first catch clause
1985 else
1986 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001987 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001988 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Steve Naroff75730982007-11-07 04:08:17 +00001990 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Steve Naroff75730982007-11-07 04:08:17 +00001992 const char *lParenLoc = strchr(startBuf, '(');
1993
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001994 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001995 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001996 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001997 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1998 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001999 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002000 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002001 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Steve Naroffe12e6922008-02-01 20:02:07 +00002003 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002004 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002005 } else if (catchDecl) {
2006 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002007 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002008 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002009 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002010 } else if (const ObjCObjectPointerType *Ptr =
2011 t->getAs<ObjCObjectPointerType>()) {
2012 // Should be a pointer to a class.
2013 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2014 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002015 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002016 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002017 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002018 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002019 }
2020 }
2021 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002022 lastCatchBody = Catch->getCatchBody();
2023 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002024 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2025 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2026 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2027 assert((*rParenBuf == ')') && "bogus @catch paren location");
2028 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Mike Stump1eb44332009-09-09 15:08:12 +00002030 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002031 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002032 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002033 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002034 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002035 }
Steve Naroff75730982007-11-07 04:08:17 +00002036 }
2037 // Complete the catch list...
2038 if (lastCatchBody) {
2039 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002040 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2041 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Steve Naroff378f47a2008-09-11 15:29:03 +00002043 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002044 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002045 buf = "} /* last catch end */\n";
2046 buf += "else {\n";
2047 buf += " _rethrow = _caught;\n";
2048 buf += " objc_exception_try_exit(&_stack);\n";
2049 buf += "} } /* @catch end */\n";
2050 if (!S->getFinallyStmt())
2051 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002052 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroff75730982007-11-07 04:08:17 +00002054 // Set lastCurlyLoc
2055 lastCurlyLoc = lastCatchBody->getLocEnd();
2056 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002057 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002058 startLoc = finalStmt->getLocStart();
2059 startBuf = SM->getCharacterData(startLoc);
2060 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Benjamin Kramerd999b372010-02-14 14:14:16 +00002062 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Steve Naroff75730982007-11-07 04:08:17 +00002064 Stmt *body = finalStmt->getFinallyBody();
2065 SourceLocation startLoc = body->getLocStart();
2066 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002067 assert(*SM->getCharacterData(startLoc) == '{' &&
2068 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002069 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002070 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002072 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002073 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002074 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002075 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Steve Naroff75730982007-11-07 04:08:17 +00002077 // Set lastCurlyLoc
2078 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Steve Naroff8c565152008-12-05 17:03:39 +00002080 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002081 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002082 } else { /* no finally clause - make sure we synthesize an implicit one */
2083 buf = "{ /* implicit finally clause */\n";
2084 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2085 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2086 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002087 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002088
2089 // Now check for any return/continue/go statements within the @try.
2090 // The implicit finally clause won't called if the @try contains any
2091 // jump statements.
2092 bool hasReturns = false;
2093 HasReturnStmts(S->getTryBody(), hasReturns);
2094 if (hasReturns)
2095 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002096 }
2097 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002098 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002099 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002100 return 0;
2101}
2102
Mike Stump1eb44332009-09-09 15:08:12 +00002103// This can't be done with ReplaceStmt(S, ThrowExpr), since
2104// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002105// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002106Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002107 // Get the start location and compute the semi location.
2108 SourceLocation startLoc = S->getLocStart();
2109 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Steve Naroff2bd03922007-11-07 15:32:26 +00002111 assert((*startBuf == '@') && "bogus @throw location");
2112
2113 std::string buf;
2114 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002115 if (S->getThrowExpr())
2116 buf = "objc_exception_throw(";
2117 else // add an implicit argument
2118 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002120 // handle "@ throw" correctly.
2121 const char *wBuf = strchr(startBuf, 'w');
2122 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002123 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Steve Naroff2bd03922007-11-07 15:32:26 +00002125 const char *semiBuf = strchr(startBuf, ';');
2126 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002127 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002128 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002129 return 0;
2130}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002131
Steve Naroffb29b4272008-04-14 22:03:09 +00002132Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002133 // Create a new string expression.
2134 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002135 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002136 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002137 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002138 StringLiteral::Ascii, false,
2139 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002140 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Chris Lattner07506182007-11-30 22:53:43 +00002142 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002143 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002144 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002145}
2146
Steve Naroffb29b4272008-04-14 22:03:09 +00002147Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002148 if (!SelGetUidFunctionDecl)
2149 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002150 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2151 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002152 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002153 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002154 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002155 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002156 StringLiteral::Ascii, false,
2157 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002158 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2159 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002160 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002161 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002162 return SelExp;
2163}
2164
Steve Naroffb29b4272008-04-14 22:03:09 +00002165CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002166 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2167 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002168 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002169 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Steve Naroffebf2b562007-10-23 23:50:29 +00002171 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002172 DeclRefExpr *DRE =
2173 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroffebf2b562007-10-23 23:50:29 +00002175 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002176 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002177 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002178 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002179 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002180
John McCall183700f2009-09-21 23:43:11 +00002181 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002183 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002184 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002185 FT->getCallResultType(*Context),
2186 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002187 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002188}
2189
Steve Naroffd5255f52007-11-01 13:24:47 +00002190static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2191 const char *&startRef, const char *&endRef) {
2192 while (startBuf < endBuf) {
2193 if (*startBuf == '<')
2194 startRef = startBuf; // mark the start.
2195 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002196 if (startRef && *startRef == '<') {
2197 endRef = startBuf; // mark the end.
2198 return true;
2199 }
2200 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002201 }
2202 startBuf++;
2203 }
2204 return false;
2205}
2206
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207static void scanToNextArgument(const char *&argRef) {
2208 int angle = 0;
2209 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2210 if (*argRef == '<')
2211 angle++;
2212 else if (*argRef == '>')
2213 angle--;
2214 argRef++;
2215 }
2216 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2217}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002218
Steve Naroffb29b4272008-04-14 22:03:09 +00002219bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002220 if (T->isObjCQualifiedIdType())
2221 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002222 if (const PointerType *PT = T->getAs<PointerType>()) {
2223 if (PT->getPointeeType()->isObjCQualifiedIdType())
2224 return true;
2225 }
2226 if (T->isObjCObjectPointerType()) {
2227 T = T->getPointeeType();
2228 return T->isObjCQualifiedInterfaceType();
2229 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002230 if (T->isArrayType()) {
2231 QualType ElemTy = Context->getBaseElementType(T);
2232 return needToScanForQualifiers(ElemTy);
2233 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002234 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002235}
2236
Steve Naroff4f95b752008-07-29 18:15:38 +00002237void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2238 QualType Type = E->getType();
2239 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002240 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Steve Naroffcda658e2008-11-19 21:15:47 +00002242 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2243 Loc = ECE->getLParenLoc();
2244 EndLoc = ECE->getRParenLoc();
2245 } else {
2246 Loc = E->getLocStart();
2247 EndLoc = E->getLocEnd();
2248 }
2249 // This will defend against trying to rewrite synthesized expressions.
2250 if (Loc.isInvalid() || EndLoc.isInvalid())
2251 return;
2252
Steve Naroff4f95b752008-07-29 18:15:38 +00002253 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002254 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002255 const char *startRef = 0, *endRef = 0;
2256 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2257 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002258 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2259 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002260 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002261 InsertText(LessLoc, "/*");
2262 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002263 }
2264 }
2265}
2266
Steve Naroffb29b4272008-04-14 22:03:09 +00002267void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002268 SourceLocation Loc;
2269 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002270 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002271 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2272 Loc = VD->getLocation();
2273 Type = VD->getType();
2274 }
2275 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2276 Loc = FD->getLocation();
2277 // Check for ObjC 'id' and class types that have been adorned with protocol
2278 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002279 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002280 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002281 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002282 if (!proto)
2283 return;
2284 Type = proto->getResultType();
2285 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002286 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2287 Loc = FD->getLocation();
2288 Type = FD->getType();
2289 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002290 else
2291 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002293 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002294 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Steve Naroffd5255f52007-11-01 13:24:47 +00002296 const char *endBuf = SM->getCharacterData(Loc);
2297 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002298 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002299 startBuf--; // scan backward (from the decl location) for return type.
2300 const char *startRef = 0, *endRef = 0;
2301 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2302 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002303 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2304 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002305 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002306 InsertText(LessLoc, "/*");
2307 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002308 }
2309 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002310 if (!proto)
2311 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002312 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 const char *startBuf = SM->getCharacterData(Loc);
2314 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002315 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2316 if (needToScanForQualifiers(proto->getArgType(i))) {
2317 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Steve Naroffd5255f52007-11-01 13:24:47 +00002319 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002320 // scan forward (from the decl location) for argument types.
2321 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002322 const char *startRef = 0, *endRef = 0;
2323 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2324 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002325 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002326 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002327 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002328 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002329 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002330 InsertText(LessLoc, "/*");
2331 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002332 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002333 startBuf = ++endBuf;
2334 }
2335 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002336 // If the function name is derived from a macro expansion, then the
2337 // argument buffer will not follow the name. Need to speak with Chris.
2338 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002339 startBuf++; // scan forward (from the decl location) for argument types.
2340 startBuf++;
2341 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002342 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002343}
2344
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002345void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2346 QualType QT = ND->getType();
2347 const Type* TypePtr = QT->getAs<Type>();
2348 if (!isa<TypeOfExprType>(TypePtr))
2349 return;
2350 while (isa<TypeOfExprType>(TypePtr)) {
2351 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2352 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2353 TypePtr = QT->getAs<Type>();
2354 }
2355 // FIXME. This will not work for multiple declarators; as in:
2356 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002357 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002358 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2359 const char *startBuf = SM->getCharacterData(DeclLoc);
2360 if (ND->getInit()) {
2361 std::string Name(ND->getNameAsString());
2362 TypeAsString += " " + Name + " = ";
2363 Expr *E = ND->getInit();
2364 SourceLocation startLoc;
2365 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2366 startLoc = ECE->getLParenLoc();
2367 else
2368 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002369 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002370 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002371 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002372 }
2373 else {
2374 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002375 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002376 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002377 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002378 }
2379}
2380
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002381// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002382void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002383 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002384 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002385 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002386 QualType getFuncType =
2387 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002388 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002389 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002390 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002391 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002392 SC_Extern,
2393 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002394}
2395
Steve Naroffb29b4272008-04-14 22:03:09 +00002396void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002397 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002398 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002399 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002400 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002401 return;
2402 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002404}
2405
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002406void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002407 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002408 const char *argPtr = TypeString.c_str();
2409 if (!strchr(argPtr, '^')) {
2410 Str += TypeString;
2411 return;
2412 }
2413 while (*argPtr) {
2414 Str += (*argPtr == '^' ? '*' : *argPtr);
2415 argPtr++;
2416 }
2417}
2418
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002419// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002420void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2421 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002422 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002423 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002424 const char *argPtr = TypeString.c_str();
2425 int paren = 0;
2426 while (*argPtr) {
2427 switch (*argPtr) {
2428 case '(':
2429 Str += *argPtr;
2430 paren++;
2431 break;
2432 case ')':
2433 Str += *argPtr;
2434 paren--;
2435 break;
2436 case '^':
2437 Str += '*';
2438 if (paren == 1)
2439 Str += VD->getNameAsString();
2440 break;
2441 default:
2442 Str += *argPtr;
2443 break;
2444 }
2445 argPtr++;
2446 }
2447}
2448
2449
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002450void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2451 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2452 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2453 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2454 if (!proto)
2455 return;
2456 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002457 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002458 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002459 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002460 FdStr += "(";
2461 unsigned numArgs = proto->getNumArgs();
2462 for (unsigned i = 0; i < numArgs; i++) {
2463 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002464 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002465 if (i+1 < numArgs)
2466 FdStr += ", ";
2467 }
2468 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002469 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002470 CurFunctionDeclToDeclareForBlock = 0;
2471}
2472
Steve Naroffc0a123c2008-03-11 17:37:02 +00002473// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002474void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002475 if (SuperContructorFunctionDecl)
2476 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002477 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002479 QualType argT = Context->getObjCIdType();
2480 assert(!argT.isNull() && "Can't find 'id' type");
2481 ArgTys.push_back(argT);
2482 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2484 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002486 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002487 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002488 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002489 SC_Extern,
2490 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002491}
2492
Steve Naroff09b266e2007-10-30 23:14:51 +00002493// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002494void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002496 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002497 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002498 assert(!argT.isNull() && "Can't find 'id' type");
2499 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002500 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002501 assert(!argT.isNull() && "Can't find 'SEL' type");
2502 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002503 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2504 &ArgTys[0], ArgTys.size(),
2505 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002506 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002507 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002508 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002509 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002512}
2513
Steve Naroff874e2322007-11-15 10:28:18 +00002514// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002515void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002516 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002517 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002518 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002519 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002520 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002521 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2522 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2523 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002525 assert(!argT.isNull() && "Can't find 'SEL' type");
2526 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2528 &ArgTys[0], ArgTys.size(),
2529 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002530 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002531 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002532 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002533 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002534 SC_Extern,
2535 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002536}
2537
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002538// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002539void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002540 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002542 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002543 assert(!argT.isNull() && "Can't find 'id' type");
2544 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002545 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002546 assert(!argT.isNull() && "Can't find 'SEL' type");
2547 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002548 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002549 &ArgTys[0], ArgTys.size(),
2550 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002551 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002552 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002553 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002554 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002555 SC_Extern,
2556 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002557}
2558
Mike Stump1eb44332009-09-09 15:08:12 +00002559// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002560// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002561void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002562 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002563 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002564 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002565 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002566 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002567 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002568 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2569 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2570 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002571 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002572 assert(!argT.isNull() && "Can't find 'SEL' type");
2573 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002574 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002575 &ArgTys[0], ArgTys.size(),
2576 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002577 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002578 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002579 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002580 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002581 SC_Extern,
2582 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002583}
2584
Steve Naroff1284db82008-05-08 22:02:18 +00002585// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002586void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002587 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002588 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002589 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002590 assert(!argT.isNull() && "Can't find 'id' type");
2591 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002593 assert(!argT.isNull() && "Can't find 'SEL' type");
2594 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002595 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2596 &ArgTys[0], ArgTys.size(),
2597 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002598 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002599 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002600 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002601 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002602 SC_Extern,
2603 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002604}
2605
Steve Naroff09b266e2007-10-30 23:14:51 +00002606// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002607void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002608 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002609 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002610 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002611 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2612 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002613 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002614 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002615 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002616 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002617 SC_Extern,
2618 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002619}
2620
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002621// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2622void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2623 IdentifierInfo *getSuperClassIdent =
2624 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002625 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002626 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002627 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2628 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002629 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002630 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002631 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002632 getSuperClassIdent,
2633 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002634 SC_Extern,
2635 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002636 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002637}
2638
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002639// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002640void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002641 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002642 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002643 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002644 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2645 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002646 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002647 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002648 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002649 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002650 SC_Extern,
2651 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002652}
2653
Steve Naroffb29b4272008-04-14 22:03:09 +00002654Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002655 QualType strType = getConstantStringStructType();
2656
2657 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002658
2659 std::string tmpName = InFileName;
2660 unsigned i;
2661 for (i=0; i < tmpName.length(); i++) {
2662 char c = tmpName.at(i);
2663 // replace any non alphanumeric characters with '_'.
2664 if (!isalpha(c) && (c < '0' || c > '9'))
2665 tmpName[i] = '_';
2666 }
2667 S += tmpName;
2668 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002669 S += utostr(NumObjCStringLiterals++);
2670
Steve Naroffba92b2e2008-03-27 22:29:16 +00002671 Preamble += "static __NSConstantStringImpl " + S;
2672 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2673 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002674 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002675 std::string prettyBufS;
2676 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002677 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2678 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002679 Preamble += prettyBuf.str();
2680 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002681 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002682
2683 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002684 SourceLocation(), &Context->Idents.get(S),
2685 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002686 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2687 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002688 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002689 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002690 VK_RValue, OK_Ordinary,
2691 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002692 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002693 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002694 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002695 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002696 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002697 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002698}
2699
Steve Naroff874e2322007-11-15 10:28:18 +00002700// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002701QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002702 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002703 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002704 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002705 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002706 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Steve Naroff874e2322007-11-15 10:28:18 +00002708 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002709 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002710 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002711 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002712
Steve Naroff874e2322007-11-15 10:28:18 +00002713 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002714 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002715 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002716 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002717 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002718 FieldTypes[i], 0,
2719 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002720 /*Mutable=*/false,
2721 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002722 }
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Douglas Gregor838db382010-02-11 01:19:42 +00002724 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002725 }
2726 return Context->getTagDeclType(SuperStructDecl);
2727}
2728
Steve Naroffb29b4272008-04-14 22:03:09 +00002729QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002730 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002731 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002732 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002733 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002734 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002736 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002737 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002738 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002739 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002740 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002741 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002742 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002743 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002744
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002745 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002746 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002747 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2748 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002749 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002750 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002751 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002752 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002753 /*Mutable=*/true,
2754 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002755 }
2756
Douglas Gregor838db382010-02-11 01:19:42 +00002757 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002758 }
2759 return Context->getTagDeclType(ConstantStringDecl);
2760}
2761
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002762Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2763 SourceLocation StartLoc,
2764 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002765 if (!SelGetUidFunctionDecl)
2766 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002767 if (!MsgSendFunctionDecl)
2768 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002769 if (!MsgSendSuperFunctionDecl)
2770 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002771 if (!MsgSendStretFunctionDecl)
2772 SynthMsgSendStretFunctionDecl();
2773 if (!MsgSendSuperStretFunctionDecl)
2774 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002775 if (!MsgSendFpretFunctionDecl)
2776 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002777 if (!GetClassFunctionDecl)
2778 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002779 if (!GetSuperClassFunctionDecl)
2780 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002781 if (!GetMetaClassFunctionDecl)
2782 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Steve Naroff874e2322007-11-15 10:28:18 +00002784 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002785 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2786 // May need to use objc_msgSend_stret() as well.
2787 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002788 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2789 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002790 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002791 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002792 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002793 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002794 }
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Steve Naroff934f2762007-10-24 22:48:43 +00002796 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002797 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 switch (Exp->getReceiverKind()) {
2799 case ObjCMessageExpr::SuperClass: {
2800 MsgSendFlavor = MsgSendSuperFunctionDecl;
2801 if (MsgSendStretFlavor)
2802 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2803 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002804
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002806
Chris Lattner5f9e2722011-07-23 10:55:15 +00002807 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002808
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809 // set the receiver to self, the first argument to all methods.
2810 InitExprs.push_back(
2811 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002812 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002813 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002814 Context->getObjCIdType(),
2815 VK_RValue,
2816 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002817 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002820 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 QualType argType = Context->getPointerType(Context->CharTy);
2822 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002823 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002824 StringLiteral::Ascii, false,
2825 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002826 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2827 &ClsExprs[0],
2828 ClsExprs.size(),
2829 StartLoc,
2830 EndLoc);
2831 // (Class)objc_getClass("CurrentClass")
2832 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002834 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 ClsExprs.clear();
2836 ClsExprs.push_back(ArgExpr);
2837 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2838 &ClsExprs[0], ClsExprs.size(),
2839 StartLoc, EndLoc);
2840
2841 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2842 // To turn off a warning, type-cast to 'id'
2843 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2844 NoTypeInfoCStyleCastExpr(Context,
2845 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002846 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 // struct objc_super
2848 QualType superType = getSuperStructType();
2849 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002850
Francois Pichet62ec1f22011-09-17 17:15:52 +00002851 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 SynthSuperContructorFunctionDecl();
2853 // Simulate a contructor call...
2854 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002855 superType, VK_LValue,
2856 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2858 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002859 superType, VK_LValue,
2860 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861 // The code for super is a little tricky to prevent collision with
2862 // the structure definition in the header. The rewriter has it's own
2863 // internal definition (__rw_objc_super) that is uses. This is why
2864 // we need the cast below. For example:
2865 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2866 //
John McCall2de56d12010-08-25 11:45:40 +00002867 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002868 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002869 VK_RValue, OK_Ordinary,
2870 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002871 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2872 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002873 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002874 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002875 // (struct objc_super) { <exprs from above> }
2876 InitListExpr *ILE =
2877 new (Context) InitListExpr(*Context, SourceLocation(),
2878 &InitExprs[0], InitExprs.size(),
2879 SourceLocation());
2880 TypeSourceInfo *superTInfo
2881 = Context->getTrivialTypeSourceInfo(superType);
2882 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002883 superType, VK_LValue,
2884 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002886 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002887 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002888 VK_RValue, OK_Ordinary,
2889 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002890 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002891 MsgExprs.push_back(SuperRep);
2892 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002893 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002894
2895 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002896 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002897 QualType argType = Context->getPointerType(Context->CharTy);
2898 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002899 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002900 IdentifierInfo *clsName = Class->getIdentifier();
2901 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002902 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002903 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002904 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002905 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2906 &ClsExprs[0],
2907 ClsExprs.size(),
2908 StartLoc, EndLoc);
2909 MsgExprs.push_back(Cls);
2910 break;
2911 }
2912
2913 case ObjCMessageExpr::SuperInstance:{
2914 MsgSendFlavor = MsgSendSuperFunctionDecl;
2915 if (MsgSendStretFlavor)
2916 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2917 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2918 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002919 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002920
2921 InitExprs.push_back(
2922 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002923 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002924 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002925 Context->getObjCIdType(),
2926 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002927 ); // set the 'receiver'.
2928
2929 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002930 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 QualType argType = Context->getPointerType(Context->CharTy);
2932 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002933 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002934 StringLiteral::Ascii, false, argType,
2935 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002936 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2937 &ClsExprs[0],
2938 ClsExprs.size(),
2939 StartLoc, EndLoc);
2940 // (Class)objc_getClass("CurrentClass")
2941 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2942 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002943 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002944 ClsExprs.clear();
2945 ClsExprs.push_back(ArgExpr);
2946 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2947 &ClsExprs[0], ClsExprs.size(),
2948 StartLoc, EndLoc);
2949
2950 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2951 // To turn off a warning, type-cast to 'id'
2952 InitExprs.push_back(
2953 // set 'super class', using class_getSuperclass().
2954 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002955 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002956 // struct objc_super
2957 QualType superType = getSuperStructType();
2958 Expr *SuperRep;
2959
Francois Pichet62ec1f22011-09-17 17:15:52 +00002960 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002961 SynthSuperContructorFunctionDecl();
2962 // Simulate a contructor call...
2963 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002964 superType, VK_LValue,
2965 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002966 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2967 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002968 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002969 // The code for super is a little tricky to prevent collision with
2970 // the structure definition in the header. The rewriter has it's own
2971 // internal definition (__rw_objc_super) that is uses. This is why
2972 // we need the cast below. For example:
2973 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2974 //
John McCall2de56d12010-08-25 11:45:40 +00002975 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002976 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002977 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002978 SourceLocation());
2979 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2980 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002981 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002982 } else {
2983 // (struct objc_super) { <exprs from above> }
2984 InitListExpr *ILE =
2985 new (Context) InitListExpr(*Context, SourceLocation(),
2986 &InitExprs[0], InitExprs.size(),
2987 SourceLocation());
2988 TypeSourceInfo *superTInfo
2989 = Context->getTrivialTypeSourceInfo(superType);
2990 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002991 superType, VK_RValue, ILE,
2992 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002993 }
2994 MsgExprs.push_back(SuperRep);
2995 break;
2996 }
2997
2998 case ObjCMessageExpr::Instance: {
2999 // Remove all type-casts because it may contain objc-style types; e.g.
3000 // Foo<Proto> *.
3001 Expr *recExpr = Exp->getInstanceReceiver();
3002 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3003 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003004 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3005 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3006 ? CK_BlockPointerToObjCPointerCast
3007 : CK_CPointerToObjCPointerCast;
3008
Douglas Gregor04badcf2010-04-21 00:45:42 +00003009 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003010 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003011 MsgExprs.push_back(recExpr);
3012 break;
3013 }
3014 }
3015
Steve Naroffbeaf2992007-11-03 11:27:19 +00003016 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003017 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003018 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003019 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003020 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003021 StringLiteral::Ascii, false,
3022 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003023 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003024 &SelExprs[0], SelExprs.size(),
3025 StartLoc,
3026 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003027 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Steve Naroff934f2762007-10-24 22:48:43 +00003029 // Now push any user supplied arguments.
3030 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003031 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003032 // Make all implicit casts explicit...ICE comes in handy:-)
3033 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3034 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003035 QualType type = ICE->getType();
3036 if (needToScanForQualifiers(type))
3037 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003038 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003039 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003040 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003041 CastKind CK;
3042 if (SubExpr->getType()->isIntegralType(*Context) &&
3043 type->isBooleanType()) {
3044 CK = CK_IntegralToBoolean;
3045 } else if (type->isObjCObjectPointerType()) {
3046 if (SubExpr->getType()->isBlockPointerType()) {
3047 CK = CK_BlockPointerToObjCPointerCast;
3048 } else if (SubExpr->getType()->isPointerType()) {
3049 CK = CK_CPointerToObjCPointerCast;
3050 } else {
3051 CK = CK_BitCast;
3052 }
3053 } else {
3054 CK = CK_BitCast;
3055 }
3056
3057 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003058 }
3059 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003060 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003061 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003062 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003063 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003064 CastKind CK;
3065 if (userExpr->getType()->isIntegralType(*Context)) {
3066 CK = CK_IntegralToPointer;
3067 } else if (userExpr->getType()->isBlockPointerType()) {
3068 CK = CK_BlockPointerToObjCPointerCast;
3069 } else if (userExpr->getType()->isPointerType()) {
3070 CK = CK_CPointerToObjCPointerCast;
3071 } else {
3072 CK = CK_BitCast;
3073 }
John McCall9d125032010-01-15 18:39:57 +00003074 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003075 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003076 }
Mike Stump1eb44332009-09-09 15:08:12 +00003077 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003078 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003079 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3080 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003081 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003082 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003083 }
Steve Naroffab972d32007-11-04 22:37:50 +00003084 // Generate the funky cast.
3085 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003086 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003087 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Steve Naroffab972d32007-11-04 22:37:50 +00003089 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003090 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3091 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3092 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003093 ArgTypes.push_back(Context->getObjCIdType());
3094 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003095 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003096 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003097 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3098 E = OMD->param_end(); PI != E; ++PI) {
3099 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003100 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003101 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003102 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003103 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003104 ArgTypes.push_back(t);
3105 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003106 returnType = Exp->getType();
3107 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003108 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003109 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003110 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003111 }
3112 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003113 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Steve Naroffab972d32007-11-04 22:37:50 +00003115 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003116 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003117 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003118
Mike Stump1eb44332009-09-09 15:08:12 +00003119 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003120 // If we don't do this cast, we get the following bizarre warning/note:
3121 // xx.m:13: warning: function called through a non-compatible type
3122 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003123 cast = NoTypeInfoCStyleCastExpr(Context,
3124 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003125 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Steve Naroffab972d32007-11-04 22:37:50 +00003127 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003128 QualType castType =
3129 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3130 // If we don't have a method decl, force a variadic cast.
3131 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003132 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003133 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003134 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003135
3136 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003137 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003138
John McCall183700f2009-09-21 23:43:11 +00003139 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003140 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003141 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003142 FT->getResultType(), VK_RValue,
3143 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003144 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003145 if (MsgSendStretFlavor) {
3146 // We have the method which returns a struct/union. Must also generate
3147 // call to objc_msgSend_stret and hang both varieties on a conditional
3148 // expression which dictate which one to envoke depending on size of
3149 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003150
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003151 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003152 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003153 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003154 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003155 cast = NoTypeInfoCStyleCastExpr(Context,
3156 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003157 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003158 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003159 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3160 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003161 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003162 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003163 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003164
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003165 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003166 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003167
John McCall183700f2009-09-21 23:43:11 +00003168 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003169 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003170 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003171 FT->getResultType(), VK_RValue,
3172 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003174 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003175 UnaryExprOrTypeTraitExpr *sizeofExpr =
3176 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3177 Context->getTrivialTypeSourceInfo(returnType),
3178 Context->getSizeType(), SourceLocation(),
3179 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003180 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3181 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3182 // For X86 it is more complicated and some kind of target specific routine
3183 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003184 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003185 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003186 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3187 llvm::APInt(IntSize, 8),
3188 Context->IntTy,
3189 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003190 BinaryOperator *lessThanExpr =
3191 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3192 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003193 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003194 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003195 new (Context) ConditionalOperator(lessThanExpr,
3196 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003197 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003198 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003199 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3200 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003201 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003202 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003203 return ReplacingStmt;
3204}
3205
Steve Naroffb29b4272008-04-14 22:03:09 +00003206Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003207 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3208 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003209
Steve Naroff934f2762007-10-24 22:48:43 +00003210 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003211 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003212
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003213 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003214 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003215}
3216
Steve Naroff621edce2009-04-29 16:37:50 +00003217// typedef struct objc_object Protocol;
3218QualType RewriteObjC::getProtocolType() {
3219 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003220 TypeSourceInfo *TInfo
3221 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003222 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003223 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003224 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003225 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003226 }
3227 return Context->getTypeDeclType(ProtocolTypeDecl);
3228}
3229
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003230/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003231/// a synthesized/forward data reference (to the protocol's metadata).
3232/// The forward references (and metadata) are generated in
3233/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003234Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003235 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3236 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003237 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003238 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003239 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003240 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3241 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003242 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003243 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003244 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003245 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003246 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003247 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003248 ReplaceStmt(Exp, castExpr);
3249 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003250 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003251 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003252
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003253}
3254
Mike Stump1eb44332009-09-09 15:08:12 +00003255bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003256 const char *endBuf) {
3257 while (startBuf < endBuf) {
3258 if (*startBuf == '#') {
3259 // Skip whitespace.
3260 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3261 ;
3262 if (!strncmp(startBuf, "if", strlen("if")) ||
3263 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3264 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3265 !strncmp(startBuf, "define", strlen("define")) ||
3266 !strncmp(startBuf, "undef", strlen("undef")) ||
3267 !strncmp(startBuf, "else", strlen("else")) ||
3268 !strncmp(startBuf, "elif", strlen("elif")) ||
3269 !strncmp(startBuf, "endif", strlen("endif")) ||
3270 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3271 !strncmp(startBuf, "include", strlen("include")) ||
3272 !strncmp(startBuf, "import", strlen("import")) ||
3273 !strncmp(startBuf, "include_next", strlen("include_next")))
3274 return true;
3275 }
3276 startBuf++;
3277 }
3278 return false;
3279}
3280
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003281/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003282/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003283void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003284 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003285 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003286 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003287 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003288 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003289 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003290 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003291 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003292 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003293 SourceLocation LocStart = CDecl->getLocStart();
3294 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003295
Steve Narofffea763e82007-11-14 19:25:57 +00003296 const char *startBuf = SM->getCharacterData(LocStart);
3297 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003298
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003299 // If no ivars and no root or if its root, directly or indirectly,
3300 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003301 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3302 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003303 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003304 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003305 return;
3306 }
Mike Stump1eb44332009-09-09 15:08:12 +00003307
3308 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003309 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003310 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003311 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003312 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003313 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003314
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003315 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003316 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003317 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003318 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003319 // If the buffer contains preprocessor directives, we do more fine-grained
3320 // rewrites. This is intended to fix code that looks like (which occurs in
3321 // NSURL.h, for example):
3322 //
3323 // #ifdef XYZ
3324 // @interface Foo : NSObject
3325 // #else
3326 // @interface FooBar : NSObject
3327 // #endif
3328 // {
3329 // int i;
3330 // }
3331 // @end
3332 //
3333 // This clause is segregated to avoid breaking the common case.
3334 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003335 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003336 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003337 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003338 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003339
Chris Lattnercafeb352009-02-20 18:18:36 +00003340 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003341 // advance to the end of the referenced protocols.
3342 while (endHeader < cursor && *endHeader != '>') endHeader++;
3343 endHeader++;
3344 }
3345 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003346 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003347 } else {
3348 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003349 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003350 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003351 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003352 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003353 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003354 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003355 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003356 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Steve Narofffea763e82007-11-14 19:25:57 +00003358 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003359 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003360 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003361 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003362 }
3363 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Steve Narofffea763e82007-11-14 19:25:57 +00003365 // Now comment out any visibility specifiers.
3366 while (cursor < endBuf) {
3367 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003368 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003369 // Skip whitespace.
3370 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3371 /*scan*/;
3372
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003373 // FIXME: presence of @public, etc. inside comment results in
3374 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003375 if (!strncmp(cursor, "public", strlen("public")) ||
3376 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003377 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003378 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003379 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003380 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003381 // FIXME: If there are cases where '<' is used in ivar declaration part
3382 // of user code, then scan the ivar list and use needToScanForQualifiers
3383 // for type checking.
3384 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003385 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003386 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003387 cursor = strchr(cursor, '>');
3388 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003389 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003390 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003391 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003392 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003393 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003394 }
Steve Narofffea763e82007-11-14 19:25:57 +00003395 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003396 }
Steve Narofffea763e82007-11-14 19:25:57 +00003397 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003398 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003399 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003400 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003401 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003402 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003403 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003404 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003405 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003406 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003407 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003408 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003409 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003410 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003411}
3412
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003413// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003414/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003415template<typename MethodIterator>
3416void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3417 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003418 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003419 StringRef prefix,
3420 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003421 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003422 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003424 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003425 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003426 SEL _cmd;
3427 char *method_types;
3428 void *_imp;
3429 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003430 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003431 Result += "\nstruct _objc_method {\n";
3432 Result += "\tSEL _cmd;\n";
3433 Result += "\tchar *method_types;\n";
3434 Result += "\tvoid *_imp;\n";
3435 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003437 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003438 }
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003440 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003441
Steve Naroff946a6932008-03-11 00:12:29 +00003442 /* struct {
3443 struct _objc_method_list *next_method;
3444 int method_count;
3445 struct _objc_method method_list[];
3446 }
3447 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003448 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003449 Result += "\nstatic struct {\n";
3450 Result += "\tstruct _objc_method_list *next_method;\n";
3451 Result += "\tint method_count;\n";
3452 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003453 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003454 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003455 Result += prefix;
3456 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3457 Result += "_METHODS_";
3458 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003459 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003460 Result += IsInstanceMethod ? "inst" : "cls";
3461 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003462 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003463
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003464 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003465 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003466 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003467 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003468 Result += "\", \"";
3469 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003470 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003471 Result += MethodInternalNames[*MethodBegin];
3472 Result += "}\n";
3473 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3474 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003475 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003476 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003477 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003478 Result += "\", \"";
3479 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003480 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003481 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003482 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003483 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003484 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003485}
3486
Steve Naroff621edce2009-04-29 16:37:50 +00003487/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003488void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003489RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3490 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003491 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003492
3493 // Output struct protocol_methods holder of method selector and type.
3494 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3495 /* struct protocol_methods {
3496 SEL _cmd;
3497 char *method_types;
3498 }
3499 */
3500 Result += "\nstruct _protocol_methods {\n";
3501 Result += "\tstruct objc_selector *_cmd;\n";
3502 Result += "\tchar *method_types;\n";
3503 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Steve Naroff621edce2009-04-29 16:37:50 +00003505 objc_protocol_methods = true;
3506 }
3507 // Do not synthesize the protocol more than once.
3508 if (ObjCSynthesizedProtocols.count(PDecl))
3509 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003510
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003511 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3512 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3513 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003514 /* struct _objc_protocol_method_list {
3515 int protocol_method_count;
3516 struct protocol_methods protocols[];
3517 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003518 */
Steve Naroff621edce2009-04-29 16:37:50 +00003519 Result += "\nstatic struct {\n";
3520 Result += "\tint protocol_method_count;\n";
3521 Result += "\tstruct _protocol_methods protocol_methods[";
3522 Result += utostr(NumMethods);
3523 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3524 Result += PDecl->getNameAsString();
3525 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3526 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Steve Naroff621edce2009-04-29 16:37:50 +00003528 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003529 for (ObjCProtocolDecl::instmeth_iterator
3530 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003531 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003532 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003533 Result += "\t ,{{(struct objc_selector *)\"";
3534 else
3535 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003536 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003537 std::string MethodTypeString;
3538 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3539 Result += "\", \"";
3540 Result += MethodTypeString;
3541 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003542 }
Steve Naroff621edce2009-04-29 16:37:50 +00003543 Result += "\t }\n};\n";
3544 }
Mike Stump1eb44332009-09-09 15:08:12 +00003545
Steve Naroff621edce2009-04-29 16:37:50 +00003546 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003547 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3548 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003549 if (NumMethods > 0) {
3550 /* struct _objc_protocol_method_list {
3551 int protocol_method_count;
3552 struct protocol_methods protocols[];
3553 }
3554 */
3555 Result += "\nstatic struct {\n";
3556 Result += "\tint protocol_method_count;\n";
3557 Result += "\tstruct _protocol_methods protocol_methods[";
3558 Result += utostr(NumMethods);
3559 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3560 Result += PDecl->getNameAsString();
3561 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3562 "{\n\t";
3563 Result += utostr(NumMethods);
3564 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Steve Naroff621edce2009-04-29 16:37:50 +00003566 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003567 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003568 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003569 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003570 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003571 Result += "\t ,{{(struct objc_selector *)\"";
3572 else
3573 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003574 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003575 std::string MethodTypeString;
3576 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3577 Result += "\", \"";
3578 Result += MethodTypeString;
3579 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003580 }
Steve Naroff621edce2009-04-29 16:37:50 +00003581 Result += "\t }\n};\n";
3582 }
3583
3584 // Output:
3585 /* struct _objc_protocol {
3586 // Objective-C 1.0 extensions
3587 struct _objc_protocol_extension *isa;
3588 char *protocol_name;
3589 struct _objc_protocol **protocol_list;
3590 struct _objc_protocol_method_list *instance_methods;
3591 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003592 };
Steve Naroff621edce2009-04-29 16:37:50 +00003593 */
3594 static bool objc_protocol = false;
3595 if (!objc_protocol) {
3596 Result += "\nstruct _objc_protocol {\n";
3597 Result += "\tstruct _objc_protocol_extension *isa;\n";
3598 Result += "\tchar *protocol_name;\n";
3599 Result += "\tstruct _objc_protocol **protocol_list;\n";
3600 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3601 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003602 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003603
Steve Naroff621edce2009-04-29 16:37:50 +00003604 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003605 }
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Steve Naroff621edce2009-04-29 16:37:50 +00003607 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3608 Result += PDecl->getNameAsString();
3609 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3610 "{\n\t0, \"";
3611 Result += PDecl->getNameAsString();
3612 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003613 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003614 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3615 Result += PDecl->getNameAsString();
3616 Result += ", ";
3617 }
3618 else
3619 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003620 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003621 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3622 Result += PDecl->getNameAsString();
3623 Result += "\n";
3624 }
3625 else
3626 Result += "0\n";
3627 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Steve Naroff621edce2009-04-29 16:37:50 +00003629 // Mark this protocol as having been generated.
3630 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003631 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003632
3633}
3634
3635void RewriteObjC::
3636RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003637 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003638 std::string &Result) {
3639 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Steve Naroff621edce2009-04-29 16:37:50 +00003641 for (unsigned i = 0; i != Protocols.size(); i++)
3642 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3643
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003644 // Output the top lovel protocol meta-data for the class.
3645 /* struct _objc_protocol_list {
3646 struct _objc_protocol_list *next;
3647 int protocol_count;
3648 struct _objc_protocol *class_protocols[];
3649 }
3650 */
3651 Result += "\nstatic struct {\n";
3652 Result += "\tstruct _objc_protocol_list *next;\n";
3653 Result += "\tint protocol_count;\n";
3654 Result += "\tstruct _objc_protocol *class_protocols[";
3655 Result += utostr(Protocols.size());
3656 Result += "];\n} _OBJC_";
3657 Result += prefix;
3658 Result += "_PROTOCOLS_";
3659 Result += ClassName;
3660 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3661 "{\n\t0, ";
3662 Result += utostr(Protocols.size());
3663 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003665 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003666 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003667 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003669 for (unsigned i = 1; i != Protocols.size(); i++) {
3670 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003671 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003672 Result += "\n";
3673 }
3674 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003675}
3676
Steve Naroff621edce2009-04-29 16:37:50 +00003677
Mike Stump1eb44332009-09-09 15:08:12 +00003678/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003679/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003680void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003681 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003682 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003683 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003684 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003685 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003686 CDecl = CDecl->getNextClassCategory())
3687 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3688 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003690 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003691 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003693
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003694 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003695 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003696 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003697
3698 // If any of our property implementations have associated getters or
3699 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003700 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3701 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003702 Prop != PropEnd; ++Prop) {
3703 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3704 continue;
3705 if (!(*Prop)->getPropertyIvarDecl())
3706 continue;
3707 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3708 if (!PD)
3709 continue;
3710 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3711 InstanceMethods.push_back(Getter);
3712 if (PD->isReadOnly())
3713 continue;
3714 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3715 InstanceMethods.push_back(Setter);
3716 }
3717 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003718 true, "CATEGORY_", FullCategoryName.c_str(),
3719 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003721 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003722 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003723 false, "CATEGORY_", FullCategoryName.c_str(),
3724 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003725
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003726 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003727 // Null CDecl is case of a category implementation with no category interface
3728 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003729 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003730 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003731 /* struct _objc_category {
3732 char *category_name;
3733 char *class_name;
3734 struct _objc_method_list *instance_methods;
3735 struct _objc_method_list *class_methods;
3736 struct _objc_protocol_list *protocols;
3737 // Objective-C 1.0 extensions
3738 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003739 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003740 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003741 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003742 */
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003744 static bool objc_category = false;
3745 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003746 Result += "\nstruct _objc_category {\n";
3747 Result += "\tchar *category_name;\n";
3748 Result += "\tchar *class_name;\n";
3749 Result += "\tstruct _objc_method_list *instance_methods;\n";
3750 Result += "\tstruct _objc_method_list *class_methods;\n";
3751 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003752 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003753 Result += "\tstruct _objc_property_list *instance_properties;\n";
3754 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003755 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003756 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003757 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3758 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003759 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003760 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003761 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003762 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003763 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003765 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003766 Result += "\t, (struct _objc_method_list *)"
3767 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3768 Result += FullCategoryName;
3769 Result += "\n";
3770 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003772 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003773 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += "\t, (struct _objc_method_list *)"
3775 "&_OBJC_CATEGORY_CLASS_METHODS_";
3776 Result += FullCategoryName;
3777 Result += "\n";
3778 }
3779 else
3780 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Chris Lattnercafeb352009-02-20 18:18:36 +00003782 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003783 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 Result += FullCategoryName;
3785 Result += "\n";
3786 }
3787 else
3788 Result += "\t, 0\n";
3789 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003790}
3791
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003792/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3793/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003794void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003795 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003796 if (ivar->isBitField()) {
3797 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3798 // place all bitfields at offset 0.
3799 Result += "0";
3800 } else {
3801 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003802 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003803 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003804 Result += "_IMPL";
3805 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003806 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003807 Result += ")";
3808 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003809}
3810
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003811//===----------------------------------------------------------------------===//
3812// Meta Data Emission
3813//===----------------------------------------------------------------------===//
3814
Steve Naroffb29b4272008-04-14 22:03:09 +00003815void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003816 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003817 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003819 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003820 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003821 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003822 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003823 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003824 }
Mike Stump1eb44332009-09-09 15:08:12 +00003825
Chris Lattnerbe6df082007-12-12 07:56:42 +00003826 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003827 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003828 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003829 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003830 if (NumIvars > 0) {
3831 static bool objc_ivar = false;
3832 if (!objc_ivar) {
3833 /* struct _objc_ivar {
3834 char *ivar_name;
3835 char *ivar_type;
3836 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003837 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003838 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003839 Result += "\nstruct _objc_ivar {\n";
3840 Result += "\tchar *ivar_name;\n";
3841 Result += "\tchar *ivar_type;\n";
3842 Result += "\tint ivar_offset;\n";
3843 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003845 objc_ivar = true;
3846 }
3847
Steve Naroff946a6932008-03-11 00:12:29 +00003848 /* struct {
3849 int ivar_count;
3850 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003851 };
Steve Naroff946a6932008-03-11 00:12:29 +00003852 */
Mike Stump1eb44332009-09-09 15:08:12 +00003853 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003854 Result += "\tint ivar_count;\n";
3855 Result += "\tstruct _objc_ivar ivar_list[";
3856 Result += utostr(NumIvars);
3857 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003858 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003859 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003860 "{\n\t";
3861 Result += utostr(NumIvars);
3862 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003864 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003865 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003866 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003867 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003868 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003869 IV != IVEnd; ++IV)
3870 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003871 IVI = IDecl->ivar_begin();
3872 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003873 } else {
3874 IVI = CDecl->ivar_begin();
3875 IVE = CDecl->ivar_end();
3876 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003877 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003878 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003879 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003880 std::string TmpString, StrEncoding;
3881 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3882 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003883 Result += StrEncoding;
3884 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003885 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003886 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003887 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003888 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003889 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003890 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003891 std::string TmpString, StrEncoding;
3892 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3893 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003894 Result += StrEncoding;
3895 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003896 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003897 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003898 }
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003900 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003901 }
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003903 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003904 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003905 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003906
3907 // If any of our property implementations have associated getters or
3908 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003909 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3910 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003911 Prop != PropEnd; ++Prop) {
3912 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3913 continue;
3914 if (!(*Prop)->getPropertyIvarDecl())
3915 continue;
3916 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3917 if (!PD)
3918 continue;
3919 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003920 if (!Getter->isDefined())
3921 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003922 if (PD->isReadOnly())
3923 continue;
3924 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003925 if (!Setter->isDefined())
3926 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003927 }
3928 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003929 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003931 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003932 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003933 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003934
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003935 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003936 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003937 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003939 // Declaration of class/meta-class metadata
3940 /* struct _objc_class {
3941 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003942 const char *super_class_name;
3943 char *name;
3944 long version;
3945 long info;
3946 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003947 struct _objc_ivar_list *ivars;
3948 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003949 struct objc_cache *cache;
3950 struct objc_protocol_list *protocols;
3951 const char *ivar_layout;
3952 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003953 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003954 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003955 static bool objc_class = false;
3956 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003957 Result += "\nstruct _objc_class {\n";
3958 Result += "\tstruct _objc_class *isa;\n";
3959 Result += "\tconst char *super_class_name;\n";
3960 Result += "\tchar *name;\n";
3961 Result += "\tlong version;\n";
3962 Result += "\tlong info;\n";
3963 Result += "\tlong instance_size;\n";
3964 Result += "\tstruct _objc_ivar_list *ivars;\n";
3965 Result += "\tstruct _objc_method_list *methods;\n";
3966 Result += "\tstruct objc_cache *cache;\n";
3967 Result += "\tstruct _objc_protocol_list *protocols;\n";
3968 Result += "\tconst char *ivar_layout;\n";
3969 Result += "\tstruct _objc_class_ext *ext;\n";
3970 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003971 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003972 }
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003974 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003975 ObjCInterfaceDecl *RootClass = 0;
3976 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003977 while (SuperClass) {
3978 RootClass = SuperClass;
3979 SuperClass = SuperClass->getSuperClass();
3980 }
3981 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003982
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003983 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003984 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003985 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003986 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003987 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003988 Result += "\"";
3989
3990 if (SuperClass) {
3991 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003992 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003993 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003994 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003995 Result += "\"";
3996 }
3997 else {
3998 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003999 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004000 Result += "\"";
4001 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004002 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004003 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004005 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004006 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004007 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004008 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004010 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004011 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004012 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004013 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004014 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004015 Result += ",0,0\n";
4016 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004017 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004018 Result += "\t,0,0,0,0\n";
4019 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004020
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004021 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004022 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004023 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004024 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004025 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004026 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004027 if (SuperClass) {
4028 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004029 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004031 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004032 Result += "\"";
4033 }
4034 else {
4035 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004036 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004037 Result += "\"";
4038 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004039 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004040 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004041 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004042 Result += ",0";
4043 else {
4044 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004045 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004046 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004047 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004048 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004049 Result += ")";
4050 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004052 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004053 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004054 Result += "\n\t";
4055 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004056 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004057 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004058 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004059 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004060 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004061 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004062 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004063 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004064 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004065 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004066 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004067 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004068 Result += ", 0,0\n";
4069 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004070 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004071 Result += ",0,0,0\n";
4072 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004073}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004074
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004075/// RewriteImplementations - This routine rewrites all method implementations
4076/// and emits meta-data.
4077
Steve Narofface66252008-11-13 20:07:04 +00004078void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004079 int ClsDefCount = ClassImplementation.size();
4080 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004082 // Rewrite implemented methods
4083 for (int i = 0; i < ClsDefCount; i++)
4084 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004085
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004086 for (int i = 0; i < CatDefCount; i++)
4087 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004088}
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Steve Narofface66252008-11-13 20:07:04 +00004090void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4091 int ClsDefCount = ClassImplementation.size();
4092 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004093
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004094 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004095 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004096 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004098 // For each implemented category, write out all its meta data.
4099 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004100 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004101
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004102 // Write objc_symtab metadata
4103 /*
4104 struct _objc_symtab
4105 {
4106 long sel_ref_cnt;
4107 SEL *refs;
4108 short cls_def_cnt;
4109 short cat_def_cnt;
4110 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004111 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004112 */
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004114 Result += "\nstruct _objc_symtab {\n";
4115 Result += "\tlong sel_ref_cnt;\n";
4116 Result += "\tSEL *refs;\n";
4117 Result += "\tshort cls_def_cnt;\n";
4118 Result += "\tshort cat_def_cnt;\n";
4119 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4120 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004121
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004122 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004123 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004124 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004125 + ", " + utostr(CatDefCount) + "\n";
4126 for (int i = 0; i < ClsDefCount; i++) {
4127 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004128 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004129 Result += "\n";
4130 }
Mike Stump1eb44332009-09-09 15:08:12 +00004131
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004132 for (int i = 0; i < CatDefCount; i++) {
4133 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004134 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004135 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004136 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004137 Result += "\n";
4138 }
Mike Stump1eb44332009-09-09 15:08:12 +00004139
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004140 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004141
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004142 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004143
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004144 /*
4145 struct _objc_module {
4146 long version;
4147 long size;
4148 const char *name;
4149 struct _objc_symtab *symtab;
4150 }
4151 */
Mike Stump1eb44332009-09-09 15:08:12 +00004152
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004153 Result += "\nstruct _objc_module {\n";
4154 Result += "\tlong version;\n";
4155 Result += "\tlong size;\n";
4156 Result += "\tconst char *name;\n";
4157 Result += "\tstruct _objc_symtab *symtab;\n";
4158 Result += "};\n\n";
4159 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004160 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004161 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004162 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004163 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004164
Francois Pichet62ec1f22011-09-17 17:15:52 +00004165 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004166 if (ProtocolExprDecls.size()) {
4167 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4168 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004169 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004170 E = ProtocolExprDecls.end(); I != E; ++I) {
4171 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4172 Result += (*I)->getNameAsString();
4173 Result += " = &_OBJC_PROTOCOL_";
4174 Result += (*I)->getNameAsString();
4175 Result += ";\n";
4176 }
4177 Result += "#pragma data_seg(pop)\n\n";
4178 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004179 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004180 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004181 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4182 Result += "&_OBJC_MODULES;\n";
4183 Result += "#pragma data_seg(pop)\n\n";
4184 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004185}
Chris Lattner311ff022007-10-16 22:36:42 +00004186
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004187void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4188 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004189 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004190 assert(BlockByRefDeclNo.count(VD) &&
4191 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004192 if (def)
4193 ResultStr += "struct ";
4194 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004195 "_" + utostr(BlockByRefDeclNo[VD]) ;
4196}
4197
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004198static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4199 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4200 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4201 return false;
4202}
4203
Steve Naroff54055232008-10-27 17:20:55 +00004204std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004205 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004206 std::string Tag) {
4207 const FunctionType *AFT = CE->getFunctionType();
4208 QualType RT = AFT->getResultType();
4209 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004210 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004211 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004212
Steve Naroff54055232008-10-27 17:20:55 +00004213 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Douglas Gregor72564e72009-02-26 23:50:07 +00004215 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004216 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004217 // block (to reference imported block decl refs).
4218 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004219 } else if (BD->param_empty()) {
4220 S += "(" + StructRef + " *__cself)";
4221 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004222 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004223 assert(FT && "SynthesizeBlockFunc: No function proto");
4224 S += '(';
4225 // first add the implicit argument.
4226 S += StructRef + " *__cself, ";
4227 std::string ParamStr;
4228 for (BlockDecl::param_iterator AI = BD->param_begin(),
4229 E = BD->param_end(); AI != E; ++AI) {
4230 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004231 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004232 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004233 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004234 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004235 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004236 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004237 S += ParamStr;
4238 }
4239 if (FT->isVariadic()) {
4240 if (!BD->param_empty()) S += ", ";
4241 S += "...";
4242 }
4243 S += ')';
4244 }
4245 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004246
Steve Naroff54055232008-10-27 17:20:55 +00004247 // Create local declarations to avoid rewriting all closure decl ref exprs.
4248 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004249 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004250 E = BlockByRefDecls.end(); I != E; ++I) {
4251 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004252 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004253 std::string TypeString;
4254 RewriteByRefString(TypeString, Name, (*I));
4255 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004256 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004257 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004258 }
Steve Naroff54055232008-10-27 17:20:55 +00004259 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004260 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004261 E = BlockByCopyDecls.end(); I != E; ++I) {
4262 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004263 // Handle nested closure invocation. For example:
4264 //
4265 // void (^myImportedClosure)(void);
4266 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004267 //
Steve Naroff54055232008-10-27 17:20:55 +00004268 // void (^anotherClosure)(void);
4269 // anotherClosure = ^(void) {
4270 // myImportedClosure(); // import and invoke the closure
4271 // };
4272 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004273 if (isTopLevelBlockPointerType((*I)->getType())) {
4274 RewriteBlockPointerTypeVariable(S, (*I));
4275 S += " = (";
4276 RewriteBlockPointerType(S, (*I)->getType());
4277 S += ")";
4278 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4279 }
4280 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004281 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004282 QualType QT = (*I)->getType();
4283 if (HasLocalVariableExternalStorage(*I))
4284 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004285 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004286 S += Name + " = __cself->" +
4287 (*I)->getNameAsString() + "; // bound by copy\n";
4288 }
Steve Naroff54055232008-10-27 17:20:55 +00004289 }
4290 std::string RewrittenStr = RewrittenBlockExprs[CE];
4291 const char *cstr = RewrittenStr.c_str();
4292 while (*cstr++ != '{') ;
4293 S += cstr;
4294 S += "\n";
4295 return S;
4296}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004297
Steve Naroff54055232008-10-27 17:20:55 +00004298std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004299 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004300 std::string Tag) {
4301 std::string StructRef = "struct " + Tag;
4302 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004303
Steve Naroff54055232008-10-27 17:20:55 +00004304 S += funcName;
4305 S += "_block_copy_" + utostr(i);
4306 S += "(" + StructRef;
4307 S += "*dst, " + StructRef;
4308 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004309 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004310 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004311 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004312 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004313 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004314 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004315 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004316 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004317 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004318 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004319 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004320 else
4321 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004322 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004323 S += "}\n";
4324
Steve Naroff54055232008-10-27 17:20:55 +00004325 S += "\nstatic void __";
4326 S += funcName;
4327 S += "_block_dispose_" + utostr(i);
4328 S += "(" + StructRef;
4329 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004330 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004331 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004332 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004333 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004334 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004335 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004336 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004337 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004338 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004339 else
4340 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004341 }
Mike Stump1eb44332009-09-09 15:08:12 +00004342 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004343 return S;
4344}
4345
Steve Naroff01aec112009-12-06 21:14:13 +00004346std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4347 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004348 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004349 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004350
Steve Naroff54055232008-10-27 17:20:55 +00004351 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004352 S += " struct " + Desc;
4353 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004354
Steve Naroff01aec112009-12-06 21:14:13 +00004355 Constructor += "(void *fp, "; // Invoke function pointer.
4356 Constructor += "struct " + Desc; // Descriptor pointer.
4357 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004358
Steve Naroff54055232008-10-27 17:20:55 +00004359 if (BlockDeclRefs.size()) {
4360 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004361 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004362 E = BlockByCopyDecls.end(); I != E; ++I) {
4363 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004364 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004365 std::string ArgName = "_" + FieldName;
4366 // Handle nested closure invocation. For example:
4367 //
4368 // void (^myImportedBlock)(void);
4369 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004370 //
Steve Naroff54055232008-10-27 17:20:55 +00004371 // void (^anotherBlock)(void);
4372 // anotherBlock = ^(void) {
4373 // myImportedBlock(); // import and invoke the closure
4374 // };
4375 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004376 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004377 S += "struct __block_impl *";
4378 Constructor += ", void *" + ArgName;
4379 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004380 QualType QT = (*I)->getType();
4381 if (HasLocalVariableExternalStorage(*I))
4382 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004383 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4384 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004385 Constructor += ", " + ArgName;
4386 }
4387 S += FieldName + ";\n";
4388 }
4389 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004390 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004391 E = BlockByRefDecls.end(); I != E; ++I) {
4392 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004393 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004394 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004395 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004396 std::string TypeString;
4397 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004398 TypeString += " *";
4399 FieldName = TypeString + FieldName;
4400 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004401 Constructor += ", " + ArgName;
4402 }
4403 S += FieldName + "; // by ref\n";
4404 }
4405 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004406 Constructor += ", int flags=0)";
4407 // Initialize all "by copy" arguments.
4408 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004409 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004410 E = BlockByCopyDecls.end(); I != E; ++I) {
4411 std::string Name = (*I)->getNameAsString();
4412 if (firsTime) {
4413 Constructor += " : ";
4414 firsTime = false;
4415 }
4416 else
4417 Constructor += ", ";
4418 if (isTopLevelBlockPointerType((*I)->getType()))
4419 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4420 else
4421 Constructor += Name + "(_" + Name + ")";
4422 }
4423 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004424 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004425 E = BlockByRefDecls.end(); I != E; ++I) {
4426 std::string Name = (*I)->getNameAsString();
4427 if (firsTime) {
4428 Constructor += " : ";
4429 firsTime = false;
4430 }
4431 else
4432 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004433 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004434 }
4435
4436 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004437 if (GlobalVarDecl)
4438 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4439 else
4440 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004441 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004442
Steve Naroff01aec112009-12-06 21:14:13 +00004443 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004444 } else {
4445 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004446 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004447 if (GlobalVarDecl)
4448 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4449 else
4450 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004451 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4452 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004453 }
4454 Constructor += " ";
4455 Constructor += "}\n";
4456 S += Constructor;
4457 S += "};\n";
4458 return S;
4459}
4460
Steve Naroff01aec112009-12-06 21:14:13 +00004461std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4462 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004463 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004464 unsigned hasCopy) {
4465 std::string S = "\nstatic struct " + DescTag;
4466
4467 S += " {\n unsigned long reserved;\n";
4468 S += " unsigned long Block_size;\n";
4469 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004470 S += " void (*copy)(struct ";
4471 S += ImplTag; S += "*, struct ";
4472 S += ImplTag; S += "*);\n";
4473
4474 S += " void (*dispose)(struct ";
4475 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004476 }
4477 S += "} ";
4478
4479 S += DescTag + "_DATA = { 0, sizeof(struct ";
4480 S += ImplTag + ")";
4481 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004482 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4483 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004484 }
4485 S += "};\n";
4486 return S;
4487}
4488
Steve Naroff54055232008-10-27 17:20:55 +00004489void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004490 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004491 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004492 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004493 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004494 bool RewriteSC = (GlobalVarDecl &&
4495 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004496 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004497 GlobalVarDecl->getType().getCVRQualifiers());
4498 if (RewriteSC) {
4499 std::string SC(" void __");
4500 SC += GlobalVarDecl->getNameAsString();
4501 SC += "() {}";
4502 InsertText(FunLocStart, SC);
4503 }
4504
Steve Naroff54055232008-10-27 17:20:55 +00004505 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004506 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4507 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004508 // Need to copy-in the inner copied-in variables not actually used in this
4509 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004510 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4511 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4512 ValueDecl *VD = Exp->getDecl();
4513 BlockDeclRefs.push_back(Exp);
4514 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4515 BlockByCopyDeclsPtrSet.insert(VD);
4516 BlockByCopyDecls.push_back(VD);
4517 }
4518 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4519 BlockByRefDeclsPtrSet.insert(VD);
4520 BlockByRefDecls.push_back(VD);
4521 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004522 // imported objects in the inner blocks not used in the outer
4523 // blocks must be copied/disposed in the outer block as well.
4524 if (Exp->isByRef() ||
4525 VD->getType()->isObjCObjectPointerType() ||
4526 VD->getType()->isBlockPointerType())
4527 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004528 }
Steve Naroff54055232008-10-27 17:20:55 +00004529
Daniel Dunbar4087f272010-08-17 22:39:59 +00004530 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4531 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004532
Steve Naroff01aec112009-12-06 21:14:13 +00004533 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004534
Benjamin Kramerd999b372010-02-14 14:14:16 +00004535 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004536
Steve Naroff01aec112009-12-06 21:14:13 +00004537 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Benjamin Kramerd999b372010-02-14 14:14:16 +00004539 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004540
4541 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004542 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004543 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004544 }
Steve Naroff01aec112009-12-06 21:14:13 +00004545 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4546 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004547 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004548
Steve Naroff54055232008-10-27 17:20:55 +00004549 BlockDeclRefs.clear();
4550 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004551 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004552 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004553 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004554 ImportedBlockDecls.clear();
4555 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004556 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004557 // Must insert any 'const/volatile/static here. Since it has been
4558 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004559 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004560 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004561 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004562 if (GlobalVarDecl->getType().isConstQualified())
4563 SC += "const ";
4564 if (GlobalVarDecl->getType().isVolatileQualified())
4565 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004566 if (GlobalVarDecl->getType().isRestrictQualified())
4567 SC += "restrict ";
4568 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004569 }
4570
Steve Naroff54055232008-10-27 17:20:55 +00004571 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004572 InnerDeclRefsCount.clear();
4573 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004574 RewrittenBlockExprs.clear();
4575}
4576
4577void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4578 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004579 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004580
Steve Naroff54055232008-10-27 17:20:55 +00004581 SynthesizeBlockLiterals(FunLocStart, FuncName);
4582}
4583
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004584static void BuildUniqueMethodName(std::string &Name,
4585 ObjCMethodDecl *MD) {
4586 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004587 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004588 Name += "__" + MD->getSelector().getAsString();
4589 // Convert colons to underscores.
4590 std::string::size_type loc = 0;
4591 while ((loc = Name.find(":", loc)) != std::string::npos)
4592 Name.replace(loc, 1, "_");
4593}
4594
Steve Naroff54055232008-10-27 17:20:55 +00004595void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004596 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4597 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004598 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004599 std::string FuncName;
4600 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004601 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004602}
4603
4604void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004605 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004606 if (*CI) {
4607 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4608 GetBlockDeclRefExprs(CBE->getBody());
4609 else
4610 GetBlockDeclRefExprs(*CI);
4611 }
4612 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004613 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004614 // FIXME: Handle enums.
4615 if (!isa<FunctionDecl>(CDRE->getDecl()))
4616 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004617 }
4618 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4619 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4620 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004621 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4622 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004623 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004624 BlockDeclRefs.push_back(BDRE);
4625 }
4626
Steve Naroff54055232008-10-27 17:20:55 +00004627 return;
4628}
4629
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004630void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004631 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004632 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004633 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004634 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004635 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4636 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004637 GetInnerBlockDeclRefExprs(CBE->getBody(),
4638 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004639 InnerContexts);
4640 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004641 else
4642 GetInnerBlockDeclRefExprs(*CI,
4643 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004644 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004645
4646 }
4647 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004648 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004649 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004650 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004651 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004652 }
4653 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4654 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4655 if (Var->isFunctionOrMethodVarDecl())
4656 ImportedLocalExternalDecls.insert(Var);
4657 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004658
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004659 return;
4660}
4661
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004662/// convertFunctionTypeOfBlocks - This routine converts a function type
4663/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004664/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004665/// all block pointers to function pointers.
4666QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4667 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4668 // FTP will be null for closures that don't take arguments.
4669 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004670 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004671 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004672 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004673
4674 if (FTP) {
4675 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4676 E = FTP->arg_type_end(); I && (I != E); ++I) {
4677 QualType t = *I;
4678 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004679 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004680 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004681 ArgTypes.push_back(t);
4682 }
4683 }
4684 QualType FuncType;
4685 // FIXME. Does this work if block takes no argument but has a return type
4686 // which is of block type?
4687 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004688 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004689 else FuncType = QualType(FT, 0);
4690 return FuncType;
4691}
4692
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004693Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004694 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004695 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004697 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004698 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004699 } else if (const BlockDeclRefExpr *CDRE =
4700 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004701 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004702 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004703 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004704 }
4705 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4706 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4707 }
4708 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4709 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4710 else if (const ConditionalOperator *CEXPR =
4711 dyn_cast<ConditionalOperator>(BlockExp)) {
4712 Expr *LHSExp = CEXPR->getLHS();
4713 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4714 Expr *RHSExp = CEXPR->getRHS();
4715 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4716 Expr *CONDExp = CEXPR->getCond();
4717 ConditionalOperator *CondExpr =
4718 new (Context) ConditionalOperator(CONDExp,
4719 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004720 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004721 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004722 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004723 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4724 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00004725 } else if (const PseudoObjectExpr *POE
4726 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4727 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004728 } else {
4729 assert(1 && "RewriteBlockClass: Bad type");
4730 }
4731 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004732 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004733 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004734 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004735 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004737 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004738 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004739 &Context->Idents.get("__block_impl"));
4740 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004741
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004742 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004743 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004745 // Push the block argument type.
4746 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004747 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004748 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004749 E = FTP->arg_type_end(); I && (I != E); ++I) {
4750 QualType t = *I;
4751 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004752 if (!convertBlockPointerToFunctionPointer(t))
4753 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004754 ArgTypes.push_back(t);
4755 }
Steve Naroff54055232008-10-27 17:20:55 +00004756 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004757 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004758 QualType PtrToFuncCastType
4759 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004761 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004762
John McCall9d125032010-01-15 18:39:57 +00004763 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004764 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004765 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004766 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004767 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4768 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004769 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Douglas Gregor44b43212008-12-11 16:49:14 +00004771 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004772 SourceLocation(),
4773 &Context->Idents.get("FuncPtr"),
4774 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004775 /*BitWidth=*/0, /*Mutable=*/true,
4776 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004777 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004778 FD->getType(), VK_LValue,
4779 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004780
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004781
John McCall9d125032010-01-15 18:39:57 +00004782 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004783 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004784 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004785
Chris Lattner5f9e2722011-07-23 10:55:15 +00004786 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004787 // Add the implicit argument.
4788 BlkExprs.push_back(BlkCast);
4789 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004790 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004791 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004792 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004793 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004794 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4795 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004796 Exp->getType(), VK_RValue,
4797 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004798 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004799}
4800
Steve Naroff621edce2009-04-29 16:37:50 +00004801// We need to return the rewritten expression to handle cases where the
4802// BlockDeclRefExpr is embedded in another expression being rewritten.
4803// For example:
4804//
4805// int main() {
4806// __block Foo *f;
4807// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004808//
Steve Naroff621edce2009-04-29 16:37:50 +00004809// void (^myblock)() = ^() {
4810// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4811// i = 77;
4812// };
4813//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004814Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004815 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004816 // for each DeclRefExp where BYREFVAR is name of the variable.
4817 ValueDecl *VD;
4818 bool isArrow = true;
4819 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4820 VD = BDRE->getDecl();
4821 else {
4822 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4823 isArrow = false;
4824 }
4825
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004826 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004827 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004828 &Context->Idents.get("__forwarding"),
4829 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004830 /*BitWidth=*/0, /*Mutable=*/true,
4831 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004832 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4833 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004834 FD->getType(), VK_LValue,
4835 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004836
Chris Lattner5f9e2722011-07-23 10:55:15 +00004837 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004838 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004839 &Context->Idents.get(Name),
4840 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004841 /*BitWidth=*/0, /*Mutable=*/true,
4842 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004843 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004844 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004845
4846
4847
Steve Naroffdf8570d2009-02-02 17:19:26 +00004848 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004849 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4850 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004851 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004852 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004853 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004854}
4855
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004856// Rewrites the imported local variable V with external storage
4857// (static, extern, etc.) as *V
4858//
4859Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4860 ValueDecl *VD = DRE->getDecl();
4861 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4862 if (!ImportedLocalExternalDecls.count(Var))
4863 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004864 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4865 VK_LValue, OK_Ordinary,
4866 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004867 // Need parens to enforce precedence.
4868 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4869 Exp);
4870 ReplaceStmt(DRE, PE);
4871 return PE;
4872}
4873
Steve Naroffb2f9e512008-11-03 23:29:32 +00004874void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4875 SourceLocation LocStart = CE->getLParenLoc();
4876 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004877
4878 // Need to avoid trying to rewrite synthesized casts.
4879 if (LocStart.isInvalid())
4880 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004881 // Need to avoid trying to rewrite casts contained in macros.
4882 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4883 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Steve Naroff54055232008-10-27 17:20:55 +00004885 const char *startBuf = SM->getCharacterData(LocStart);
4886 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004887 QualType QT = CE->getType();
4888 const Type* TypePtr = QT->getAs<Type>();
4889 if (isa<TypeOfExprType>(TypePtr)) {
4890 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4891 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4892 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004893 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004894 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004895 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004896 return;
4897 }
Steve Naroff54055232008-10-27 17:20:55 +00004898 // advance the location to startArgList.
4899 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004900
Steve Naroff54055232008-10-27 17:20:55 +00004901 while (*argPtr++ && (argPtr < endBuf)) {
4902 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004903 case '^':
4904 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004905 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004906 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004907 break;
Steve Naroff54055232008-10-27 17:20:55 +00004908 }
4909 }
4910 return;
4911}
4912
4913void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4914 SourceLocation DeclLoc = FD->getLocation();
4915 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004916
Steve Naroff54055232008-10-27 17:20:55 +00004917 // We have 1 or more arguments that have closure pointers.
4918 const char *startBuf = SM->getCharacterData(DeclLoc);
4919 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004920
Steve Naroff54055232008-10-27 17:20:55 +00004921 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004922
Steve Naroff54055232008-10-27 17:20:55 +00004923 parenCount++;
4924 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004925 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004926 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Steve Naroff54055232008-10-27 17:20:55 +00004928 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Steve Naroff54055232008-10-27 17:20:55 +00004930 while (*argPtr++ && parenCount) {
4931 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004932 case '^':
4933 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004934 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004935 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004936 break;
4937 case '(':
4938 parenCount++;
4939 break;
4940 case ')':
4941 parenCount--;
4942 break;
Steve Naroff54055232008-10-27 17:20:55 +00004943 }
4944 }
4945 return;
4946}
4947
4948bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004949 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004950 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004951 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004952 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004953 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004954 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004955 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004956 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004957 }
4958 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004959 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004960 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004961 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004962 return true;
4963 }
4964 return false;
4965}
4966
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004967bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4968 const FunctionProtoType *FTP;
4969 const PointerType *PT = QT->getAs<PointerType>();
4970 if (PT) {
4971 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4972 } else {
4973 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4974 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4975 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4976 }
4977 if (FTP) {
4978 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004979 E = FTP->arg_type_end(); I != E; ++I) {
4980 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004981 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004982 if ((*I)->isObjCObjectPointerType() &&
4983 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4984 return true;
4985 }
4986
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004987 }
4988 return false;
4989}
4990
Ted Kremenek8189cde2009-02-07 01:47:29 +00004991void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4992 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004993 const char *argPtr = strchr(Name, '(');
4994 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004995
Steve Naroff54055232008-10-27 17:20:55 +00004996 LParen = argPtr; // output the start.
4997 argPtr++; // skip past the left paren.
4998 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Steve Naroff54055232008-10-27 17:20:55 +00005000 while (*argPtr && parenCount) {
5001 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005002 case '(': parenCount++; break;
5003 case ')': parenCount--; break;
5004 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005005 }
5006 if (parenCount) argPtr++;
5007 }
5008 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5009 RParen = argPtr; // output the end
5010}
5011
5012void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5013 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5014 RewriteBlockPointerFunctionArgs(FD);
5015 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005016 }
Steve Naroff54055232008-10-27 17:20:55 +00005017 // Handle Variables and Typedefs.
5018 SourceLocation DeclLoc = ND->getLocation();
5019 QualType DeclT;
5020 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5021 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005022 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005023 DeclT = TDD->getUnderlyingType();
5024 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5025 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005026 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005027 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005028
Steve Naroff54055232008-10-27 17:20:55 +00005029 const char *startBuf = SM->getCharacterData(DeclLoc);
5030 const char *endBuf = startBuf;
5031 // scan backward (from the decl location) for the end of the previous decl.
5032 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5033 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005034 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005035 std::string buf;
5036 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005037 // *startBuf != '^' if we are dealing with a pointer to function that
5038 // may take block argument types (which will be handled below).
5039 if (*startBuf == '^') {
5040 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005041 buf = '*';
5042 startBuf++;
5043 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005044 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005045 while (*startBuf != ')') {
5046 buf += *startBuf;
5047 startBuf++;
5048 OrigLength++;
5049 }
5050 buf += ')';
5051 OrigLength++;
5052
5053 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5054 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005055 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005056 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005057 DeclLoc = ND->getLocation();
5058 startBuf = SM->getCharacterData(DeclLoc);
5059 const char *argListBegin, *argListEnd;
5060 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5061 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005062 if (*argListBegin == '^')
5063 buf += '*';
5064 else if (*argListBegin == '<') {
5065 buf += "/*";
5066 buf += *argListBegin++;
5067 OrigLength++;;
5068 while (*argListBegin != '>') {
5069 buf += *argListBegin++;
5070 OrigLength++;
5071 }
5072 buf += *argListBegin;
5073 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005074 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005075 else
5076 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005077 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005078 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005079 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005080 buf += ')';
5081 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005082 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005083 ReplaceText(Start, OrigLength, buf);
5084
Steve Naroff54055232008-10-27 17:20:55 +00005085 return;
5086}
5087
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005088
5089/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5090/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5091/// struct Block_byref_id_object *src) {
5092/// _Block_object_assign (&_dest->object, _src->object,
5093/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5094/// [|BLOCK_FIELD_IS_WEAK]) // object
5095/// _Block_object_assign(&_dest->object, _src->object,
5096/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5097/// [|BLOCK_FIELD_IS_WEAK]) // block
5098/// }
5099/// And:
5100/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5101/// _Block_object_dispose(_src->object,
5102/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5103/// [|BLOCK_FIELD_IS_WEAK]) // object
5104/// _Block_object_dispose(_src->object,
5105/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5106/// [|BLOCK_FIELD_IS_WEAK]) // block
5107/// }
5108
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005109std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5110 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005111 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005112 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005113 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005114 CopyDestroyCache.insert(flag);
5115 S = "static void __Block_byref_id_object_copy_";
5116 S += utostr(flag);
5117 S += "(void *dst, void *src) {\n";
5118
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005119 // offset into the object pointer is computed as:
5120 // void * + void* + int + int + void* + void *
5121 unsigned IntSize =
5122 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5123 unsigned VoidPtrSize =
5124 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5125
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005126 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005127 S += " _Block_object_assign((char*)dst + ";
5128 S += utostr(offset);
5129 S += ", *(void * *) ((char*)src + ";
5130 S += utostr(offset);
5131 S += "), ";
5132 S += utostr(flag);
5133 S += ");\n}\n";
5134
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005135 S += "static void __Block_byref_id_object_dispose_";
5136 S += utostr(flag);
5137 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005138 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5139 S += utostr(offset);
5140 S += "), ";
5141 S += utostr(flag);
5142 S += ");\n}\n";
5143 return S;
5144}
5145
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005146/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5147/// the declaration into:
5148/// struct __Block_byref_ND {
5149/// void *__isa; // NULL for everything except __weak pointers
5150/// struct __Block_byref_ND *__forwarding;
5151/// int32_t __flags;
5152/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005153/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5154/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005155/// typex ND;
5156/// };
5157///
5158/// It then replaces declaration of ND variable with:
5159/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5160/// __size=sizeof(struct __Block_byref_ND),
5161/// ND=initializer-if-any};
5162///
5163///
5164void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005165 // Insert declaration for the function in which block literal is
5166 // used.
5167 if (CurFunctionDeclToDeclareForBlock)
5168 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005169 int flag = 0;
5170 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005172 if (DeclLoc.isInvalid())
5173 // If type location is missing, it is because of missing type (a warning).
5174 // Use variable's location which is good for this case.
5175 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005176 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005177 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005178 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005179 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005180 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005181 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005182 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005183 ByrefType += " {\n";
5184 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005185 RewriteByRefString(ByrefType, Name, ND);
5186 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005187 ByrefType += " int __flags;\n";
5188 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005189 // Add void *__Block_byref_id_object_copy;
5190 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005191 QualType Ty = ND->getType();
5192 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5193 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005194 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5195 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005196 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005197
5198 QualType T = Ty;
5199 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005200 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005201
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005202 ByrefType += " " + Name + ";\n";
5203 ByrefType += "};\n";
5204 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005205 SourceLocation FunLocStart;
5206 if (CurFunctionDef)
5207 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5208 else {
5209 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5210 FunLocStart = CurMethodDef->getLocStart();
5211 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005212 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005213 if (Ty.isObjCGCWeak()) {
5214 flag |= BLOCK_FIELD_IS_WEAK;
5215 isa = 1;
5216 }
5217
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005218 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005219 flag = BLOCK_BYREF_CALLER;
5220 QualType Ty = ND->getType();
5221 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5222 if (Ty->isBlockPointerType())
5223 flag |= BLOCK_FIELD_IS_BLOCK;
5224 else
5225 flag |= BLOCK_FIELD_IS_OBJECT;
5226 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005227 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005228 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005229 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005230
5231 // struct __Block_byref_ND ND =
5232 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5233 // initializer-if-any};
5234 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005235 unsigned flags = 0;
5236 if (HasCopyAndDispose)
5237 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005238 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005239 ByrefType.clear();
5240 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005241 std::string ForwardingCastType("(");
5242 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005243 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005244 ByrefType += " " + Name + " = {(void*)";
5245 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005246 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005247 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005248 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005249 ByrefType += "sizeof(";
5250 RewriteByRefString(ByrefType, Name, ND);
5251 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005252 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005253 ByrefType += ", __Block_byref_id_object_copy_";
5254 ByrefType += utostr(flag);
5255 ByrefType += ", __Block_byref_id_object_dispose_";
5256 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005257 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005258 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005259 unsigned nameSize = Name.size();
5260 // for block or function pointer declaration. Name is aleady
5261 // part of the declaration.
5262 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5263 nameSize = 1;
5264 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005265 }
5266 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005267 SourceLocation startLoc;
5268 Expr *E = ND->getInit();
5269 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5270 startLoc = ECE->getLParenLoc();
5271 else
5272 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005273 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005274 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005275 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005276 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005277 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005278 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005279 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005280 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005281 ByrefType += "sizeof(";
5282 RewriteByRefString(ByrefType, Name, ND);
5283 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005284 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005285 ByrefType += "__Block_byref_id_object_copy_";
5286 ByrefType += utostr(flag);
5287 ByrefType += ", __Block_byref_id_object_dispose_";
5288 ByrefType += utostr(flag);
5289 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005290 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005291 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005292
5293 // Complete the newly synthesized compound expression by inserting a right
5294 // curly brace before the end of the declaration.
5295 // FIXME: This approach avoids rewriting the initializer expression. It
5296 // also assumes there is only one declarator. For example, the following
5297 // isn't currently supported by this routine (in general):
5298 //
5299 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5300 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005301 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5302 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005303 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5304 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005305 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005306
Benjamin Kramerd999b372010-02-14 14:14:16 +00005307 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005308 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005309 return;
5310}
5311
Mike Stump1eb44332009-09-09 15:08:12 +00005312void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005313 // Add initializers for any closure decl refs.
5314 GetBlockDeclRefExprs(Exp->getBody());
5315 if (BlockDeclRefs.size()) {
5316 // Unique all "by copy" declarations.
5317 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005318 if (!BlockDeclRefs[i]->isByRef()) {
5319 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5320 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5321 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5322 }
5323 }
Steve Naroff54055232008-10-27 17:20:55 +00005324 // Unique all "by ref" declarations.
5325 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5326 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005327 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5328 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5329 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5330 }
Steve Naroff54055232008-10-27 17:20:55 +00005331 }
5332 // Find any imported blocks...they will need special attention.
5333 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005334 if (BlockDeclRefs[i]->isByRef() ||
5335 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005336 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005337 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005338 }
5339}
5340
Chris Lattner5f9e2722011-07-23 10:55:15 +00005341FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005342 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005343 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005344 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5345 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005346 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005347}
5348
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005349Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005350 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005351 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005352 Blocks.push_back(Exp);
5353
5354 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005355
5356 // Add inner imported variables now used in current block.
5357 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005358 if (!InnerBlockDeclRefs.empty()) {
5359 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5360 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5361 ValueDecl *VD = Exp->getDecl();
5362 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005363 // We need to save the copied-in variables in nested
5364 // blocks because it is needed at the end for some of the API generations.
5365 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005366 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5367 BlockDeclRefs.push_back(Exp);
5368 BlockByCopyDeclsPtrSet.insert(VD);
5369 BlockByCopyDecls.push_back(VD);
5370 }
5371 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5372 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5373 BlockDeclRefs.push_back(Exp);
5374 BlockByRefDeclsPtrSet.insert(VD);
5375 BlockByRefDecls.push_back(VD);
5376 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005377 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005378 // Find any imported blocks...they will need special attention.
5379 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5380 if (InnerBlockDeclRefs[i]->isByRef() ||
5381 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5382 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5383 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005384 }
5385 InnerDeclRefsCount.push_back(countOfInnerDecls);
5386
Steve Narofffa15fd92008-10-28 20:29:00 +00005387 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005388
Steve Narofffa15fd92008-10-28 20:29:00 +00005389 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005390 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005391 else if (CurMethodDef)
5392 BuildUniqueMethodName(FuncName, CurMethodDef);
5393 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005394 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005395
Steve Narofffa15fd92008-10-28 20:29:00 +00005396 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005397
Steve Narofffa15fd92008-10-28 20:29:00 +00005398 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5399 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005400
Steve Narofffa15fd92008-10-28 20:29:00 +00005401 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005402 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5403 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005404
5405 FunctionDecl *FD;
5406 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005407
Steve Narofffa15fd92008-10-28 20:29:00 +00005408 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005409 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005410 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5411 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005412
Chris Lattner5f9e2722011-07-23 10:55:15 +00005413 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005414
Steve Narofffdc03722008-10-29 21:23:59 +00005415 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005416 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005417 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005418 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005419 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005420 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005421 InitExprs.push_back(castExpr);
5422
Steve Naroff01aec112009-12-06 21:14:13 +00005423 // Initialize the block descriptor.
5424 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005426 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5427 SourceLocation(), SourceLocation(),
5428 &Context->Idents.get(DescData.c_str()),
5429 Context->VoidPtrTy, 0,
5430 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005431 UnaryOperator *DescRefExpr =
5432 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5433 Context->VoidPtrTy,
5434 VK_LValue,
5435 SourceLocation()),
5436 UO_AddrOf,
5437 Context->getPointerType(Context->VoidPtrTy),
5438 VK_RValue, OK_Ordinary,
5439 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005440 InitExprs.push_back(DescRefExpr);
5441
Steve Narofffa15fd92008-10-28 20:29:00 +00005442 // Add initializers for any closure decl refs.
5443 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005444 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005445 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005446 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005447 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005449 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005450 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005451 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5452 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005453 if (HasLocalVariableExternalStorage(*I)) {
5454 QualType QT = (*I)->getType();
5455 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005456 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5457 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005458 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005459 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005460 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005461 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5462 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005463 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005464 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005466 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005467 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5468 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005469 if (HasLocalVariableExternalStorage(*I)) {
5470 QualType QT = (*I)->getType();
5471 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005472 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5473 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005474 }
5475
Steve Narofffa15fd92008-10-28 20:29:00 +00005476 }
Mike Stump1eb44332009-09-09 15:08:12 +00005477 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005478 }
5479 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005480 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005481 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005482 ValueDecl *ND = (*I);
5483 std::string Name(ND->getNameAsString());
5484 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005485 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005486 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5487 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005488 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005489 SourceLocation(), SourceLocation(),
5490 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005491 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5492 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5493
Daniel Dunbar4087f272010-08-17 22:39:59 +00005494 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005495 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5496 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005497 bool isNestedCapturedVar = false;
5498 if (block)
5499 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5500 ce = block->capture_end(); ci != ce; ++ci) {
5501 const VarDecl *variable = ci->getVariable();
5502 if (variable == ND && ci->isNested()) {
5503 assert (ci->isByRef() &&
5504 "SynthBlockInitExpr - captured block variable is not byref");
5505 isNestedCapturedVar = true;
5506 break;
5507 }
5508 }
5509 // captured nested byref variable has its address passed. Do not take
5510 // its address again.
5511 if (!isNestedCapturedVar)
5512 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005513 Context->getPointerType(Exp->getType()),
5514 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005515 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005516 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005517 }
5518 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005519 if (ImportedBlockDecls.size()) {
5520 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5521 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005522 unsigned IntSize =
5523 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005524 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5525 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005526 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005527 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005528 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005529 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005530 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005531 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005532 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005533 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005534 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005535 BlockDeclRefs.clear();
5536 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005537 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005538 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005539 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005540 ImportedBlockDecls.clear();
5541 return NewRep;
5542}
5543
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005544bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5545 if (const ObjCForCollectionStmt * CS =
5546 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5547 return CS->getElement() == DS;
5548 return false;
5549}
5550
Steve Narofffa15fd92008-10-28 20:29:00 +00005551//===----------------------------------------------------------------------===//
5552// Function Body / Expression rewriting
5553//===----------------------------------------------------------------------===//
5554
5555Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005556 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005557 isa<DoStmt>(S) || isa<ForStmt>(S))
5558 Stmts.push_back(S);
5559 else if (isa<ObjCForCollectionStmt>(S)) {
5560 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005561 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005562 }
Mike Stump1eb44332009-09-09 15:08:12 +00005563
John McCall4b9c2d22011-11-06 09:01:30 +00005564 // Pseudo-object operations and ivar references need special
5565 // treatment because we're going to recursively rewrite them.
5566 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5567 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5568 return RewritePropertyOrImplicitSetter(PseudoOp);
5569 } else {
5570 return RewritePropertyOrImplicitGetter(PseudoOp);
5571 }
5572 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5573 return RewriteObjCIvarRefExpr(IvarRefExpr);
5574 }
5575
Steve Narofffa15fd92008-10-28 20:29:00 +00005576 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005577
Steve Narofffa15fd92008-10-28 20:29:00 +00005578 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005579 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005580 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00005581 Stmt *childStmt = (*CI);
5582 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005583 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00005584 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005585 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005586 }
Mike Stump1eb44332009-09-09 15:08:12 +00005587
Steve Narofffa15fd92008-10-28 20:29:00 +00005588 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005589 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005590 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5591 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005592 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005593 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005594 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005595 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005596 Stmt *SaveCurrentBody = CurrentBody;
5597 CurrentBody = BE->getBody();
5598 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005599 // block literal on rhs of a property-dot-sytax assignment
5600 // must be replaced by its synthesize ast so getRewrittenText
5601 // works as expected. In this case, what actually ends up on RHS
5602 // is the blockTranscribed which is the helper function for the
5603 // block literal; as in: self.c = ^() {[ace ARR];};
5604 bool saveDisableReplaceStmt = DisableReplaceStmt;
5605 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005607 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005608 CurrentBody = SaveCurrentBody;
5609 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005610 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005611 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005612 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005613 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005615 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5616
Steve Narofffa15fd92008-10-28 20:29:00 +00005617 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005618 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005619 return blockTranscribed;
5620 }
5621 // Handle specific things.
5622 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5623 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005624
Steve Narofffa15fd92008-10-28 20:29:00 +00005625 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5626 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005627
Steve Narofffa15fd92008-10-28 20:29:00 +00005628 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5629 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Steve Narofffa15fd92008-10-28 20:29:00 +00005631 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005632#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005633 // Before we rewrite it, put the original message expression in a comment.
5634 SourceLocation startLoc = MessExpr->getLocStart();
5635 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005636
Steve Narofffa15fd92008-10-28 20:29:00 +00005637 const char *startBuf = SM->getCharacterData(startLoc);
5638 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005639
Steve Narofffa15fd92008-10-28 20:29:00 +00005640 std::string messString;
5641 messString += "// ";
5642 messString.append(startBuf, endBuf-startBuf+1);
5643 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005644
5645 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005646 // InsertText(clang::SourceLocation, char const*, unsigned int).
5647 // InsertText(startLoc, messString.c_str(), messString.size());
5648 // Tried this, but it didn't work either...
5649 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005650#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005651 return RewriteMessageExpr(MessExpr);
5652 }
Mike Stump1eb44332009-09-09 15:08:12 +00005653
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5655 return RewriteObjCTryStmt(StmtTry);
5656
5657 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5658 return RewriteObjCSynchronizedStmt(StmtTry);
5659
5660 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5661 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005662
Steve Narofffa15fd92008-10-28 20:29:00 +00005663 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5664 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005665
5666 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005667 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005668 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005669 OrigStmtRange.getEnd());
5670 if (BreakStmt *StmtBreakStmt =
5671 dyn_cast<BreakStmt>(S))
5672 return RewriteBreakStmt(StmtBreakStmt);
5673 if (ContinueStmt *StmtContinueStmt =
5674 dyn_cast<ContinueStmt>(S))
5675 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005676
5677 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005678 // and cast exprs.
5679 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5680 // FIXME: What we're doing here is modifying the type-specifier that
5681 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005682 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005683 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5684 // the context of an ObjCForCollectionStmt. For example:
5685 // NSArray *someArray;
5686 // for (id <FooProtocol> index in someArray) ;
5687 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5688 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005689 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005690 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005691
Steve Narofffa15fd92008-10-28 20:29:00 +00005692 // Blocks rewrite rules.
5693 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5694 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005695 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005696 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005697 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005698 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005699 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005700 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005701 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005702 if (VD->hasAttr<BlocksAttr>()) {
5703 static unsigned uniqueByrefDeclCount = 0;
5704 assert(!BlockByRefDeclNo.count(ND) &&
5705 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5706 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005707 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005708 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005709 else
5710 RewriteTypeOfDecl(VD);
5711 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005712 }
Richard Smith162e1c12011-04-15 14:24:37 +00005713 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005714 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005715 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005716 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005717 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5718 }
5719 }
5720 }
Mike Stump1eb44332009-09-09 15:08:12 +00005721
Steve Narofffa15fd92008-10-28 20:29:00 +00005722 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5723 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005724
5725 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005726 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5727 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005728 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5729 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005730 && "Statement stack mismatch");
5731 Stmts.pop_back();
5732 }
5733 // Handle blocks rewriting.
5734 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5735 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005736 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005737 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5739 ValueDecl *VD = DRE->getDecl();
5740 if (VD->hasAttr<BlocksAttr>())
5741 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005742 if (HasLocalVariableExternalStorage(VD))
5743 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005744 }
5745
Steve Narofffa15fd92008-10-28 20:29:00 +00005746 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005747 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005748 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005749 ReplaceStmt(S, BlockCall);
5750 return BlockCall;
5751 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005752 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005753 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005754 RewriteCastExpr(CE);
5755 }
5756#if 0
5757 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005758 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5759 ICE->getSubExpr(),
5760 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005761 // Get the new text.
5762 std::string SStr;
5763 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005764 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005765 const std::string &Str = Buf.str();
5766
5767 printf("CAST = %s\n", &Str[0]);
5768 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5769 delete S;
5770 return Replacement;
5771 }
5772#endif
5773 // Return this stmt unmodified.
5774 return S;
5775}
5776
Steve Naroff3d7e7862009-12-05 15:55:59 +00005777void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5778 for (RecordDecl::field_iterator i = RD->field_begin(),
5779 e = RD->field_end(); i != e; ++i) {
5780 FieldDecl *FD = *i;
5781 if (isTopLevelBlockPointerType(FD->getType()))
5782 RewriteBlockPointerDecl(FD);
5783 if (FD->getType()->isObjCQualifiedIdType() ||
5784 FD->getType()->isObjCQualifiedInterfaceType())
5785 RewriteObjCQualifiedInterfaceTypes(FD);
5786 }
5787}
5788
Steve Narofffa15fd92008-10-28 20:29:00 +00005789/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5790/// main file of the input.
5791void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005793 if (FD->isOverloadedOperator())
5794 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005795
Steve Narofffa15fd92008-10-28 20:29:00 +00005796 // Since function prototypes don't have ParmDecl's, we check the function
5797 // prototype. This enables us to rewrite function declarations and
5798 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005799 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005800
Sebastian Redld3a413d2009-04-26 20:35:05 +00005801 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005802 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005803 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005804 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005805 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005806 Body =
5807 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5808 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005809 CurrentBody = 0;
5810 if (PropParentMap) {
5811 delete PropParentMap;
5812 PropParentMap = 0;
5813 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005814 // This synthesizes and inserts the block "impl" struct, invoke function,
5815 // and any copy/dispose helper functions.
5816 InsertBlockLiteralsWithinFunction(FD);
5817 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005818 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005819 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005820 return;
5821 }
5822 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005823 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005824 CurMethodDef = MD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005825 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005826 Body =
5827 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5828 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005829 CurrentBody = 0;
5830 if (PropParentMap) {
5831 delete PropParentMap;
5832 PropParentMap = 0;
5833 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005834 InsertBlockLiteralsWithinMethod(MD);
5835 CurMethodDef = 0;
5836 }
5837 }
5838 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5839 ClassImplementation.push_back(CI);
5840 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5841 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005842 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005843 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005844 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5845 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005846 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005847 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005848 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005849 CheckFunctionPointerDecl(VD->getType(), VD);
5850 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005851 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005852 RewriteCastExpr(CE);
5853 }
5854 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005855 } else if (VD->getType()->isRecordType()) {
5856 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00005857 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005858 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005859 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005860 if (VD->getInit()) {
5861 GlobalVarDecl = VD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005862 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005863 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005864 CurrentBody = 0;
5865 if (PropParentMap) {
5866 delete PropParentMap;
5867 PropParentMap = 0;
5868 }
Mike Stump1eb44332009-09-09 15:08:12 +00005869 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005870 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005871 GlobalVarDecl = 0;
5872
5873 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005874 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005875 RewriteCastExpr(CE);
5876 }
5877 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005878 return;
5879 }
Richard Smith162e1c12011-04-15 14:24:37 +00005880 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005881 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005882 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005883 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005884 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5885 return;
5886 }
5887 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
John McCall5e1cdac2011-10-07 06:10:15 +00005888 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005889 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005890 return;
5891 }
5892 // Nothing yet.
5893}
5894
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005895void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005896 if (Diags.hasErrorOccurred())
5897 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005898
Steve Narofffa15fd92008-10-28 20:29:00 +00005899 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005900
Steve Naroff621edce2009-04-29 16:37:50 +00005901 // Here's a great place to add any extra declarations that may be needed.
5902 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005903 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005904 E = ProtocolExprDecls.end(); I != E; ++I)
5905 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5906
Benjamin Kramerd999b372010-02-14 14:14:16 +00005907 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005908 if (ClassImplementation.size() || CategoryImplementation.size())
5909 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005910
Steve Narofffa15fd92008-10-28 20:29:00 +00005911 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5912 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005913 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005914 Rewrite.getRewriteBufferFor(MainFileID)) {
5915 //printf("Changed:\n");
5916 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5917 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005918 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005919 }
Steve Narofface66252008-11-13 20:07:04 +00005920
Steve Naroff621edce2009-04-29 16:37:50 +00005921 if (ClassImplementation.size() || CategoryImplementation.size() ||
5922 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005923 // Rewrite Objective-c meta data*
5924 std::string ResultStr;
5925 SynthesizeMetaDataIntoBuffer(ResultStr);
5926 // Emit metadata.
5927 *OutFile << ResultStr;
5928 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005929 OutFile->flush();
5930}