blob: 48649574c038acfec61001fac1bff0880385c82f [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanianf4609d42010-03-01 23:36:21 +000031
Chris Lattnere99c8322007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000034
Chris Lattnere99c8322007-10-11 00:43:27 +000035namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000036 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian83077422011-12-08 18:25:15 +000037 protected:
38
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000039 enum {
Nico Weber1879bca2010-11-22 10:26:41 +000040 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000041 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
Nico Weber1879bca2010-11-22 10:26:41 +000045 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000046 helpers */
Nico Weber1879bca2010-11-22 10:26:41 +000047 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +000048 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000060 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahanian83077422011-12-08 18:25:15 +000061
Chris Lattner0bd1c972007-10-16 21:07:07 +000062 Rewriter Rewrite;
David Blaikie9c902b52011-09-25 23:23:43 +000063 DiagnosticsEngine &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000064 const LangOptions &LangOpts;
Chris Lattnerc6d91c02007-10-17 22:35:30 +000065 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000066 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000067 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000068 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000069 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000070 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
Fariborz Jahanian8efef602011-12-05 19:50:04 +000072 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
78 unsigned RewriteFailedDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +000083
Fariborz Jahanian8efef602011-12-05 19:50:04 +000084 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
Fariborz Jahanian83077422011-12-08 18:25:15 +000087 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahanian8efef602011-12-05 19:50:04 +000088 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000103 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump11289f42009-09-09 15:08:12 +0000106
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000107 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +0000111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
113 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000114 SmallVector<Stmt *, 32> Stmts;
115 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +0000116 // Remember all the @protocol(<expr>) expressions.
117 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahaniane3891582010-01-05 18:04:40 +0000118
119 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000120
121 // Block expressions.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000122 SmallVector<BlockExpr *, 32> Blocks;
123 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian8652be02010-02-24 22:48:18 +0000125
John McCall113bee02012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump11289f42009-09-09 15:08:12 +0000127
Steve Naroff677ab3a2008-10-27 17:20:55 +0000128 // Block related declarations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000133 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000135 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
136
Steve Naroff677ab3a2008-10-27 17:20:55 +0000137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff22216db2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000143
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000144 // Needed for header files being rewritten
145 bool IsHeader;
146 bool SilenceRewriteMacroWarning;
147 bool objc_impl_method;
148
Steve Naroff08628db2008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
John McCallfe96e0b2011-11-06 09:01:30 +0000150 class DisableReplaceStmtScope {
151 RewriteObjC &R;
152 bool SavedValue;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000153
John McCallfe96e0b2011-11-06 09:01:30 +0000154 public:
155 DisableReplaceStmtScope(RewriteObjC &R)
156 : R(R), SavedValue(R.DisableReplaceStmt) {
157 R.DisableReplaceStmt = true;
158 }
159 ~DisableReplaceStmtScope() {
160 R.DisableReplaceStmt = SavedValue;
161 }
162 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000163 void InitializeCommon(ASTContext &context);
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattnere99c8322007-10-11 00:43:27 +0000165 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000166
Chris Lattner3c799d72007-10-24 17:06:59 +0000167 // Top Level Driver code.
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000168 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000169 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000170 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
171 if (!Class->isThisDeclarationADefinition()) {
172 RewriteForwardClassDecl(D);
173 break;
174 }
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000175 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000176
Douglas Gregorf6102672012-01-01 21:23:57 +0000177 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
178 if (!Proto->isThisDeclarationADefinition()) {
179 RewriteForwardProtocolDecl(D);
180 break;
181 }
182 }
183
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000184 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000185 }
Argyrios Kyrtzidis841dd882011-11-18 00:26:59 +0000186 return true;
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000187 }
188 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000189 void HandleDeclInMainFile(Decl *D);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000190 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000191 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000192 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000193
194 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000195
Chris Lattnercf169832009-03-28 04:11:33 +0000196 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000197
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000198 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000199 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000200
Steve Naroff22216db2008-12-04 23:50:32 +0000201 if (ReplacingStmt)
202 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000203
Steve Naroff08628db2008-12-09 12:56:34 +0000204 if (DisableReplaceStmt)
John McCallfe96e0b2011-11-06 09:01:30 +0000205 return;
Steve Naroff08628db2008-12-09 12:56:34 +0000206
Steve Naroff22216db2008-12-04 23:50:32 +0000207 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahaniana7e1dcd2010-02-05 16:43:40 +0000208 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff22216db2008-12-04 23:50:32 +0000209 ReplacedNodes[Old] = New;
210 return;
211 }
212 if (SilenceRewriteMacroWarning)
213 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000214 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
215 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000216 }
Steve Naroff08628db2008-12-09 12:56:34 +0000217
218 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCallfe96e0b2011-11-06 09:01:30 +0000219 if (DisableReplaceStmt)
220 return;
221
Nick Lewycky508ef2c2010-10-31 21:07:24 +0000222 // Measure the old text.
Steve Naroff08628db2008-12-09 12:56:34 +0000223 int Size = Rewrite.getRangeSize(SrcRange);
224 if (Size == -1) {
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 return;
228 }
229 // Get the new text.
230 std::string SStr;
231 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000232 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000233 const std::string &Str = S.str();
234
235 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000236 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000237 ReplacedNodes[Old] = New;
238 return;
239 }
240 if (SilenceRewriteMacroWarning)
241 return;
242 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
243 << Old->getSourceRange();
244 }
245
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000246 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroff00a31762008-03-27 22:29:16 +0000247 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000248 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000249 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000250 SilenceRewriteMacroWarning)
251 return;
Mike Stump11289f42009-09-09 15:08:12 +0000252
Chris Lattner1780a852008-01-31 19:42:41 +0000253 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
254 }
Mike Stump11289f42009-09-09 15:08:12 +0000255
Chris Lattner9cc55f52008-01-31 19:51:04 +0000256 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000257 StringRef Str) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000258 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000259 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000260 SilenceRewriteMacroWarning)
261 return;
Mike Stump11289f42009-09-09 15:08:12 +0000262
Chris Lattner9cc55f52008-01-31 19:51:04 +0000263 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
264 }
Mike Stump11289f42009-09-09 15:08:12 +0000265
Chris Lattner3c799d72007-10-24 17:06:59 +0000266 // Syntactic Rewriting.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000267 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000268 void RewriteInclude();
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000269 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000270 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000271 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000272 const std::string &typedefString);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000273 void RewriteImplementations();
Steve Naroffc038b3a2008-12-02 17:36:43 +0000274 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
275 ObjCImplementationDecl *IMD,
276 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000277 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000278 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000279 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
280 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000281 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
282 const FunctionType *&FPRetType);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +0000283 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +0000284 ValueDecl *VD, bool def=false);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000285 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
286 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorf6102672012-01-01 21:23:57 +0000287 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000288 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000289 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000290 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000291 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbar8ab6c542010-06-30 19:16:53 +0000292 void RewriteBlockPointerType(std::string& Str, QualType Type);
293 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000294 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000295 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +0000296 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff873bd842008-07-29 18:15:38 +0000297 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000298
Chris Lattner3c799d72007-10-24 17:06:59 +0000299 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000300 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattner69534692007-10-24 16:57:36 +0000301 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCallfe96e0b2011-11-06 09:01:30 +0000302 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
303 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000304 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000305 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000306 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000307 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000308 void RewriteTryReturnStmts(Stmt *S);
309 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000310 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000311 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000312 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000313 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
314 SourceLocation OrigEnd);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000315 Stmt *RewriteBreakStmt(BreakStmt *S);
316 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000317 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000318
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000320 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000321
Mike Stump11289f42009-09-09 15:08:12 +0000322 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000323 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian02e07732009-12-23 02:07:37 +0000324 void RewriteByRefVar(VarDecl *VD);
John McCall113bee02012-03-10 09:33:50 +0000325 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +0000326 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000327 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000328
329 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
330 std::string &Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +0000331
332 virtual void Initialize(ASTContext &context) = 0;
333
334 // Metadata Rewriting.
335 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
336 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
337 StringRef prefix,
338 StringRef ClassName,
339 std::string &Result) = 0;
340 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
341 std::string &Result) = 0;
342 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
343 StringRef prefix,
344 StringRef ClassName,
345 std::string &Result) = 0;
346 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
347 std::string &Result) = 0;
348
349 // Rewriting ivar access
350 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
351 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
352 std::string &Result) = 0;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000353
Benjamin Kramer474261a2012-06-02 10:20:41 +0000354 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000355 // rewriting routines on the new ASTs.
356 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
357 Expr **args, unsigned nargs,
358 SourceLocation StartLoc=SourceLocation(),
359 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +0000360 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
361 QualType msgSendType,
362 QualType returnType,
363 SmallVectorImpl<QualType> &ArgTypes,
364 SmallVectorImpl<Expr*> &MsgExprs,
365 ObjCMethodDecl *Method);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000366 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
367 SourceLocation StartLoc=SourceLocation(),
368 SourceLocation EndLoc=SourceLocation());
369
370 void SynthCountByEnumWithState(std::string &buf);
371 void SynthMsgSendFunctionDecl();
372 void SynthMsgSendSuperFunctionDecl();
373 void SynthMsgSendStretFunctionDecl();
374 void SynthMsgSendFpretFunctionDecl();
375 void SynthMsgSendSuperStretFunctionDecl();
376 void SynthGetClassFunctionDecl();
377 void SynthGetMetaClassFunctionDecl();
378 void SynthGetSuperClassFunctionDecl();
379 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000380 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000381
382 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump11289f42009-09-09 15:08:12 +0000383 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000384 StringRef funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000385 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000386 StringRef funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000387 std::string SynthesizeBlockImpl(BlockExpr *CE,
388 std::string Tag, std::string Desc);
389 std::string SynthesizeBlockDescriptor(std::string DescTag,
390 std::string ImplTag,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000391 int i, StringRef funcName,
Steve Naroff30484702009-12-06 21:14:13 +0000392 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000393 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000394 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000395 StringRef FunName);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000396 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
397 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000398 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump11289f42009-09-09 15:08:12 +0000399
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000400 // Misc. helper routines.
Fariborz Jahanian8efef602011-12-05 19:50:04 +0000401 QualType getProtocolType();
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000402 void WarnAboutReturnGotoStmts(Stmt *S);
403 void HasReturnStmts(Stmt *S, bool &hasReturns);
404 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
405 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
406 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
407
408 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000409 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000410 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000411 void GetInnerBlockDeclRefExprs(Stmt *S,
412 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +0000413 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump11289f42009-09-09 15:08:12 +0000414
Steve Naroff677ab3a2008-10-27 17:20:55 +0000415 // We avoid calling Type::isBlockPointerType(), since it operates on the
416 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000417 bool isTopLevelBlockPointerType(QualType T) {
418 return isa<BlockPointerType>(T);
419 }
Mike Stump11289f42009-09-09 15:08:12 +0000420
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +0000421 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
422 /// to a function pointer type and upon success, returns true; false
423 /// otherwise.
424 bool convertBlockPointerToFunctionPointer(QualType &T) {
425 if (isTopLevelBlockPointerType(T)) {
426 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
427 T = Context->getPointerType(BPT->getPointeeType());
428 return true;
429 }
430 return false;
431 }
432
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000433 bool needToScanForQualifiers(QualType T);
434 QualType getSuperStructType();
435 QualType getConstantStringStructType();
436 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
437 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
438
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000439 void convertToUnqualifiedObjCType(QualType &T) {
440 if (T->isObjCQualifiedIdType())
441 T = Context->getObjCIdType();
442 else if (T->isObjCQualifiedClassType())
443 T = Context->getObjCClassType();
444 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +0000445 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
446 if (const ObjCObjectPointerType * OBJPT =
447 T->getAsObjCInterfacePointerType()) {
448 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
449 T = QualType(IFaceT, 0);
450 T = Context->getPointerType(T);
451 }
452 }
Fariborz Jahanian90d2e572010-11-05 18:34:46 +0000453 }
454
Steve Naroff677ab3a2008-10-27 17:20:55 +0000455 // FIXME: This predicate seems like it would be useful to add to ASTContext.
456 bool isObjCType(QualType T) {
457 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
458 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000459
Steve Naroff677ab3a2008-10-27 17:20:55 +0000460 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000461
Steve Naroff677ab3a2008-10-27 17:20:55 +0000462 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
463 OCT == Context->getCanonicalType(Context->getObjCClassType()))
464 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000466 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000467 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000468 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000469 return true;
470 }
471 return false;
472 }
473 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +0000474 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000475 void GetExtentOfArgList(const char *Name, const char *&LParen,
476 const char *&RParen);
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000477
Steve Naroffd9803712009-04-29 16:37:50 +0000478 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000479 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000480 if (From[i] == '"')
481 To += "\\\"";
482 else
483 To += From[i];
484 }
485 }
John McCalldb40c7f2010-12-14 08:05:40 +0000486
487 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000488 ArrayRef<QualType> args,
John McCalldb40c7f2010-12-14 08:05:40 +0000489 bool variadic = false) {
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000490 if (result == Context->getObjCInstanceType())
491 result = Context->getObjCIdType();
John McCalldb40c7f2010-12-14 08:05:40 +0000492 FunctionProtoType::ExtProtoInfo fpi;
493 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000494 return Context->getFunctionType(result, args, fpi);
John McCalldb40c7f2010-12-14 08:05:40 +0000495 }
John McCall97513962010-01-15 18:39:57 +0000496
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000497 // Helper function: create a CStyleCastExpr with trivial type source info.
498 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
499 CastKind Kind, Expr *E) {
500 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
501 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
502 SourceLocation(), SourceLocation());
503 }
504 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000505
506 class RewriteObjCFragileABI : public RewriteObjC {
507 public:
508
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512 D, LOpts,
513 silenceMacroWarn) {}
514
515 ~RewriteObjCFragileABI() {}
516 virtual void Initialize(ASTContext &context);
517
518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
526 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix,
528 StringRef ClassName,
529 std::string &Result);
530 virtual void RewriteObjCProtocolListMetaData(
531 const ObjCList<ObjCProtocolDecl> &Prots,
532 StringRef prefix, StringRef ClassName, std::string &Result);
533 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
534 std::string &Result);
535 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
536 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
537 std::string &Result);
538
539 // Rewriting ivar
540 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
541 std::string &Result);
542 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
543 };
Chris Lattnere99c8322007-10-11 00:43:27 +0000544}
545
Mike Stump11289f42009-09-09 15:08:12 +0000546void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000548 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000550 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
551 E = fproto->param_type_end();
552 I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000553 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000554 // All the args are checked/rewritten. Don't call twice!
555 RewriteBlockPointerDecl(D);
556 break;
557 }
558 }
559}
560
561void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000562 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000563 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000564 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000565}
566
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000567static bool IsHeaderFile(const std::string &Filename) {
568 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000569
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000570 if (DotPos == std::string::npos) {
571 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000572 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000573 }
Mike Stump11289f42009-09-09 15:08:12 +0000574
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000575 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
576 // C header: .h
577 // C++ header: .hh or .H;
578 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000579}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000580
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000581RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000582 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000583 bool silenceMacroWarn)
584 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
585 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000586 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000587 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000588 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000589 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
590 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000591 "rewriter doesn't support user-specified control flow semantics "
592 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000593}
594
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000595ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000596 raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000597 DiagnosticsEngine &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000598 const LangOptions &LOpts,
599 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000600 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000601}
Chris Lattnere99c8322007-10-11 00:43:27 +0000602
Fariborz Jahanian83077422011-12-08 18:25:15 +0000603void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000604 Context = &context;
605 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000606 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000607 MsgSendFunctionDecl = 0;
608 MsgSendSuperFunctionDecl = 0;
609 MsgSendStretFunctionDecl = 0;
610 MsgSendSuperStretFunctionDecl = 0;
611 MsgSendFpretFunctionDecl = 0;
612 GetClassFunctionDecl = 0;
613 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000614 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000615 SelGetUidFunctionDecl = 0;
616 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000617 ConstantStringClassReference = 0;
618 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000619 CurMethodDef = 0;
620 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000621 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000622 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000623 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000624 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000625 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000626 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000627 SuperConstructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000628 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000629 PropParentMap = 0;
630 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000631 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000632 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000633
Chris Lattner187f6262008-01-31 19:38:44 +0000634 // Get the ID and start/end of the main file.
635 MainFileID = SM->getMainFileID();
636 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
637 MainFileStart = MainBuf->getBufferStart();
638 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000639
David Blaikiebbafb8a2012-03-11 07:00:24 +0000640 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000641}
642
Chris Lattner3c799d72007-10-24 17:06:59 +0000643//===----------------------------------------------------------------------===//
644// Top Level Driver Code
645//===----------------------------------------------------------------------===//
646
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000647void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000648 if (Diags.hasErrorOccurred())
649 return;
650
Chris Lattner0bd1c972007-10-16 21:07:07 +0000651 // Two cases: either the decl could be in the main file, or it could be in a
652 // #included file. If the former, rewrite it now. If the later, check to see
653 // if we rewrote the #include/#import.
654 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000655 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattner0bd1c972007-10-16 21:07:07 +0000657 // If this is for a builtin, ignore it.
658 if (Loc.isInvalid()) return;
659
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000660 // Look for built-in declarations that we need to refer during the rewrite.
661 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000662 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000663 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000664 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000665 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000666 ConstantStringClassReference = FVD;
667 return;
668 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000669 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
670 if (ID->isThisDeclarationADefinition())
671 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000672 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000673 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000674 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000675 if (PD->isThisDeclarationADefinition())
676 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000677 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
678 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000679 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
680 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000681 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000682 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
683 if (!IFace->isThisDeclarationADefinition()) {
684 SmallVector<Decl *, 8> DG;
685 SourceLocation StartLoc = IFace->getLocStart();
686 do {
687 if (isa<ObjCInterfaceDecl>(*DI) &&
688 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
689 StartLoc == (*DI)->getLocStart())
690 DG.push_back(*DI);
691 else
692 break;
693
Douglas Gregordc9166c2011-12-15 20:29:51 +0000694 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000695 } while (DI != DIEnd);
696 RewriteForwardClassDecl(DG);
697 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000698 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000699 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000700
701 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
702 if (!Proto->isThisDeclarationADefinition()) {
703 SmallVector<Decl *, 8> DG;
704 SourceLocation StartLoc = Proto->getLocStart();
705 do {
706 if (isa<ObjCProtocolDecl>(*DI) &&
707 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
708 StartLoc == (*DI)->getLocStart())
709 DG.push_back(*DI);
710 else
711 break;
712
713 ++DI;
714 } while (DI != DIEnd);
715 RewriteForwardProtocolDecl(DG);
716 continue;
717 }
718 }
719
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000720 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000721 ++DI;
722 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000723 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000724 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000725 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000726 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000727}
728
Chris Lattner3c799d72007-10-24 17:06:59 +0000729//===----------------------------------------------------------------------===//
730// Syntactic (non-AST) Rewriting Code
731//===----------------------------------------------------------------------===//
732
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000733void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000734 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000735 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000736 const char *MainBufStart = MainBuf.begin();
737 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000738 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000739
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000740 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000741 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
742 if (*BufPtr == '#') {
743 if (++BufPtr == MainBufEnd)
744 return;
745 while (*BufPtr == ' ' || *BufPtr == '\t')
746 if (++BufPtr == MainBufEnd)
747 return;
748 if (!strncmp(BufPtr, "import", ImportLen)) {
749 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000750 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000751 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000752 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000753 BufPtr += ImportLen;
754 }
755 }
756 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000757}
758
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000759static std::string getIvarAccessString(ObjCIvarDecl *OID) {
760 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000761 std::string S;
762 S = "((struct ";
763 S += ClassDecl->getIdentifier()->getName();
764 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000765 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000766 return S;
767}
768
Steve Naroffc038b3a2008-12-02 17:36:43 +0000769void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
770 ObjCImplementationDecl *IMD,
771 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000772 static bool objcGetPropertyDefined = false;
773 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000774 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000775 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000776 const char *startBuf = SM->getCharacterData(startLoc);
777 assert((*startBuf == '@') && "bogus @synthesize location");
778 const char *semiBuf = strchr(startBuf, ';');
779 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000780 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000781 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000782
783 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
784 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000785
Steve Naroff9af94912008-12-02 15:48:25 +0000786 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000787 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000788 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000789
Steve Naroff003d00e2008-12-02 16:05:55 +0000790 if (!OID)
791 return;
Bill Wendling44426052012-12-20 19:22:21 +0000792 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000793 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000794 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
795 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000796 ObjCPropertyDecl::OBJC_PR_copy));
797 std::string Getr;
798 if (GenGetProperty && !objcGetPropertyDefined) {
799 objcGetPropertyDefined = true;
800 // FIXME. Is this attribute correct in all cases?
801 Getr = "\nextern \"C\" __declspec(dllimport) "
802 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000803 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000804 RewriteObjCMethodDecl(OID->getContainingInterface(),
805 PD->getGetterMethodDecl(), Getr);
806 Getr += "{ ";
807 // Synthesize an explicit cast to gain access to the ivar.
808 // See objc-act.c:objc_synthesize_new_getter() for details.
809 if (GenGetProperty) {
810 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
811 Getr += "typedef ";
812 const FunctionType *FPRetType = 0;
813 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
814 FPRetType);
815 Getr += " _TYPE";
816 if (FPRetType) {
817 Getr += ")"; // close the precedence "scope" for "*".
818
819 // Now, emit the argument types (if any).
820 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
821 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000822 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000823 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000824 std::string ParamStr =
825 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000826 Getr += ParamStr;
827 }
828 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000829 if (FT->getNumParams())
830 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000831 Getr += "...";
832 }
833 Getr += ")";
834 } else
835 Getr += "()";
836 }
837 Getr += ";\n";
838 Getr += "return (_TYPE)";
839 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000840 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000841 Getr += ", 1)";
842 }
843 else
844 Getr += "return " + getIvarAccessString(OID);
845 Getr += "; }";
846 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000847 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000848
849 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000850 return;
Mike Stump11289f42009-09-09 15:08:12 +0000851
Steve Naroff9af94912008-12-02 15:48:25 +0000852 // Generate the 'setter' function.
853 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000854 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 ObjCPropertyDecl::OBJC_PR_copy);
856 if (GenSetProperty && !objcSetPropertyDefined) {
857 objcSetPropertyDefined = true;
858 // FIXME. Is this attribute correct in all cases?
859 Setr = "\nextern \"C\" __declspec(dllimport) "
860 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
861 }
862
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000863 RewriteObjCMethodDecl(OID->getContainingInterface(),
864 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000865 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000866 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000867 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000868 if (GenSetProperty) {
869 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000870 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000871 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000872 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000873 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000874 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000875 Setr += "0, ";
876 else
877 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000878 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000879 Setr += "1)";
880 else
881 Setr += "0)";
882 }
883 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000884 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000885 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000886 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000887 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000888 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000889}
Chris Lattner16a0de42007-10-11 18:38:32 +0000890
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000891static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
892 std::string &typedefString) {
893 typedefString += "#ifndef _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "#define _REWRITER_typedef_";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += "\n";
899 typedefString += "typedef struct objc_object ";
900 typedefString += ForwardDecl->getNameAsString();
901 typedefString += ";\n#endif\n";
902}
903
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000904void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000905 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000906 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000907 const char *startBuf = SM->getCharacterData(startLoc);
908 const char *semiPtr = strchr(startBuf, ';');
909 // Replace the @class with typedefs corresponding to the classes.
910 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
911}
912
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000913void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000914 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000915 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000916 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000917 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000918 // Translate to typedef's that forward reference structs with the same name
919 // as the class. As a convenience, we include the original declaration
920 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921 typedefString += "// @class ";
922 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000923 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000924 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000925 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000926 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000927 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000928 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000929}
Mike Stump11289f42009-09-09 15:08:12 +0000930
Craig Topper5603df42013-07-05 19:34:19 +0000931void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000932 std::string typedefString;
933 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000934 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000935 if (i == 0) {
936 typedefString += "// @class ";
937 typedefString += ForwardDecl->getNameAsString();
938 typedefString += ";\n";
939 }
940 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
941 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000942 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000943}
944
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000945void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000946 // When method is a synthesized one, such as a getter/setter there is
947 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000948 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000949 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000950 SourceLocation LocStart = Method->getLocStart();
951 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000952
Chandler Carruthd48db212011-07-25 21:09:52 +0000953 if (SM->getExpansionLineNumber(LocEnd) >
954 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000955 InsertText(LocStart, "#if 0\n");
956 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000957 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000958 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000959 }
960}
961
Mike Stump11289f42009-09-09 15:08:12 +0000962void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000963 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000964
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000965 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000966 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000967}
968
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000969void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000970 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000971
Steve Naroff5448cf62007-10-30 13:30:57 +0000972 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000973 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000974
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000975 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
976 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +0000977 RewriteProperty(*I);
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000978
Mike Stump11289f42009-09-09 15:08:12 +0000979 for (ObjCCategoryDecl::instmeth_iterator
980 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000981 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000982 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000983 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000984 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000985 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000986 RewriteMethodDeclaration(*I);
987
Steve Naroff5448cf62007-10-30 13:30:57 +0000988 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000989 ReplaceText(CatDecl->getAtEndRange().getBegin(),
990 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000991}
992
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000993void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000994 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +0000995 assert(PDecl->isThisDeclarationADefinition());
996
Steve Narofff921385f2007-10-30 16:42:30 +0000997 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000999
1000 for (ObjCProtocolDecl::instmeth_iterator
1001 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001002 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001003 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001004 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001005 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001006 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001007 RewriteMethodDeclaration(*I);
1008
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001009 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1010 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001011 RewriteProperty(*I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001012
Steve Narofff921385f2007-10-30 16:42:30 +00001013 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001014 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001015 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001016
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001017 // Must comment out @optional/@required
1018 const char *startBuf = SM->getCharacterData(LocStart);
1019 const char *endBuf = SM->getCharacterData(LocEnd);
1020 for (const char *p = startBuf; p < endBuf; p++) {
1021 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001022 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001023 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001024
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001025 }
1026 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001027 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001028 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001029
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001030 }
1031 }
Steve Narofff921385f2007-10-30 16:42:30 +00001032}
1033
Douglas Gregorf6102672012-01-01 21:23:57 +00001034void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1035 SourceLocation LocStart = (*D.begin())->getLocStart();
1036 if (LocStart.isInvalid())
1037 llvm_unreachable("Invalid SourceLocation");
1038 // FIXME: handle forward protocol that are declared across multiple lines.
1039 ReplaceText(LocStart, 0, "// ");
1040}
1041
1042void
Craig Topper5603df42013-07-05 19:34:19 +00001043RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001044 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001045 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001046 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001047 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001048 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001049}
1050
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001051void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1052 const FunctionType *&FPRetType) {
1053 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001054 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001055 else if (T->isFunctionPointerType() ||
1056 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001057 // needs special handling, since pointer-to-functions have special
1058 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001059 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001060 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001061 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001062 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001064 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001065 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001066 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001067 Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001068 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001069 }
1070 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001071 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001072}
1073
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001074void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1075 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001076 std::string &ResultStr) {
1077 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1078 const FunctionType *FPRetType = 0;
1079 ResultStr += "\nstatic ";
1080 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001081 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001082
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001083 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001084 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001085
Douglas Gregorffca3a22009-01-09 17:18:27 +00001086 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001087 NameStr += "_I_";
1088 else
1089 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001090
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001091 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001092 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001093
1094 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001095 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001096 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001097 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001098 }
Mike Stump11289f42009-09-09 15:08:12 +00001099 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001100 {
1101 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001102 int len = selString.size();
1103 for (int i = 0; i < len; i++)
1104 if (selString[i] == ':')
1105 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001106 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001107 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001108 // Remember this name for metadata emission
1109 MethodInternalNames[OMD] = NameStr;
1110 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001111
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001112 // Rewrite arguments
1113 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001114
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001115 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001116 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001117 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001118 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001119 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001120 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001121 ResultStr += "struct ";
1122 }
1123 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001124 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001125 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001126 }
1127 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001128 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001129 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001130
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001131 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001132 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001133 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001134
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001135 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +00001136 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1137 E = OMD->param_end(); PI != E; ++PI) {
1138 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001139 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001140 if (PDecl->getType()->isObjCQualifiedIdType()) {
1141 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001142 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001143 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001144 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00001145 QualType QT = PDecl->getType();
1146 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001147 (void)convertBlockPointerToFunctionPointer(QT);
1148 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroffdcdcdcd2008-04-18 21:13:19 +00001149 ResultStr += Name;
1150 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001151 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +00001152 if (OMD->isVariadic())
1153 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001154 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +00001155
Steve Naroffb067bbd2008-07-16 14:40:40 +00001156 if (FPRetType) {
1157 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +00001158
Steve Naroffb067bbd2008-07-16 14:40:40 +00001159 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001160 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001161 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001162 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001163 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001164 std::string ParamStr =
1165 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroffb067bbd2008-07-16 14:40:40 +00001166 ResultStr += ParamStr;
1167 }
1168 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001169 if (FT->getNumParams())
1170 ResultStr += ", ";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001171 ResultStr += "...";
1172 }
1173 ResultStr += ")";
1174 } else {
1175 ResultStr += "()";
1176 }
1177 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001178}
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001179void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001180 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1181 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +00001182
Fariborz Jahanian02d964b2010-02-15 21:11:41 +00001183 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001184
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001185 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001186 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1187 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001188 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001189 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001190 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001191 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001192 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001193 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001194
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001195 const char *startBuf = SM->getCharacterData(LocStart);
1196 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001197 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001200 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001201 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1202 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001203 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001204 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001205 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001206 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001207 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001208 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001209
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001210 const char *startBuf = SM->getCharacterData(LocStart);
1211 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001212 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001213 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001214 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001215 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001216 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001217 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001218 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001219 }
1220
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001221 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001222}
1223
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001224void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001225 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001226 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001227 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001228 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001229 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001230 ResultStr += "\n";
1231 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001232 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001233 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001234 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001235 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001236 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001237 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001238 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001239 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001240 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001241
1242 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001243 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001244 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001245 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001246 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001247 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001248 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001249 for (ObjCInterfaceDecl::classmeth_iterator
1250 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001251 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001252 RewriteMethodDeclaration(*I);
1253
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001254 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001255 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1256 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001257}
1258
John McCallfe96e0b2011-11-06 09:01:30 +00001259Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1260 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001261
John McCallfe96e0b2011-11-06 09:01:30 +00001262 // We just magically know some things about the structure of this
1263 // expression.
1264 ObjCMessageExpr *OldMsg =
1265 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1266 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001267
John McCallfe96e0b2011-11-06 09:01:30 +00001268 // Because the rewriter doesn't allow us to rewrite rewritten code,
1269 // we need to suppress rewriting the sub-statements.
1270 Expr *Base, *RHS;
1271 {
1272 DisableReplaceStmtScope S(*this);
1273
1274 // Rebuild the base expression if we have one.
1275 Base = 0;
1276 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1277 Base = OldMsg->getInstanceReceiver();
1278 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1279 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1280 }
1281
1282 // Rebuild the RHS.
1283 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1284 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1285 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1286 }
1287
1288 // TODO: avoid this copy.
1289 SmallVector<SourceLocation, 1> SelLocs;
1290 OldMsg->getSelectorLocs(SelLocs);
1291
Chad Rosier598f3d22012-01-06 20:05:14 +00001292 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001293 switch (OldMsg->getReceiverKind()) {
1294 case ObjCMessageExpr::Class:
1295 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1296 OldMsg->getValueKind(),
1297 OldMsg->getLeftLoc(),
1298 OldMsg->getClassReceiverTypeInfo(),
1299 OldMsg->getSelector(),
1300 SelLocs,
1301 OldMsg->getMethodDecl(),
1302 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001303 OldMsg->getRightLoc(),
1304 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001305 break;
1306
1307 case ObjCMessageExpr::Instance:
1308 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1309 OldMsg->getValueKind(),
1310 OldMsg->getLeftLoc(),
1311 Base,
1312 OldMsg->getSelector(),
1313 SelLocs,
1314 OldMsg->getMethodDecl(),
1315 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001316 OldMsg->getRightLoc(),
1317 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001318 break;
1319
1320 case ObjCMessageExpr::SuperClass:
1321 case ObjCMessageExpr::SuperInstance:
1322 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1323 OldMsg->getValueKind(),
1324 OldMsg->getLeftLoc(),
1325 OldMsg->getSuperLoc(),
1326 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1327 OldMsg->getSuperType(),
1328 OldMsg->getSelector(),
1329 SelLocs,
1330 OldMsg->getMethodDecl(),
1331 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001332 OldMsg->getRightLoc(),
1333 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001334 break;
1335 }
1336
1337 Stmt *Replacement = SynthMessageExpr(NewMsg);
1338 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1339 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001340}
1341
John McCallfe96e0b2011-11-06 09:01:30 +00001342Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1343 SourceRange OldRange = PseudoOp->getSourceRange();
1344
1345 // We just magically know some things about the structure of this
1346 // expression.
1347 ObjCMessageExpr *OldMsg =
1348 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1349
1350 // Because the rewriter doesn't allow us to rewrite rewritten code,
1351 // we need to suppress rewriting the sub-statements.
1352 Expr *Base = 0;
1353 {
1354 DisableReplaceStmtScope S(*this);
1355
1356 // Rebuild the base expression if we have one.
1357 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1358 Base = OldMsg->getInstanceReceiver();
1359 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1360 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001361 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001362 }
Steve Narofff326f402008-12-03 00:56:33 +00001363
John McCallfe96e0b2011-11-06 09:01:30 +00001364 // Intentionally empty.
1365 SmallVector<SourceLocation, 1> SelLocs;
1366 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001367
Chad Rosier598f3d22012-01-06 20:05:14 +00001368 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001369 switch (OldMsg->getReceiverKind()) {
1370 case ObjCMessageExpr::Class:
1371 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1372 OldMsg->getValueKind(),
1373 OldMsg->getLeftLoc(),
1374 OldMsg->getClassReceiverTypeInfo(),
1375 OldMsg->getSelector(),
1376 SelLocs,
1377 OldMsg->getMethodDecl(),
1378 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001379 OldMsg->getRightLoc(),
1380 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001381 break;
1382
1383 case ObjCMessageExpr::Instance:
1384 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1385 OldMsg->getValueKind(),
1386 OldMsg->getLeftLoc(),
1387 Base,
1388 OldMsg->getSelector(),
1389 SelLocs,
1390 OldMsg->getMethodDecl(),
1391 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001392 OldMsg->getRightLoc(),
1393 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001394 break;
1395
1396 case ObjCMessageExpr::SuperClass:
1397 case ObjCMessageExpr::SuperInstance:
1398 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1399 OldMsg->getValueKind(),
1400 OldMsg->getLeftLoc(),
1401 OldMsg->getSuperLoc(),
1402 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1403 OldMsg->getSuperType(),
1404 OldMsg->getSelector(),
1405 SelLocs,
1406 OldMsg->getMethodDecl(),
1407 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001408 OldMsg->getRightLoc(),
1409 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001410 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001411 }
John McCallfe96e0b2011-11-06 09:01:30 +00001412
1413 Stmt *Replacement = SynthMessageExpr(NewMsg);
1414 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1415 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001416}
1417
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001418/// SynthCountByEnumWithState - To print:
1419/// ((unsigned int (*)
1420/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001421/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001422/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001423/// "countByEnumeratingWithState:objects:count:"),
1424/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001425/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001426///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001427void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001428 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1429 "id *, unsigned int))(void *)objc_msgSend)";
1430 buf += "\n\t\t";
1431 buf += "((id)l_collection,\n\t\t";
1432 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1433 buf += "\n\t\t";
1434 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001435 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001436}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001437
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001438/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1439/// statement to exit to its outer synthesized loop.
1440///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001441Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001442 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1443 return S;
1444 // replace break with goto __break_label
1445 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001446
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001447 SourceLocation startLoc = S->getLocStart();
1448 buf = "goto __break_label_";
1449 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001450 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001451
1452 return 0;
1453}
1454
1455/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1456/// statement to continue with its inner synthesized loop.
1457///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001458Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001459 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1460 return S;
1461 // replace continue with goto __continue_label
1462 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001463
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001464 SourceLocation startLoc = S->getLocStart();
1465 buf = "goto __continue_label_";
1466 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001467 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001468
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001469 return 0;
1470}
1471
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001472/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001473/// It rewrites:
1474/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001475
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001476/// Into:
1477/// {
Mike Stump11289f42009-09-09 15:08:12 +00001478/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001479/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001480/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001481/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001482/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001483/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001484/// if (limit) {
1485/// unsigned long startMutations = *enumState.mutationsPtr;
1486/// do {
1487/// unsigned long counter = 0;
1488/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001489/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001491/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001492/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001493/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001494/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001495/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001496/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001497/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001498/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001499/// }
1500/// else
1501/// elem = nil;
1502/// }
1503///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001504Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001505 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001506 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001507 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001508 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001509 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001510 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001511
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001512 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001513 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001514 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001515 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001516 std::string buf;
1517 buf = "\n{\n\t";
1518 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1519 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001520 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001521 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001522 if (ElementType->isObjCQualifiedIdType() ||
1523 ElementType->isObjCQualifiedInterfaceType())
1524 // Simply use 'id' for all qualified types.
1525 elementTypeAsString = "id";
1526 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001527 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001528 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001529 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001530 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001531 buf += elementName;
1532 buf += ";\n\t";
1533 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001534 else {
1535 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001536 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001537 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1538 if (VD->getType()->isObjCQualifiedIdType() ||
1539 VD->getType()->isObjCQualifiedInterfaceType())
1540 // Simply use 'id' for all qualified types.
1541 elementTypeAsString = "id";
1542 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001543 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001546 // struct __objcFastEnumerationState enumState = { 0 };
1547 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001548 // id __rw_items[16];
1549 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001550 // id l_collection = (id)
1551 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001552 // Find start location of 'collection' the hard way!
1553 const char *startCollectionBuf = startBuf;
1554 startCollectionBuf += 3; // skip 'for'
1555 startCollectionBuf = strchr(startCollectionBuf, '(');
1556 startCollectionBuf++; // skip '('
1557 // find 'in' and skip it.
1558 while (*startCollectionBuf != ' ' ||
1559 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1560 (*(startCollectionBuf+3) != ' ' &&
1561 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1562 startCollectionBuf++;
1563 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001564
1565 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001566 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001567 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001568 SourceLocation rightParenLoc = S->getRParenLoc();
1569 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001570 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001571 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001572
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001573 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001574 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001575 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001576 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 // ((unsigned int (*)
1578 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001579 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001580 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001581 // "countByEnumeratingWithState:objects:count:"),
1582 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001583 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001584 buf += "unsigned long limit =\n\t\t";
1585 SynthCountByEnumWithState(buf);
1586 buf += ";\n\t";
1587 /// if (limit) {
1588 /// unsigned long startMutations = *enumState.mutationsPtr;
1589 /// do {
1590 /// unsigned long counter = 0;
1591 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001592 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001593 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001594 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001595 buf += "if (limit) {\n\t";
1596 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1597 buf += "do {\n\t\t";
1598 buf += "unsigned long counter = 0;\n\t\t";
1599 buf += "do {\n\t\t\t";
1600 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1601 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1602 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001603 buf += " = (";
1604 buf += elementTypeAsString;
1605 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001606 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001607 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001608
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001609 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001610 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001611 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001612 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001613 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001614 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001615 /// }
1616 /// else
1617 /// elem = nil;
1618 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001619 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001620 buf = ";\n\t";
1621 buf += "__continue_label_";
1622 buf += utostr(ObjCBcLabelNo.back());
1623 buf += ": ;";
1624 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001625 buf += "} while (counter < limit);\n\t";
1626 buf += "} while (limit = ";
1627 SynthCountByEnumWithState(buf);
1628 buf += ");\n\t";
1629 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001630 buf += " = ((";
1631 buf += elementTypeAsString;
1632 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001633 buf += "__break_label_";
1634 buf += utostr(ObjCBcLabelNo.back());
1635 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001636 buf += "}\n\t";
1637 buf += "else\n\t\t";
1638 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001639 buf += " = ((";
1640 buf += elementTypeAsString;
1641 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001642 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001643
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001644 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001645 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001646 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001647 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001648 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001649 } else {
1650 /* Need to treat single statements specially. For example:
1651 *
1652 * for (A *a in b) if (stuff()) break;
1653 * for (A *a in b) xxxyy;
1654 *
1655 * The following code simply scans ahead to the semi to find the actual end.
1656 */
1657 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1658 const char *semiBuf = strchr(stmtBuf, ';');
1659 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001660 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001661 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001662 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001663 Stmts.pop_back();
1664 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001665 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001666}
1667
Mike Stump11289f42009-09-09 15:08:12 +00001668/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001669/// This routine rewrites @synchronized(expr) stmt;
1670/// into:
1671/// objc_sync_enter(expr);
1672/// @try stmt @finally { objc_sync_exit(expr); }
1673///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001674Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001675 // Get the start location and compute the semi location.
1676 SourceLocation startLoc = S->getLocStart();
1677 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001678
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001679 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001680
1681 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001682 buf = "objc_sync_enter((id)";
1683 const char *lparenBuf = startBuf;
1684 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001685 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001686 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1687 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001688 // been rewritten! (which implies the SourceLocation's are invalid).
1689 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001690 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001691 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001692 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001693 buf = ");\n";
1694 // declare a new scope with two variables, _stack and _rethrow.
1695 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1696 buf += "int buf[18/*32-bit i386*/];\n";
1697 buf += "char *pointers[4];} _stack;\n";
1698 buf += "id volatile _rethrow = 0;\n";
1699 buf += "objc_exception_try_enter(&_stack);\n";
1700 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001701 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001702 startLoc = S->getSynchBody()->getLocEnd();
1703 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Steve Naroffad7013b2008-08-19 13:04:19 +00001705 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001706 SourceLocation lastCurlyLoc = startLoc;
1707 buf = "}\nelse {\n";
1708 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001709 buf += "}\n";
1710 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001711 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001712
1713 std::string syncBuf;
1714 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001715
1716 Expr *syncExpr = S->getSynchExpr();
1717 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1718 ? CK_BitCast :
1719 syncExpr->getType()->isBlockPointerType()
1720 ? CK_BlockPointerToObjCPointerCast
1721 : CK_CPointerToObjCPointerCast;
1722 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1723 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001724 std::string syncExprBufS;
1725 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smith235341b2012-08-16 03:56:14 +00001726 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001727 syncBuf += syncExprBuf.str();
1728 syncBuf += ");";
1729
1730 buf += syncBuf;
1731 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001732 buf += "}\n";
1733 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001734
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001735 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001736
1737 bool hasReturns = false;
1738 HasReturnStmts(S->getSynchBody(), hasReturns);
1739 if (hasReturns)
1740 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1741
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001742 return 0;
1743}
1744
Steve Naroffec60b432009-12-05 21:43:12 +00001745void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1746{
Steve Naroff6d6da252008-12-05 17:03:39 +00001747 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001748 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001749 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001750 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001751
Steve Naroffec60b432009-12-05 21:43:12 +00001752 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001753 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001754 TryFinallyContainsReturnDiag);
1755 }
1756 return;
1757}
1758
Steve Naroffec60b432009-12-05 21:43:12 +00001759void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1760{
1761 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001762 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001763 if (*CI)
1764 HasReturnStmts(*CI, hasReturns);
1765
1766 if (isa<ReturnStmt>(S))
1767 hasReturns = true;
1768 return;
1769}
1770
1771void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1772 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001773 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001774 if (*CI) {
1775 RewriteTryReturnStmts(*CI);
1776 }
1777 if (isa<ReturnStmt>(S)) {
1778 SourceLocation startLoc = S->getLocStart();
1779 const char *startBuf = SM->getCharacterData(startLoc);
1780
1781 const char *semiBuf = strchr(startBuf, ';');
1782 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001783 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001784
1785 std::string buf;
1786 buf = "{ objc_exception_try_exit(&_stack); return";
1787
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001788 ReplaceText(startLoc, 6, buf);
1789 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001790 }
1791 return;
1792}
1793
1794void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1795 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001796 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001797 if (*CI) {
1798 RewriteSyncReturnStmts(*CI, syncExitBuf);
1799 }
1800 if (isa<ReturnStmt>(S)) {
1801 SourceLocation startLoc = S->getLocStart();
1802 const char *startBuf = SM->getCharacterData(startLoc);
1803
1804 const char *semiBuf = strchr(startBuf, ';');
1805 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001806 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001807
1808 std::string buf;
1809 buf = "{ objc_exception_try_exit(&_stack);";
1810 buf += syncExitBuf;
1811 buf += " return";
1812
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001813 ReplaceText(startLoc, 6, buf);
1814 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001815 }
1816 return;
1817}
1818
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001819Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001820 // Get the start location and compute the semi location.
1821 SourceLocation startLoc = S->getLocStart();
1822 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001823
Steve Naroffbf478ec2007-11-07 04:08:17 +00001824 assert((*startBuf == '@') && "bogus @try location");
1825
1826 std::string buf;
1827 // declare a new scope with two variables, _stack and _rethrow.
1828 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1829 buf += "int buf[18/*32-bit i386*/];\n";
1830 buf += "char *pointers[4];} _stack;\n";
1831 buf += "id volatile _rethrow = 0;\n";
1832 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001833 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001834
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001835 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001836
Steve Naroffbf478ec2007-11-07 04:08:17 +00001837 startLoc = S->getTryBody()->getLocEnd();
1838 startBuf = SM->getCharacterData(startLoc);
1839
1840 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001841
Steve Naroffbf478ec2007-11-07 04:08:17 +00001842 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001843 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001844 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001845 buf = " /* @catch begin */ else {\n";
1846 buf += " id _caught = objc_exception_extract(&_stack);\n";
1847 buf += " objc_exception_try_enter (&_stack);\n";
1848 buf += " if (_setjmp(_stack.buf))\n";
1849 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1850 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001851
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001852 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001853 } else { /* no catch list */
1854 buf = "}\nelse {\n";
1855 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1856 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001857 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001858 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001859 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001860 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1861 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001862 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001863
Douglas Gregor96c79492010-04-23 22:50:49 +00001864 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001865 buf = "if ("; // we are generating code for the first catch clause
1866 else
1867 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001868 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001869 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001870
Steve Naroffbf478ec2007-11-07 04:08:17 +00001871 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001872
Steve Naroffbf478ec2007-11-07 04:08:17 +00001873 const char *lParenLoc = strchr(startBuf, '(');
1874
Douglas Gregor96c79492010-04-23 22:50:49 +00001875 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001876 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001877 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001878 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1879 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001880 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001881 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001882 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001883
Steve Naroffedb5bc62008-02-01 20:02:07 +00001884 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001885 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001886 } else if (catchDecl) {
1887 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001888 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001889 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001890 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001891 } else if (const ObjCObjectPointerType *Ptr =
1892 t->getAs<ObjCObjectPointerType>()) {
1893 // Should be a pointer to a class.
1894 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1895 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001896 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001897 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001898 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001899 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001900 }
1901 }
1902 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001903 lastCatchBody = Catch->getCatchBody();
1904 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001905 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1906 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1907 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1908 assert((*rParenBuf == ')') && "bogus @catch paren location");
1909 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001910
Mike Stump11289f42009-09-09 15:08:12 +00001911 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001912 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001913 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001914 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001915 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001916 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001917 }
1918 // Complete the catch list...
1919 if (lastCatchBody) {
1920 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001921 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1922 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001923
Steve Naroff4adbe312008-09-11 15:29:03 +00001924 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001925 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001926 buf = "} /* last catch end */\n";
1927 buf += "else {\n";
1928 buf += " _rethrow = _caught;\n";
1929 buf += " objc_exception_try_exit(&_stack);\n";
1930 buf += "} } /* @catch end */\n";
1931 if (!S->getFinallyStmt())
1932 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001933 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001934
Steve Naroffbf478ec2007-11-07 04:08:17 +00001935 // Set lastCurlyLoc
1936 lastCurlyLoc = lastCatchBody->getLocEnd();
1937 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001938 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001939 startLoc = finalStmt->getLocStart();
1940 startBuf = SM->getCharacterData(startLoc);
1941 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001942
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001943 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001944
Steve Naroffbf478ec2007-11-07 04:08:17 +00001945 Stmt *body = finalStmt->getFinallyBody();
1946 SourceLocation startLoc = body->getLocStart();
1947 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001948 assert(*SM->getCharacterData(startLoc) == '{' &&
1949 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001950 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001951 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001952
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001953 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001954 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001955 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001956 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001957
Steve Naroffbf478ec2007-11-07 04:08:17 +00001958 // Set lastCurlyLoc
1959 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001960
Steve Naroff6d6da252008-12-05 17:03:39 +00001961 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001962 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001963 } else { /* no finally clause - make sure we synthesize an implicit one */
1964 buf = "{ /* implicit finally clause */\n";
1965 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1966 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1967 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001968 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001969
1970 // Now check for any return/continue/go statements within the @try.
1971 // The implicit finally clause won't called if the @try contains any
1972 // jump statements.
1973 bool hasReturns = false;
1974 HasReturnStmts(S->getTryBody(), hasReturns);
1975 if (hasReturns)
1976 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001977 }
1978 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001979 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001980 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001981 return 0;
1982}
1983
Mike Stump11289f42009-09-09 15:08:12 +00001984// This can't be done with ReplaceStmt(S, ThrowExpr), since
1985// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001986// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001987Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001988 // Get the start location and compute the semi location.
1989 SourceLocation startLoc = S->getLocStart();
1990 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001991
Steve Naroffa733c7f2007-11-07 15:32:26 +00001992 assert((*startBuf == '@') && "bogus @throw location");
1993
1994 std::string buf;
1995 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001996 if (S->getThrowExpr())
1997 buf = "objc_exception_throw(";
1998 else // add an implicit argument
1999 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00002000
Steve Naroff29788342008-07-25 15:41:30 +00002001 // handle "@ throw" correctly.
2002 const char *wBuf = strchr(startBuf, 'w');
2003 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002004 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00002005
Steve Naroffa733c7f2007-11-07 15:32:26 +00002006 const char *semiBuf = strchr(startBuf, ';');
2007 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002008 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002009 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002010 return 0;
2011}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002012
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002013Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002014 // Create a new string expression.
2015 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00002016 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002017 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad9a6b0982011-06-21 15:13:30 +00002018 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregorfb65e592011-07-27 05:40:30 +00002019 StringLiteral::Ascii, false,
2020 StrType, SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002021 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002022
Chris Lattner4431a1b2007-11-30 22:53:43 +00002023 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002024 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002025 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002026}
2027
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002028Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002029 if (!SelGetUidFunctionDecl)
2030 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002031 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2032 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 SmallVector<Expr*, 8> SelExprs;
Steve Naroffe4f9b232007-11-05 14:50:49 +00002034 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002035 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad9a6b0982011-06-21 15:13:30 +00002036 Exp->getSelector().getAsString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002037 StringLiteral::Ascii, false,
2038 argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002039 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2040 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002041 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002042 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002043 return SelExp;
2044}
2045
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002046CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002047 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2048 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002049 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002050 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002051
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002052 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002053 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2054 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002055
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002056 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002057 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002058 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002059 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002060 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002061
John McCall9dd450b2009-09-21 23:43:11 +00002062 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002063
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002064 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002065 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCall7decc9e2010-11-18 06:31:45 +00002066 FT->getCallResultType(*Context),
2067 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002068 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002069}
2070
Steve Naroff50d42052007-11-01 13:24:47 +00002071static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2072 const char *&startRef, const char *&endRef) {
2073 while (startBuf < endBuf) {
2074 if (*startBuf == '<')
2075 startRef = startBuf; // mark the start.
2076 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002077 if (startRef && *startRef == '<') {
2078 endRef = startBuf; // mark the end.
2079 return true;
2080 }
2081 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002082 }
2083 startBuf++;
2084 }
2085 return false;
2086}
2087
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002088static void scanToNextArgument(const char *&argRef) {
2089 int angle = 0;
2090 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2091 if (*argRef == '<')
2092 angle++;
2093 else if (*argRef == '>')
2094 angle--;
2095 argRef++;
2096 }
2097 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2098}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002099
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002100bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002101 if (T->isObjCQualifiedIdType())
2102 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002103 if (const PointerType *PT = T->getAs<PointerType>()) {
2104 if (PT->getPointeeType()->isObjCQualifiedIdType())
2105 return true;
2106 }
2107 if (T->isObjCObjectPointerType()) {
2108 T = T->getPointeeType();
2109 return T->isObjCQualifiedInterfaceType();
2110 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002111 if (T->isArrayType()) {
2112 QualType ElemTy = Context->getBaseElementType(T);
2113 return needToScanForQualifiers(ElemTy);
2114 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002115 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002116}
2117
Steve Naroff873bd842008-07-29 18:15:38 +00002118void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2119 QualType Type = E->getType();
2120 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002121 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002122
Steve Naroffdbfc6932008-11-19 21:15:47 +00002123 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2124 Loc = ECE->getLParenLoc();
2125 EndLoc = ECE->getRParenLoc();
2126 } else {
2127 Loc = E->getLocStart();
2128 EndLoc = E->getLocEnd();
2129 }
2130 // This will defend against trying to rewrite synthesized expressions.
2131 if (Loc.isInvalid() || EndLoc.isInvalid())
2132 return;
2133
Steve Naroff873bd842008-07-29 18:15:38 +00002134 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002135 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002136 const char *startRef = 0, *endRef = 0;
2137 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2138 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002139 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2140 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002141 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002142 InsertText(LessLoc, "/*");
2143 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002144 }
2145 }
2146}
2147
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002148void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002149 SourceLocation Loc;
2150 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002151 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2153 Loc = VD->getLocation();
2154 Type = VD->getType();
2155 }
2156 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2157 Loc = FD->getLocation();
2158 // Check for ObjC 'id' and class types that have been adorned with protocol
2159 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002160 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002161 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002162 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002163 if (!proto)
2164 return;
2165 Type = proto->getResultType();
2166 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002167 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2168 Loc = FD->getLocation();
2169 Type = FD->getType();
2170 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002171 else
2172 return;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002174 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002175 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002176
Steve Naroff50d42052007-11-01 13:24:47 +00002177 const char *endBuf = SM->getCharacterData(Loc);
2178 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002179 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002180 startBuf--; // scan backward (from the decl location) for return type.
2181 const char *startRef = 0, *endRef = 0;
2182 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2183 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002184 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2185 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002186 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002187 InsertText(LessLoc, "/*");
2188 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002189 }
2190 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002191 if (!proto)
2192 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002193 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002194 const char *startBuf = SM->getCharacterData(Loc);
2195 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002196 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2197 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002198 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002199
Steve Naroff50d42052007-11-01 13:24:47 +00002200 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002201 // scan forward (from the decl location) for argument types.
2202 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002203 const char *startRef = 0, *endRef = 0;
2204 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2205 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002206 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002207 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002208 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002209 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002210 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002211 InsertText(LessLoc, "/*");
2212 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002213 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002214 startBuf = ++endBuf;
2215 }
2216 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002217 // If the function name is derived from a macro expansion, then the
2218 // argument buffer will not follow the name. Need to speak with Chris.
2219 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002220 startBuf++; // scan forward (from the decl location) for argument types.
2221 startBuf++;
2222 }
Steve Naroff50d42052007-11-01 13:24:47 +00002223 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002224}
2225
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002226void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2227 QualType QT = ND->getType();
2228 const Type* TypePtr = QT->getAs<Type>();
2229 if (!isa<TypeOfExprType>(TypePtr))
2230 return;
2231 while (isa<TypeOfExprType>(TypePtr)) {
2232 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2233 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2234 TypePtr = QT->getAs<Type>();
2235 }
2236 // FIXME. This will not work for multiple declarators; as in:
2237 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002238 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002239 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2240 const char *startBuf = SM->getCharacterData(DeclLoc);
2241 if (ND->getInit()) {
2242 std::string Name(ND->getNameAsString());
2243 TypeAsString += " " + Name + " = ";
2244 Expr *E = ND->getInit();
2245 SourceLocation startLoc;
2246 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2247 startLoc = ECE->getLParenLoc();
2248 else
2249 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002250 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002251 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002252 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002253 }
2254 else {
2255 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002256 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002257 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002258 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002259 }
2260}
2261
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002262// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002263void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002264 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002265 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002266 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002267 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002268 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002269 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002270 SourceLocation(),
2271 SourceLocation(),
2272 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002273 SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002274}
2275
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002276void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002277 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002278 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002279 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002280 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002281 return;
2282 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002283 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002284}
2285
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002286void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002287 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002288 const char *argPtr = TypeString.c_str();
2289 if (!strchr(argPtr, '^')) {
2290 Str += TypeString;
2291 return;
2292 }
2293 while (*argPtr) {
2294 Str += (*argPtr == '^' ? '*' : *argPtr);
2295 argPtr++;
2296 }
2297}
2298
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002299// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002300void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2301 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002302 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002303 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002304 const char *argPtr = TypeString.c_str();
2305 int paren = 0;
2306 while (*argPtr) {
2307 switch (*argPtr) {
2308 case '(':
2309 Str += *argPtr;
2310 paren++;
2311 break;
2312 case ')':
2313 Str += *argPtr;
2314 paren--;
2315 break;
2316 case '^':
2317 Str += '*';
2318 if (paren == 1)
2319 Str += VD->getNameAsString();
2320 break;
2321 default:
2322 Str += *argPtr;
2323 break;
2324 }
2325 argPtr++;
2326 }
2327}
2328
2329
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002330void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2331 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2332 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2333 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2334 if (!proto)
2335 return;
2336 QualType Type = proto->getResultType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002337 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002338 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002339 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002340 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002341 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002342 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002343 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002344 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002345 if (i+1 < numArgs)
2346 FdStr += ", ";
2347 }
2348 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002349 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002350 CurFunctionDeclToDeclareForBlock = 0;
2351}
2352
Benjamin Kramer60509af2013-09-09 14:48:42 +00002353// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2354void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2355 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002356 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002357 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002358 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002359 QualType argT = Context->getObjCIdType();
2360 assert(!argT.isNull() && "Can't find 'id' type");
2361 ArgTys.push_back(argT);
2362 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002363 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002364 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002365 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002366 SourceLocation(),
2367 SourceLocation(),
2368 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002369 0, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002370}
2371
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002372// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002373void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002374 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002375 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002376 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'id' type");
2378 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002379 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002380 assert(!argT.isNull() && "Can't find 'SEL' type");
2381 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002382 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002383 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002384 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002385 SourceLocation(),
2386 SourceLocation(),
2387 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002388 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002389}
2390
Steve Naroff7fa2f042007-11-15 10:28:18 +00002391// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002392void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002393 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002394 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002395 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002396 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002397 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002398 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2399 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2400 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002401 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002402 assert(!argT.isNull() && "Can't find 'SEL' type");
2403 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002404 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002405 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002406 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002407 SourceLocation(),
2408 SourceLocation(),
2409 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002410 SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002411}
2412
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002413// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002414void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002415 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002417 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002418 assert(!argT.isNull() && "Can't find 'id' type");
2419 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002420 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002421 assert(!argT.isNull() && "Can't find 'SEL' type");
2422 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002423 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002424 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002425 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002426 SourceLocation(),
2427 SourceLocation(),
2428 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002429 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002430}
2431
Mike Stump11289f42009-09-09 15:08:12 +00002432// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002433// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002434void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002435 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002436 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002437 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002438 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002439 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002440 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002441 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2442 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2443 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002444 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002445 assert(!argT.isNull() && "Can't find 'SEL' type");
2446 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002447 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002448 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002449 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002450 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002451 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002452 msgSendIdent,
2453 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002454 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002455}
2456
Steve Naroff2e4e3852008-05-08 22:02:18 +00002457// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002458void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002460 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002461 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002464 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002467 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002469 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
2472 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002473 SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002474}
2475
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002476// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002477void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002478 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002479 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002480 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002481 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002482 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002483 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002484 SourceLocation(),
2485 SourceLocation(),
2486 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002487 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002488}
2489
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002490// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2491void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2492 IdentifierInfo *getSuperClassIdent =
2493 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002494 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002495 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002496 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002497 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002498 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002499 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002500 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002501 getSuperClassIdent,
2502 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002503 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002504}
2505
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002506// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002507void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002508 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002509 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002510 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002511 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002512 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002513 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002514 SourceLocation(),
2515 SourceLocation(),
2516 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002517 0, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002518}
2519
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002520Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002521 QualType strType = getConstantStringStructType();
2522
2523 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002524
2525 std::string tmpName = InFileName;
2526 unsigned i;
2527 for (i=0; i < tmpName.length(); i++) {
2528 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002529 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002530 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002531 tmpName[i] = '_';
2532 }
2533 S += tmpName;
2534 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002535 S += utostr(NumObjCStringLiterals++);
2536
Steve Naroff00a31762008-03-27 22:29:16 +00002537 Preamble += "static __NSConstantStringImpl " + S;
2538 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2539 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002540 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002541 std::string prettyBufS;
2542 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002543 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002544 Preamble += prettyBuf.str();
2545 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002546 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002547
2548 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002549 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002550 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002551 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002552 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002553 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002554 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002555 VK_RValue, OK_Ordinary,
2556 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002557 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002558 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002559 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002560 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002561 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002562 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002563}
2564
Steve Naroff7fa2f042007-11-15 10:28:18 +00002565// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002566QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002567 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002568 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002569 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002570 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002571 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002572
Steve Naroff7fa2f042007-11-15 10:28:18 +00002573 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002574 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002575 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002576 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002577
Steve Naroff7fa2f042007-11-15 10:28:18 +00002578 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002579 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002580 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002581 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002582 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002583 FieldTypes[i], 0,
2584 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002585 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002586 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002587 }
Mike Stump11289f42009-09-09 15:08:12 +00002588
Douglas Gregord5058122010-02-11 01:19:42 +00002589 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002590 }
2591 return Context->getTagDeclType(SuperStructDecl);
2592}
2593
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002594QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002595 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002596 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002597 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002598 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002599 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002600
Steve Naroffce8e8862008-03-15 00:55:56 +00002601 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002602 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002603 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002604 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002605 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002606 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002607 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002608 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002609
Steve Naroffce8e8862008-03-15 00:55:56 +00002610 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002611 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002612 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2613 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002614 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00002615 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002616 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002617 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002618 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002619 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002620 }
2621
Douglas Gregord5058122010-02-11 01:19:42 +00002622 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002623 }
2624 return Context->getTagDeclType(ConstantStringDecl);
2625}
2626
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002627CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2628 QualType msgSendType,
2629 QualType returnType,
2630 SmallVectorImpl<QualType> &ArgTypes,
2631 SmallVectorImpl<Expr*> &MsgExprs,
2632 ObjCMethodDecl *Method) {
2633 // Create a reference to the objc_msgSend_stret() declaration.
2634 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2635 false, msgSendType,
2636 VK_LValue, SourceLocation());
2637 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2638 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2639 Context->getPointerType(Context->VoidTy),
2640 CK_BitCast, STDRE);
2641 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002642 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2643 Method ? Method->isVariadic()
2644 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002645 castType = Context->getPointerType(castType);
2646 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2647 cast);
2648
2649 // Don't forget the parens to enforce the proper binding.
2650 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2651
2652 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00002653 CallExpr *STCE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002654 FT->getResultType(), VK_RValue,
2655 SourceLocation());
2656 return STCE;
2657
2658}
2659
2660
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002661Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2662 SourceLocation StartLoc,
2663 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002664 if (!SelGetUidFunctionDecl)
2665 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002666 if (!MsgSendFunctionDecl)
2667 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002668 if (!MsgSendSuperFunctionDecl)
2669 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002670 if (!MsgSendStretFunctionDecl)
2671 SynthMsgSendStretFunctionDecl();
2672 if (!MsgSendSuperStretFunctionDecl)
2673 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002674 if (!MsgSendFpretFunctionDecl)
2675 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002676 if (!GetClassFunctionDecl)
2677 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002678 if (!GetSuperClassFunctionDecl)
2679 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002680 if (!GetMetaClassFunctionDecl)
2681 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002682
Steve Naroff7fa2f042007-11-15 10:28:18 +00002683 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002684 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2685 // May need to use objc_msgSend_stret() as well.
2686 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002687 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2688 QualType resultType = mDecl->getResultType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002689 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002690 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002691 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002692 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002693 }
Mike Stump11289f42009-09-09 15:08:12 +00002694
Steve Naroff574440f2007-10-24 22:48:43 +00002695 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002696 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002697 switch (Exp->getReceiverKind()) {
2698 case ObjCMessageExpr::SuperClass: {
2699 MsgSendFlavor = MsgSendSuperFunctionDecl;
2700 if (MsgSendStretFlavor)
2701 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2702 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002703
Douglas Gregor9a129192010-04-21 00:45:42 +00002704 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002706 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002707
Douglas Gregor9a129192010-04-21 00:45:42 +00002708 // set the receiver to self, the first argument to all methods.
2709 InitExprs.push_back(
2710 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002711 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002712 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002713 false,
John McCall7decc9e2010-11-18 06:31:45 +00002714 Context->getObjCIdType(),
2715 VK_RValue,
2716 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002717 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002718
Douglas Gregor9a129192010-04-21 00:45:42 +00002719 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002720 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002721 QualType argType = Context->getPointerType(Context->CharTy);
2722 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad9a6b0982011-06-21 15:13:30 +00002723 ClassDecl->getIdentifier()->getName(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002724 StringLiteral::Ascii, false,
2725 argType, SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002726 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2727 &ClsExprs[0],
2728 ClsExprs.size(),
2729 StartLoc,
2730 EndLoc);
2731 // (Class)objc_getClass("CurrentClass")
2732 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2733 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002734 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002735 ClsExprs.clear();
2736 ClsExprs.push_back(ArgExpr);
2737 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2738 &ClsExprs[0], ClsExprs.size(),
2739 StartLoc, EndLoc);
2740
2741 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2742 // To turn off a warning, type-cast to 'id'
2743 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2744 NoTypeInfoCStyleCastExpr(Context,
2745 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002746 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002747 // struct objc_super
2748 QualType superType = getSuperStructType();
2749 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002750
Francois Pichet0706d202011-09-17 17:15:52 +00002751 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002752 SynthSuperConstructorFunctionDecl();
2753 // Simulate a constructor call...
2754 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002755 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002756 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002757 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002758 superType, VK_LValue,
2759 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002760 // The code for super is a little tricky to prevent collision with
2761 // the structure definition in the header. The rewriter has it's own
2762 // internal definition (__rw_objc_super) that is uses. This is why
2763 // we need the cast below. For example:
2764 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2765 //
John McCalle3027922010-08-25 11:45:40 +00002766 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002767 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002768 VK_RValue, OK_Ordinary,
2769 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002770 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2771 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002772 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002773 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002774 // (struct objc_super) { <exprs from above> }
2775 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002776 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002777 SourceLocation());
2778 TypeSourceInfo *superTInfo
2779 = Context->getTrivialTypeSourceInfo(superType);
2780 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002781 superType, VK_LValue,
2782 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002783 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002784 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002785 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002786 VK_RValue, OK_Ordinary,
2787 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002788 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002789 MsgExprs.push_back(SuperRep);
2790 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002791 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002792
2793 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002795 QualType argType = Context->getPointerType(Context->CharTy);
2796 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002797 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002798 IdentifierInfo *clsName = Class->getIdentifier();
2799 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad9a6b0982011-06-21 15:13:30 +00002800 clsName->getName(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002801 StringLiteral::Ascii, false,
Anders Carlsson75245402011-04-14 00:40:03 +00002802 argType, SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002803 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2804 &ClsExprs[0],
2805 ClsExprs.size(),
2806 StartLoc, EndLoc);
2807 MsgExprs.push_back(Cls);
2808 break;
2809 }
2810
2811 case ObjCMessageExpr::SuperInstance:{
2812 MsgSendFlavor = MsgSendSuperFunctionDecl;
2813 if (MsgSendStretFlavor)
2814 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2815 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2816 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002817 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002818
2819 InitExprs.push_back(
2820 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002821 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002822 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002823 false,
John McCall7decc9e2010-11-18 06:31:45 +00002824 Context->getObjCIdType(),
2825 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002826 ); // set the 'receiver'.
2827
2828 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002829 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002830 QualType argType = Context->getPointerType(Context->CharTy);
2831 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad9a6b0982011-06-21 15:13:30 +00002832 ClassDecl->getIdentifier()->getName(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002833 StringLiteral::Ascii, false, argType,
2834 SourceLocation()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002835 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2836 &ClsExprs[0],
2837 ClsExprs.size(),
2838 StartLoc, EndLoc);
2839 // (Class)objc_getClass("CurrentClass")
2840 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2841 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002842 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002843 ClsExprs.clear();
2844 ClsExprs.push_back(ArgExpr);
2845 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2846 &ClsExprs[0], ClsExprs.size(),
2847 StartLoc, EndLoc);
2848
2849 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2850 // To turn off a warning, type-cast to 'id'
2851 InitExprs.push_back(
2852 // set 'super class', using class_getSuperclass().
2853 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002854 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002855 // struct objc_super
2856 QualType superType = getSuperStructType();
2857 Expr *SuperRep;
2858
Francois Pichet0706d202011-09-17 17:15:52 +00002859 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002860 SynthSuperConstructorFunctionDecl();
2861 // Simulate a constructor call...
2862 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002863 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002864 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002865 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002866 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002867 // The code for super is a little tricky to prevent collision with
2868 // the structure definition in the header. The rewriter has it's own
2869 // internal definition (__rw_objc_super) that is uses. This is why
2870 // we need the cast below. For example:
2871 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2872 //
John McCalle3027922010-08-25 11:45:40 +00002873 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002874 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002875 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002876 SourceLocation());
2877 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2878 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002879 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002880 } else {
2881 // (struct objc_super) { <exprs from above> }
2882 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002883 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002884 SourceLocation());
2885 TypeSourceInfo *superTInfo
2886 = Context->getTrivialTypeSourceInfo(superType);
2887 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002888 superType, VK_RValue, ILE,
2889 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002890 }
2891 MsgExprs.push_back(SuperRep);
2892 break;
2893 }
2894
2895 case ObjCMessageExpr::Instance: {
2896 // Remove all type-casts because it may contain objc-style types; e.g.
2897 // Foo<Proto> *.
2898 Expr *recExpr = Exp->getInstanceReceiver();
2899 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2900 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002901 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2902 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2903 ? CK_BlockPointerToObjCPointerCast
2904 : CK_CPointerToObjCPointerCast;
2905
Douglas Gregor9a129192010-04-21 00:45:42 +00002906 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002907 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002908 MsgExprs.push_back(recExpr);
2909 break;
2910 }
2911 }
2912
Steve Naroffa397efd2007-11-03 11:27:19 +00002913 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002914 SmallVector<Expr*, 8> SelExprs;
Steve Naroff574440f2007-10-24 22:48:43 +00002915 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002916 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad9a6b0982011-06-21 15:13:30 +00002917 Exp->getSelector().getAsString(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002918 StringLiteral::Ascii, false,
2919 argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002920 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002921 &SelExprs[0], SelExprs.size(),
2922 StartLoc,
2923 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002924 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002925
Steve Naroff574440f2007-10-24 22:48:43 +00002926 // Now push any user supplied arguments.
2927 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002928 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002929 // Make all implicit casts explicit...ICE comes in handy:-)
2930 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2931 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002932 QualType type = ICE->getType();
2933 if (needToScanForQualifiers(type))
2934 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002935 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002936 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002937 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002938 CastKind CK;
2939 if (SubExpr->getType()->isIntegralType(*Context) &&
2940 type->isBooleanType()) {
2941 CK = CK_IntegralToBoolean;
2942 } else if (type->isObjCObjectPointerType()) {
2943 if (SubExpr->getType()->isBlockPointerType()) {
2944 CK = CK_BlockPointerToObjCPointerCast;
2945 } else if (SubExpr->getType()->isPointerType()) {
2946 CK = CK_CPointerToObjCPointerCast;
2947 } else {
2948 CK = CK_BitCast;
2949 }
2950 } else {
2951 CK = CK_BitCast;
2952 }
2953
2954 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002955 }
2956 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002957 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002958 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002959 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002960 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002961 CastKind CK;
2962 if (userExpr->getType()->isIntegralType(*Context)) {
2963 CK = CK_IntegralToPointer;
2964 } else if (userExpr->getType()->isBlockPointerType()) {
2965 CK = CK_BlockPointerToObjCPointerCast;
2966 } else if (userExpr->getType()->isPointerType()) {
2967 CK = CK_CPointerToObjCPointerCast;
2968 } else {
2969 CK = CK_BitCast;
2970 }
John McCall97513962010-01-15 18:39:57 +00002971 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002972 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002973 }
Mike Stump11289f42009-09-09 15:08:12 +00002974 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002975 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002976 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2977 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002978 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002979 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002980 }
Steve Narofff36987c2007-11-04 22:37:50 +00002981 // Generate the funky cast.
2982 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002983 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002984 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002985
Steve Narofff36987c2007-11-04 22:37:50 +00002986 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002987 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2988 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2989 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002990 ArgTypes.push_back(Context->getObjCIdType());
2991 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002992 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002993 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002994 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2995 E = OMD->param_end(); PI != E; ++PI) {
2996 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002997 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002998 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002999 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003000 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00003001 ArgTypes.push_back(t);
3002 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00003003 returnType = Exp->getType();
3004 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003005 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00003006 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003007 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00003008 }
3009 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00003010 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003011
Steve Narofff36987c2007-11-04 22:37:50 +00003012 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003013 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00003014 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00003015
Mike Stump11289f42009-09-09 15:08:12 +00003016 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00003017 // If we don't do this cast, we get the following bizarre warning/note:
3018 // xx.m:13: warning: function called through a non-compatible type
3019 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00003020 cast = NoTypeInfoCStyleCastExpr(Context,
3021 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00003022 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00003023
Steve Narofff36987c2007-11-04 22:37:50 +00003024 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003025 // If we don't have a method decl, force a variadic cast.
3026 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00003027 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003028 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00003029 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00003030 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003031 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003032
3033 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003034 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003035
John McCall9dd450b2009-09-21 23:43:11 +00003036 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramerc215e762012-08-24 11:54:20 +00003037 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003038 FT->getResultType(), VK_RValue,
3039 EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003040 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003041 if (MsgSendStretFlavor) {
3042 // We have the method which returns a struct/union. Must also generate
3043 // call to objc_msgSend_stret and hang both varieties on a conditional
3044 // expression which dictate which one to envoke depending on size of
3045 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00003046
3047 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3048 msgSendType, returnType,
3049 ArgTypes, MsgExprs,
3050 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003051
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003052 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003053 UnaryExprOrTypeTraitExpr *sizeofExpr =
3054 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3055 Context->getTrivialTypeSourceInfo(returnType),
3056 Context->getSizeType(), SourceLocation(),
3057 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003058 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3059 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3060 // For X86 it is more complicated and some kind of target specific routine
3061 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003062 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003063 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003064 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3065 llvm::APInt(IntSize, 8),
3066 Context->IntTy,
3067 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003068 BinaryOperator *lessThanExpr =
3069 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003070 VK_RValue, OK_Ordinary, SourceLocation(),
3071 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003072 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003073 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003074 new (Context) ConditionalOperator(lessThanExpr,
3075 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003076 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003077 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003078 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3079 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003080 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003081 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003082 return ReplacingStmt;
3083}
3084
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003085Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003086 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3087 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003088
Steve Naroff574440f2007-10-24 22:48:43 +00003089 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003090 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003091
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003092 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003093 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003094}
3095
Steve Naroffd9803712009-04-29 16:37:50 +00003096// typedef struct objc_object Protocol;
3097QualType RewriteObjC::getProtocolType() {
3098 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003099 TypeSourceInfo *TInfo
3100 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003101 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003102 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003103 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003104 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003105 }
3106 return Context->getTypeDeclType(ProtocolTypeDecl);
3107}
3108
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003109/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003110/// a synthesized/forward data reference (to the protocol's metadata).
3111/// The forward references (and metadata) are generated in
3112/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003113Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003114 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3115 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003116 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003117 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003118 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003119 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3120 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003121 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003122 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003123 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003124 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003125 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003126 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003127 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003128 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003129 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003130 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003131
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003132}
3133
Mike Stump11289f42009-09-09 15:08:12 +00003134bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003135 const char *endBuf) {
3136 while (startBuf < endBuf) {
3137 if (*startBuf == '#') {
3138 // Skip whitespace.
3139 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3140 ;
3141 if (!strncmp(startBuf, "if", strlen("if")) ||
3142 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3143 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3144 !strncmp(startBuf, "define", strlen("define")) ||
3145 !strncmp(startBuf, "undef", strlen("undef")) ||
3146 !strncmp(startBuf, "else", strlen("else")) ||
3147 !strncmp(startBuf, "elif", strlen("elif")) ||
3148 !strncmp(startBuf, "endif", strlen("endif")) ||
3149 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3150 !strncmp(startBuf, "include", strlen("include")) ||
3151 !strncmp(startBuf, "import", strlen("import")) ||
3152 !strncmp(startBuf, "include_next", strlen("include_next")))
3153 return true;
3154 }
3155 startBuf++;
3156 }
3157 return false;
3158}
3159
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003160/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003161/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003162void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003163 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003164 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003165 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003166 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003167 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003168 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003169 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003170 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003171 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003172 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003173 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003174
Steve Naroffdde78982007-11-14 19:25:57 +00003175 const char *startBuf = SM->getCharacterData(LocStart);
3176 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003177
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003178 // If no ivars and no root or if its root, directly or indirectly,
3179 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003180 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003181 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003182 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003183 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003184 return;
3185 }
Mike Stump11289f42009-09-09 15:08:12 +00003186
3187 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003188 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003189 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003190 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003191 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003192 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003193
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003194 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003195 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003196 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003197 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003198 // If the buffer contains preprocessor directives, we do more fine-grained
3199 // rewrites. This is intended to fix code that looks like (which occurs in
3200 // NSURL.h, for example):
3201 //
3202 // #ifdef XYZ
3203 // @interface Foo : NSObject
3204 // #else
3205 // @interface FooBar : NSObject
3206 // #endif
3207 // {
3208 // int i;
3209 // }
3210 // @end
3211 //
3212 // This clause is segregated to avoid breaking the common case.
3213 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003214 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003215 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003216 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003217 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003218
Chris Lattnerf5b77512009-02-20 18:18:36 +00003219 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003220 // advance to the end of the referenced protocols.
3221 while (endHeader < cursor && *endHeader != '>') endHeader++;
3222 endHeader++;
3223 }
3224 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003225 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003226 } else {
3227 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003228 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003229 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003230 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003231 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003232 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003233 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003235 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003236
Steve Naroffdde78982007-11-14 19:25:57 +00003237 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003238 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003239 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003240 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003241 }
3242 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003243
Steve Naroffdde78982007-11-14 19:25:57 +00003244 // Now comment out any visibility specifiers.
3245 while (cursor < endBuf) {
3246 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003247 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003248 // Skip whitespace.
3249 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3250 /*scan*/;
3251
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003252 // FIXME: presence of @public, etc. inside comment results in
3253 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003254 if (!strncmp(cursor, "public", strlen("public")) ||
3255 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003256 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003257 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003258 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003259 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003260 // FIXME: If there are cases where '<' is used in ivar declaration part
3261 // of user code, then scan the ivar list and use needToScanForQualifiers
3262 // for type checking.
3263 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003264 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003265 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003266 cursor = strchr(cursor, '>');
3267 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003268 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003269 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003270 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003271 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003272 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003273 }
Steve Naroffdde78982007-11-14 19:25:57 +00003274 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003275 }
Steve Naroffdde78982007-11-14 19:25:57 +00003276 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003277 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003278 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003279 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003280 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003281 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003282 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003283 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003284 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003285 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003286 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003287 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003288 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikie83d382b2011-09-23 05:06:16 +00003289 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003290}
3291
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003292//===----------------------------------------------------------------------===//
3293// Meta Data Emission
3294//===----------------------------------------------------------------------===//
3295
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003296
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003297/// RewriteImplementations - This routine rewrites all method implementations
3298/// and emits meta-data.
3299
Steve Narofff8cfd162008-11-13 20:07:04 +00003300void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003301 int ClsDefCount = ClassImplementation.size();
3302 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003303
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003304 // Rewrite implemented methods
3305 for (int i = 0; i < ClsDefCount; i++)
3306 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003307
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003308 for (int i = 0; i < CatDefCount; i++)
3309 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003310}
Mike Stump11289f42009-09-09 15:08:12 +00003311
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003312void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3313 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003314 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003315 assert(BlockByRefDeclNo.count(VD) &&
3316 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003317 if (def)
3318 ResultStr += "struct ";
3319 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003320 "_" + utostr(BlockByRefDeclNo[VD]) ;
3321}
3322
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003323static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3324 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3325 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3326 return false;
3327}
3328
Steve Naroff677ab3a2008-10-27 17:20:55 +00003329std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003330 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003331 std::string Tag) {
3332 const FunctionType *AFT = CE->getFunctionType();
3333 QualType RT = AFT->getResultType();
3334 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003335 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003336 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003337
Steve Naroff677ab3a2008-10-27 17:20:55 +00003338 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003340 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003341 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003342 // block (to reference imported block decl refs).
3343 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003344 } else if (BD->param_empty()) {
3345 S += "(" + StructRef + " *__cself)";
3346 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003347 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003348 assert(FT && "SynthesizeBlockFunc: No function proto");
3349 S += '(';
3350 // first add the implicit argument.
3351 S += StructRef + " *__cself, ";
3352 std::string ParamStr;
3353 for (BlockDecl::param_iterator AI = BD->param_begin(),
3354 E = BD->param_end(); AI != E; ++AI) {
3355 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003356 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003357 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003358 (void)convertBlockPointerToFunctionPointer(QT);
3359 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003360 S += ParamStr;
3361 }
3362 if (FT->isVariadic()) {
3363 if (!BD->param_empty()) S += ", ";
3364 S += "...";
3365 }
3366 S += ')';
3367 }
3368 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003369
Steve Naroff677ab3a2008-10-27 17:20:55 +00003370 // Create local declarations to avoid rewriting all closure decl ref exprs.
3371 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003372 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003373 E = BlockByRefDecls.end(); I != E; ++I) {
3374 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003375 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003376 std::string TypeString;
3377 RewriteByRefString(TypeString, Name, (*I));
3378 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003379 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003380 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003381 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003382 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003383 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003384 E = BlockByCopyDecls.end(); I != E; ++I) {
3385 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003386 // Handle nested closure invocation. For example:
3387 //
3388 // void (^myImportedClosure)(void);
3389 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003390 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003391 // void (^anotherClosure)(void);
3392 // anotherClosure = ^(void) {
3393 // myImportedClosure(); // import and invoke the closure
3394 // };
3395 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003396 if (isTopLevelBlockPointerType((*I)->getType())) {
3397 RewriteBlockPointerTypeVariable(S, (*I));
3398 S += " = (";
3399 RewriteBlockPointerType(S, (*I)->getType());
3400 S += ")";
3401 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3402 }
3403 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003404 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003405 QualType QT = (*I)->getType();
3406 if (HasLocalVariableExternalStorage(*I))
3407 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003408 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003409 S += Name + " = __cself->" +
3410 (*I)->getNameAsString() + "; // bound by copy\n";
3411 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003412 }
3413 std::string RewrittenStr = RewrittenBlockExprs[CE];
3414 const char *cstr = RewrittenStr.c_str();
3415 while (*cstr++ != '{') ;
3416 S += cstr;
3417 S += "\n";
3418 return S;
3419}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003420
Steve Naroff677ab3a2008-10-27 17:20:55 +00003421std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003422 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003423 std::string Tag) {
3424 std::string StructRef = "struct " + Tag;
3425 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003426
Steve Naroff677ab3a2008-10-27 17:20:55 +00003427 S += funcName;
3428 S += "_block_copy_" + utostr(i);
3429 S += "(" + StructRef;
3430 S += "*dst, " + StructRef;
3431 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003432 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003433 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003434 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003435 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003436 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003437 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003438 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003439 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003440 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003441 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003442 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003443 else
3444 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003445 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003446 S += "}\n";
3447
Steve Naroff677ab3a2008-10-27 17:20:55 +00003448 S += "\nstatic void __";
3449 S += funcName;
3450 S += "_block_dispose_" + utostr(i);
3451 S += "(" + StructRef;
3452 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003453 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003454 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003455 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003456 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003457 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003458 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003459 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003460 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003461 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003462 else
3463 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003466 return S;
3467}
3468
Steve Naroff30484702009-12-06 21:14:13 +00003469std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3470 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003471 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003472 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003473
Steve Naroff677ab3a2008-10-27 17:20:55 +00003474 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003475 S += " struct " + Desc;
3476 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003477
Steve Naroff30484702009-12-06 21:14:13 +00003478 Constructor += "(void *fp, "; // Invoke function pointer.
3479 Constructor += "struct " + Desc; // Descriptor pointer.
3480 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003481
Steve Naroff677ab3a2008-10-27 17:20:55 +00003482 if (BlockDeclRefs.size()) {
3483 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003484 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003485 E = BlockByCopyDecls.end(); I != E; ++I) {
3486 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003487 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003488 std::string ArgName = "_" + FieldName;
3489 // Handle nested closure invocation. For example:
3490 //
3491 // void (^myImportedBlock)(void);
3492 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003493 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003494 // void (^anotherBlock)(void);
3495 // anotherBlock = ^(void) {
3496 // myImportedBlock(); // import and invoke the closure
3497 // };
3498 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003499 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003500 S += "struct __block_impl *";
3501 Constructor += ", void *" + ArgName;
3502 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003503 QualType QT = (*I)->getType();
3504 if (HasLocalVariableExternalStorage(*I))
3505 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003506 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3507 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003508 Constructor += ", " + ArgName;
3509 }
3510 S += FieldName + ";\n";
3511 }
3512 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003513 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003514 E = BlockByRefDecls.end(); I != E; ++I) {
3515 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003516 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003517 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003518 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003519 std::string TypeString;
3520 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003521 TypeString += " *";
3522 FieldName = TypeString + FieldName;
3523 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003524 Constructor += ", " + ArgName;
3525 }
3526 S += FieldName + "; // by ref\n";
3527 }
3528 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003529 Constructor += ", int flags=0)";
3530 // Initialize all "by copy" arguments.
3531 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003532 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003533 E = BlockByCopyDecls.end(); I != E; ++I) {
3534 std::string Name = (*I)->getNameAsString();
3535 if (firsTime) {
3536 Constructor += " : ";
3537 firsTime = false;
3538 }
3539 else
3540 Constructor += ", ";
3541 if (isTopLevelBlockPointerType((*I)->getType()))
3542 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3543 else
3544 Constructor += Name + "(_" + Name + ")";
3545 }
3546 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003547 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003548 E = BlockByRefDecls.end(); I != E; ++I) {
3549 std::string Name = (*I)->getNameAsString();
3550 if (firsTime) {
3551 Constructor += " : ";
3552 firsTime = false;
3553 }
3554 else
3555 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003556 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003557 }
3558
3559 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003560 if (GlobalVarDecl)
3561 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3562 else
3563 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003564 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003565
Steve Naroff30484702009-12-06 21:14:13 +00003566 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003567 } else {
3568 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003569 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003570 if (GlobalVarDecl)
3571 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3572 else
3573 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003574 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3575 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003576 }
3577 Constructor += " ";
3578 Constructor += "}\n";
3579 S += Constructor;
3580 S += "};\n";
3581 return S;
3582}
3583
Steve Naroff30484702009-12-06 21:14:13 +00003584std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3585 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003586 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003587 unsigned hasCopy) {
3588 std::string S = "\nstatic struct " + DescTag;
3589
3590 S += " {\n unsigned long reserved;\n";
3591 S += " unsigned long Block_size;\n";
3592 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003593 S += " void (*copy)(struct ";
3594 S += ImplTag; S += "*, struct ";
3595 S += ImplTag; S += "*);\n";
3596
3597 S += " void (*dispose)(struct ";
3598 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003599 }
3600 S += "} ";
3601
3602 S += DescTag + "_DATA = { 0, sizeof(struct ";
3603 S += ImplTag + ")";
3604 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003605 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3606 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003607 }
3608 S += "};\n";
3609 return S;
3610}
3611
Steve Naroff677ab3a2008-10-27 17:20:55 +00003612void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003613 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003614 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003615 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003616 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003617 bool RewriteSC = (GlobalVarDecl &&
3618 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003619 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003620 GlobalVarDecl->getType().getCVRQualifiers());
3621 if (RewriteSC) {
3622 std::string SC(" void __");
3623 SC += GlobalVarDecl->getNameAsString();
3624 SC += "() {}";
3625 InsertText(FunLocStart, SC);
3626 }
3627
Steve Naroff677ab3a2008-10-27 17:20:55 +00003628 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003629 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3630 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003631 // Need to copy-in the inner copied-in variables not actually used in this
3632 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003633 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003634 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003635 ValueDecl *VD = Exp->getDecl();
3636 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003637 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003638 BlockByCopyDeclsPtrSet.insert(VD);
3639 BlockByCopyDecls.push_back(VD);
3640 }
John McCall113bee02012-03-10 09:33:50 +00003641 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003642 BlockByRefDeclsPtrSet.insert(VD);
3643 BlockByRefDecls.push_back(VD);
3644 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003645 // imported objects in the inner blocks not used in the outer
3646 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003647 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003648 VD->getType()->isObjCObjectPointerType() ||
3649 VD->getType()->isBlockPointerType())
3650 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003651 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003652
Daniel Dunbar56df9772010-08-17 22:39:59 +00003653 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3654 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003655
Steve Naroff30484702009-12-06 21:14:13 +00003656 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003657
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003658 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003659
Steve Naroff30484702009-12-06 21:14:13 +00003660 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003661
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003662 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003663
3664 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003665 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003666 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003667 }
Steve Naroff30484702009-12-06 21:14:13 +00003668 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3669 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003670 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003671
Steve Naroff677ab3a2008-10-27 17:20:55 +00003672 BlockDeclRefs.clear();
3673 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003674 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003675 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003676 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003677 ImportedBlockDecls.clear();
3678 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003679 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003680 // Must insert any 'const/volatile/static here. Since it has been
3681 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003682 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003683 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003684 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003685 if (GlobalVarDecl->getType().isConstQualified())
3686 SC += "const ";
3687 if (GlobalVarDecl->getType().isVolatileQualified())
3688 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003689 if (GlobalVarDecl->getType().isRestrictQualified())
3690 SC += "restrict ";
3691 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003692 }
3693
Steve Naroff677ab3a2008-10-27 17:20:55 +00003694 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003695 InnerDeclRefsCount.clear();
3696 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003697 RewrittenBlockExprs.clear();
3698}
3699
3700void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3701 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003702 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003703
Steve Naroff677ab3a2008-10-27 17:20:55 +00003704 SynthesizeBlockLiterals(FunLocStart, FuncName);
3705}
3706
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003707static void BuildUniqueMethodName(std::string &Name,
3708 ObjCMethodDecl *MD) {
3709 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003710 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003711 Name += "__" + MD->getSelector().getAsString();
3712 // Convert colons to underscores.
3713 std::string::size_type loc = 0;
3714 while ((loc = Name.find(":", loc)) != std::string::npos)
3715 Name.replace(loc, 1, "_");
3716}
3717
Steve Naroff677ab3a2008-10-27 17:20:55 +00003718void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003719 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3720 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003721 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003722 std::string FuncName;
3723 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003724 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003725}
3726
3727void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00003728 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00003729 if (*CI) {
3730 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3731 GetBlockDeclRefExprs(CBE->getBody());
3732 else
3733 GetBlockDeclRefExprs(*CI);
3734 }
3735 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3737 if (DRE->refersToEnclosingLocal()) {
3738 // FIXME: Handle enums.
3739 if (!isa<FunctionDecl>(DRE->getDecl()))
3740 BlockDeclRefs.push_back(DRE);
3741 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3742 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003743 }
John McCall113bee02012-03-10 09:33:50 +00003744 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003745
Steve Naroff677ab3a2008-10-27 17:20:55 +00003746 return;
3747}
3748
Craig Topper5603df42013-07-05 19:34:19 +00003749void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3750 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003751 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00003752 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003753 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003754 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3755 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003756 GetInnerBlockDeclRefExprs(CBE->getBody(),
3757 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003758 InnerContexts);
3759 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003760 else
3761 GetInnerBlockDeclRefExprs(*CI,
3762 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003763 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003764
3765 }
3766 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003767 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3768 if (DRE->refersToEnclosingLocal()) {
3769 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3770 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3771 InnerBlockDeclRefs.push_back(DRE);
3772 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3773 if (Var->isFunctionOrMethodVarDecl())
3774 ImportedLocalExternalDecls.insert(Var);
3775 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003776 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003777
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003778 return;
3779}
3780
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003781/// convertFunctionTypeOfBlocks - This routine converts a function type
3782/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003783/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003784/// all block pointers to function pointers.
3785QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3786 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3787 // FTP will be null for closures that don't take arguments.
3788 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003789 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003790 QualType Res = FT->getResultType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003791 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003792
3793 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003794 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3795 E = FTP->param_type_end();
3796 I && (I != E); ++I) {
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003797 QualType t = *I;
3798 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003799 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003800 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003801 ArgTypes.push_back(t);
3802 }
3803 }
3804 QualType FuncType;
3805 // FIXME. Does this work if block takes no argument but has a return type
3806 // which is of block type?
3807 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003808 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003809 else FuncType = QualType(FT, 0);
3810 return FuncType;
3811}
3812
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003813Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003814 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003815 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003816
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003817 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003819 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003820 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003821 }
3822 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3823 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3824 }
3825 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3826 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3827 else if (const ConditionalOperator *CEXPR =
3828 dyn_cast<ConditionalOperator>(BlockExp)) {
3829 Expr *LHSExp = CEXPR->getLHS();
3830 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3831 Expr *RHSExp = CEXPR->getRHS();
3832 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3833 Expr *CONDExp = CEXPR->getCond();
3834 ConditionalOperator *CondExpr =
3835 new (Context) ConditionalOperator(CONDExp,
3836 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003837 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003838 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003839 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003840 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3841 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003842 } else if (const PseudoObjectExpr *POE
3843 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3844 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003845 } else {
3846 assert(1 && "RewriteBlockClass: Bad type");
3847 }
3848 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003849 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003850 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003851 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003852 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003853
Abramo Bagnara6150c882010-05-11 21:36:43 +00003854 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003855 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003856 &Context->Idents.get("__block_impl"));
3857 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003858
Steve Naroff350b6652008-10-30 10:07:53 +00003859 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003860 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003861
Steve Naroff350b6652008-10-30 10:07:53 +00003862 // Push the block argument type.
3863 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003864 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003865 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3866 E = FTP->param_type_end();
3867 I && (I != E); ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003868 QualType t = *I;
3869 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003870 if (!convertBlockPointerToFunctionPointer(t))
3871 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003872 ArgTypes.push_back(t);
3873 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003874 }
Steve Naroff350b6652008-10-30 10:07:53 +00003875 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003876 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003877
Steve Naroff350b6652008-10-30 10:07:53 +00003878 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003879
John McCall97513962010-01-15 18:39:57 +00003880 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003881 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003882 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003883 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3885 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003886 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003887
Douglas Gregor91f84212008-12-11 16:49:14 +00003888 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003889 SourceLocation(),
3890 &Context->Idents.get("FuncPtr"),
3891 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003892 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003893 ICIS_NoInit);
Ted Kremenek5a201952009-02-07 01:47:29 +00003894 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003895 FD->getType(), VK_LValue,
3896 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00003897
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003898
John McCall97513962010-01-15 18:39:57 +00003899 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00003900 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00003901 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003902
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003903 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003904 // Add the implicit argument.
3905 BlkExprs.push_back(BlkCast);
3906 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003907 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003908 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003909 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003910 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003911 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003912 Exp->getType(), VK_RValue,
3913 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003914 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003915}
3916
Steve Naroffd9803712009-04-29 16:37:50 +00003917// We need to return the rewritten expression to handle cases where the
3918// BlockDeclRefExpr is embedded in another expression being rewritten.
3919// For example:
3920//
3921// int main() {
3922// __block Foo *f;
3923// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003924//
Steve Naroffd9803712009-04-29 16:37:50 +00003925// void (^myblock)() = ^() {
3926// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3927// i = 77;
3928// };
3929//}
John McCall113bee02012-03-10 09:33:50 +00003930Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003931 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003932 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003933 ValueDecl *VD = DeclRefExp->getDecl();
3934 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003935
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003936 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003937 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003938 &Context->Idents.get("__forwarding"),
3939 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003940 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003941 ICIS_NoInit);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003942 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3943 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003944 FD->getType(), VK_LValue,
3945 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003946
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003947 StringRef Name = VD->getName();
Abramo Bagnaradff19302011-03-08 08:55:46 +00003948 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003949 &Context->Idents.get(Name),
3950 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003951 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003952 ICIS_NoInit);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003953 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003954 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003955
3956
3957
Steve Narofff26a1d42009-02-02 17:19:26 +00003958 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00003959 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3960 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003961 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003962 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003963 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003964}
3965
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003966// Rewrites the imported local variable V with external storage
3967// (static, extern, etc.) as *V
3968//
3969Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3970 ValueDecl *VD = DRE->getDecl();
3971 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3972 if (!ImportedLocalExternalDecls.count(Var))
3973 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003974 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3975 VK_LValue, OK_Ordinary,
3976 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003977 // Need parens to enforce precedence.
3978 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3979 Exp);
3980 ReplaceStmt(DRE, PE);
3981 return PE;
3982}
3983
Steve Naroffc989a7b2008-11-03 23:29:32 +00003984void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3985 SourceLocation LocStart = CE->getLParenLoc();
3986 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003987
3988 // Need to avoid trying to rewrite synthesized casts.
3989 if (LocStart.isInvalid())
3990 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003991 // Need to avoid trying to rewrite casts contained in macros.
3992 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3993 return;
Mike Stump11289f42009-09-09 15:08:12 +00003994
Steve Naroff677ab3a2008-10-27 17:20:55 +00003995 const char *startBuf = SM->getCharacterData(LocStart);
3996 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003997 QualType QT = CE->getType();
3998 const Type* TypePtr = QT->getAs<Type>();
3999 if (isa<TypeOfExprType>(TypePtr)) {
4000 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4001 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4002 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00004003 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004004 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004005 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00004006 return;
4007 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004008 // advance the location to startArgList.
4009 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Steve Naroff677ab3a2008-10-27 17:20:55 +00004011 while (*argPtr++ && (argPtr < endBuf)) {
4012 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004013 case '^':
4014 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004015 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004016 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004017 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004018 }
4019 }
4020 return;
4021}
4022
4023void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4024 SourceLocation DeclLoc = FD->getLocation();
4025 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004026
Steve Naroff677ab3a2008-10-27 17:20:55 +00004027 // We have 1 or more arguments that have closure pointers.
4028 const char *startBuf = SM->getCharacterData(DeclLoc);
4029 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004030
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004032
Steve Naroff677ab3a2008-10-27 17:20:55 +00004033 parenCount++;
4034 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004035 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004036 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004037
Steve Naroff677ab3a2008-10-27 17:20:55 +00004038 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004039
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 while (*argPtr++ && parenCount) {
4041 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004042 case '^':
4043 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004044 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004045 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004046 break;
4047 case '(':
4048 parenCount++;
4049 break;
4050 case ')':
4051 parenCount--;
4052 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004053 }
4054 }
4055 return;
4056}
4057
4058bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004059 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004060 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004061 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004062 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004063 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004064 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004065 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004066 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004067 }
4068 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004069 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4070 E = FTP->param_type_end();
4071 I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004072 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004073 return true;
4074 }
4075 return false;
4076}
4077
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004078bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4079 const FunctionProtoType *FTP;
4080 const PointerType *PT = QT->getAs<PointerType>();
4081 if (PT) {
4082 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4083 } else {
4084 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4085 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4086 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4087 }
4088 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004089 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4090 E = FTP->param_type_end();
4091 I != E; ++I) {
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004092 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004093 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004094 if ((*I)->isObjCObjectPointerType() &&
4095 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4096 return true;
4097 }
4098
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004099 }
4100 return false;
4101}
4102
Ted Kremenek5a201952009-02-07 01:47:29 +00004103void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4104 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004105 const char *argPtr = strchr(Name, '(');
4106 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004107
Steve Naroff677ab3a2008-10-27 17:20:55 +00004108 LParen = argPtr; // output the start.
4109 argPtr++; // skip past the left paren.
4110 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004111
Steve Naroff677ab3a2008-10-27 17:20:55 +00004112 while (*argPtr && parenCount) {
4113 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004114 case '(': parenCount++; break;
4115 case ')': parenCount--; break;
4116 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004117 }
4118 if (parenCount) argPtr++;
4119 }
4120 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4121 RParen = argPtr; // output the end
4122}
4123
4124void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4126 RewriteBlockPointerFunctionArgs(FD);
4127 return;
Mike Stump11289f42009-09-09 15:08:12 +00004128 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004129 // Handle Variables and Typedefs.
4130 SourceLocation DeclLoc = ND->getLocation();
4131 QualType DeclT;
4132 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4133 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004134 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004135 DeclT = TDD->getUnderlyingType();
4136 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4137 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004138 else
David Blaikie83d382b2011-09-23 05:06:16 +00004139 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004140
Steve Naroff677ab3a2008-10-27 17:20:55 +00004141 const char *startBuf = SM->getCharacterData(DeclLoc);
4142 const char *endBuf = startBuf;
4143 // scan backward (from the decl location) for the end of the previous decl.
4144 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4145 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004146 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004147 std::string buf;
4148 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004149 // *startBuf != '^' if we are dealing with a pointer to function that
4150 // may take block argument types (which will be handled below).
4151 if (*startBuf == '^') {
4152 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004153 buf = '*';
4154 startBuf++;
4155 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004156 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004157 while (*startBuf != ')') {
4158 buf += *startBuf;
4159 startBuf++;
4160 OrigLength++;
4161 }
4162 buf += ')';
4163 OrigLength++;
4164
4165 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4166 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004167 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004168 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004169 DeclLoc = ND->getLocation();
4170 startBuf = SM->getCharacterData(DeclLoc);
4171 const char *argListBegin, *argListEnd;
4172 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4173 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004174 if (*argListBegin == '^')
4175 buf += '*';
4176 else if (*argListBegin == '<') {
4177 buf += "/*";
4178 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004179 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004180 while (*argListBegin != '>') {
4181 buf += *argListBegin++;
4182 OrigLength++;
4183 }
4184 buf += *argListBegin;
4185 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004186 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004187 else
4188 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004189 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004190 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004192 buf += ')';
4193 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004194 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004195 ReplaceText(Start, OrigLength, buf);
4196
Steve Naroff677ab3a2008-10-27 17:20:55 +00004197 return;
4198}
4199
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004200
4201/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4202/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4203/// struct Block_byref_id_object *src) {
4204/// _Block_object_assign (&_dest->object, _src->object,
4205/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4206/// [|BLOCK_FIELD_IS_WEAK]) // object
4207/// _Block_object_assign(&_dest->object, _src->object,
4208/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4209/// [|BLOCK_FIELD_IS_WEAK]) // block
4210/// }
4211/// And:
4212/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4213/// _Block_object_dispose(_src->object,
4214/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4215/// [|BLOCK_FIELD_IS_WEAK]) // object
4216/// _Block_object_dispose(_src->object,
4217/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4218/// [|BLOCK_FIELD_IS_WEAK]) // block
4219/// }
4220
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004221std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4222 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004223 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004224 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004225 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004226 CopyDestroyCache.insert(flag);
4227 S = "static void __Block_byref_id_object_copy_";
4228 S += utostr(flag);
4229 S += "(void *dst, void *src) {\n";
4230
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004231 // offset into the object pointer is computed as:
4232 // void * + void* + int + int + void* + void *
4233 unsigned IntSize =
4234 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4235 unsigned VoidPtrSize =
4236 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4237
Ken Dyckd9c83e62011-04-30 16:08:27 +00004238 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004239 S += " _Block_object_assign((char*)dst + ";
4240 S += utostr(offset);
4241 S += ", *(void * *) ((char*)src + ";
4242 S += utostr(offset);
4243 S += "), ";
4244 S += utostr(flag);
4245 S += ");\n}\n";
4246
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004247 S += "static void __Block_byref_id_object_dispose_";
4248 S += utostr(flag);
4249 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004250 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4251 S += utostr(offset);
4252 S += "), ";
4253 S += utostr(flag);
4254 S += ");\n}\n";
4255 return S;
4256}
4257
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004258/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4259/// the declaration into:
4260/// struct __Block_byref_ND {
4261/// void *__isa; // NULL for everything except __weak pointers
4262/// struct __Block_byref_ND *__forwarding;
4263/// int32_t __flags;
4264/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004265/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4266/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004267/// typex ND;
4268/// };
4269///
4270/// It then replaces declaration of ND variable with:
4271/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4272/// __size=sizeof(struct __Block_byref_ND),
4273/// ND=initializer-if-any};
4274///
4275///
4276void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004277 // Insert declaration for the function in which block literal is
4278 // used.
4279 if (CurFunctionDeclToDeclareForBlock)
4280 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004281 int flag = 0;
4282 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004283 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004284 if (DeclLoc.isInvalid())
4285 // If type location is missing, it is because of missing type (a warning).
4286 // Use variable's location which is good for this case.
4287 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004288 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004289 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004290 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004291 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004292 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004293 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004294 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004295 ByrefType += " {\n";
4296 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004297 RewriteByRefString(ByrefType, Name, ND);
4298 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004299 ByrefType += " int __flags;\n";
4300 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004301 // Add void *__Block_byref_id_object_copy;
4302 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004303 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004304 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004305 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004306 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4307 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004308 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004309
4310 QualType T = Ty;
4311 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004312 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004313
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004314 ByrefType += " " + Name + ";\n";
4315 ByrefType += "};\n";
4316 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004317 SourceLocation FunLocStart;
4318 if (CurFunctionDef)
4319 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4320 else {
4321 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4322 FunLocStart = CurMethodDef->getLocStart();
4323 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004324 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004325 if (Ty.isObjCGCWeak()) {
4326 flag |= BLOCK_FIELD_IS_WEAK;
4327 isa = 1;
4328 }
4329
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004330 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004331 flag = BLOCK_BYREF_CALLER;
4332 QualType Ty = ND->getType();
4333 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4334 if (Ty->isBlockPointerType())
4335 flag |= BLOCK_FIELD_IS_BLOCK;
4336 else
4337 flag |= BLOCK_FIELD_IS_OBJECT;
4338 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004339 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004340 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004341 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004342
4343 // struct __Block_byref_ND ND =
4344 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4345 // initializer-if-any};
4346 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004347 unsigned flags = 0;
4348 if (HasCopyAndDispose)
4349 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004350 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004351 ByrefType.clear();
4352 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004353 std::string ForwardingCastType("(");
4354 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004355 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004356 ByrefType += " " + Name + " = {(void*)";
4357 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004358 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004359 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004360 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004361 ByrefType += "sizeof(";
4362 RewriteByRefString(ByrefType, Name, ND);
4363 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004364 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004365 ByrefType += ", __Block_byref_id_object_copy_";
4366 ByrefType += utostr(flag);
4367 ByrefType += ", __Block_byref_id_object_dispose_";
4368 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004369 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004370 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004371 unsigned nameSize = Name.size();
4372 // for block or function pointer declaration. Name is aleady
4373 // part of the declaration.
4374 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4375 nameSize = 1;
4376 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004377 }
4378 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004379 SourceLocation startLoc;
4380 Expr *E = ND->getInit();
4381 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4382 startLoc = ECE->getLParenLoc();
4383 else
4384 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004385 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004386 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004387 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004388 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004389 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004390 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004391 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004392 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004393 ByrefType += "sizeof(";
4394 RewriteByRefString(ByrefType, Name, ND);
4395 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004396 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004397 ByrefType += "__Block_byref_id_object_copy_";
4398 ByrefType += utostr(flag);
4399 ByrefType += ", __Block_byref_id_object_dispose_";
4400 ByrefType += utostr(flag);
4401 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004402 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004403 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004404
4405 // Complete the newly synthesized compound expression by inserting a right
4406 // curly brace before the end of the declaration.
4407 // FIXME: This approach avoids rewriting the initializer expression. It
4408 // also assumes there is only one declarator. For example, the following
4409 // isn't currently supported by this routine (in general):
4410 //
4411 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4412 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004413 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4414 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004415 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4416 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004417 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004418
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004419 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004420 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004421 return;
4422}
4423
Mike Stump11289f42009-09-09 15:08:12 +00004424void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004425 // Add initializers for any closure decl refs.
4426 GetBlockDeclRefExprs(Exp->getBody());
4427 if (BlockDeclRefs.size()) {
4428 // Unique all "by copy" declarations.
4429 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004430 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004431 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4432 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4433 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4434 }
4435 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004436 // Unique all "by ref" declarations.
4437 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004438 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004439 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4440 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4441 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4442 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004443 }
4444 // Find any imported blocks...they will need special attention.
4445 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004446 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004447 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004448 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004449 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004450 }
4451}
4452
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004453FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004454 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004455 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004456 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4457 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004458 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004459}
4460
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004461Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004462 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004463 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004464 Blocks.push_back(Exp);
4465
4466 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004467
4468 // Add inner imported variables now used in current block.
4469 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004470 if (!InnerBlockDeclRefs.empty()) {
4471 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004472 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004473 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004474 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004475 // We need to save the copied-in variables in nested
4476 // blocks because it is needed at the end for some of the API generations.
4477 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004478 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4479 BlockDeclRefs.push_back(Exp);
4480 BlockByCopyDeclsPtrSet.insert(VD);
4481 BlockByCopyDecls.push_back(VD);
4482 }
John McCall113bee02012-03-10 09:33:50 +00004483 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004484 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4485 BlockDeclRefs.push_back(Exp);
4486 BlockByRefDeclsPtrSet.insert(VD);
4487 BlockByRefDecls.push_back(VD);
4488 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004489 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004490 // Find any imported blocks...they will need special attention.
4491 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004492 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004493 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4494 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4495 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004496 }
4497 InnerDeclRefsCount.push_back(countOfInnerDecls);
4498
Steve Narofff4b992a2008-10-28 20:29:00 +00004499 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004500
Steve Narofff4b992a2008-10-28 20:29:00 +00004501 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004502 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004503 else if (CurMethodDef)
4504 BuildUniqueMethodName(FuncName, CurMethodDef);
4505 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004506 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004507
Steve Narofff4b992a2008-10-28 20:29:00 +00004508 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004509
Steve Narofff4b992a2008-10-28 20:29:00 +00004510 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4511 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004512
Steve Narofff4b992a2008-10-28 20:29:00 +00004513 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004514 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4515 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004516
4517 FunctionDecl *FD;
4518 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004519
Benjamin Kramer60509af2013-09-09 14:48:42 +00004520 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004521 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004522 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004523 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004524
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004525 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004526
Steve Naroffe2514232008-10-29 21:23:59 +00004527 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004528 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004529 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4530 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004531 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004532 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004533 InitExprs.push_back(castExpr);
4534
Steve Naroff30484702009-12-06 21:14:13 +00004535 // Initialize the block descriptor.
4536 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004537
Abramo Bagnaradff19302011-03-08 08:55:46 +00004538 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4539 SourceLocation(), SourceLocation(),
4540 &Context->Idents.get(DescData.c_str()),
4541 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004542 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004543 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004544 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004545 Context->VoidPtrTy,
4546 VK_LValue,
4547 SourceLocation()),
4548 UO_AddrOf,
4549 Context->getPointerType(Context->VoidPtrTy),
4550 VK_RValue, OK_Ordinary,
4551 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004552 InitExprs.push_back(DescRefExpr);
4553
Steve Narofff4b992a2008-10-28 20:29:00 +00004554 // Add initializers for any closure decl refs.
4555 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004556 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004557 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004558 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004559 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004560 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004561 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004562 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004563 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004564 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004565 if (HasLocalVariableExternalStorage(*I)) {
4566 QualType QT = (*I)->getType();
4567 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004568 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4569 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004570 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004571 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004572 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004573 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004574 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004575 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004576 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004577 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004578 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004579 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004580 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004581 if (HasLocalVariableExternalStorage(*I)) {
4582 QualType QT = (*I)->getType();
4583 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004584 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4585 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004586 }
4587
Steve Narofff4b992a2008-10-28 20:29:00 +00004588 }
Mike Stump11289f42009-09-09 15:08:12 +00004589 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004590 }
4591 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004592 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004593 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004594 ValueDecl *ND = (*I);
4595 std::string Name(ND->getNameAsString());
4596 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004597 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004598 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4599 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004600 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004601 SourceLocation(), SourceLocation(),
4602 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004603 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4604 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4605
Daniel Dunbar56df9772010-08-17 22:39:59 +00004606 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004607 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004608 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004609 bool isNestedCapturedVar = false;
4610 if (block)
4611 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4612 ce = block->capture_end(); ci != ce; ++ci) {
4613 const VarDecl *variable = ci->getVariable();
4614 if (variable == ND && ci->isNested()) {
4615 assert (ci->isByRef() &&
4616 "SynthBlockInitExpr - captured block variable is not byref");
4617 isNestedCapturedVar = true;
4618 break;
4619 }
4620 }
4621 // captured nested byref variable has its address passed. Do not take
4622 // its address again.
4623 if (!isNestedCapturedVar)
4624 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004625 Context->getPointerType(Exp->getType()),
4626 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004627 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004628 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004629 }
4630 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004631 if (ImportedBlockDecls.size()) {
4632 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4633 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004634 unsigned IntSize =
4635 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004636 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4637 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004638 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004639 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004640 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004641 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004642 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004643 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004644 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004645 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004646 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004647 BlockDeclRefs.clear();
4648 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004649 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004650 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004651 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004652 ImportedBlockDecls.clear();
4653 return NewRep;
4654}
4655
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004656bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4657 if (const ObjCForCollectionStmt * CS =
4658 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4659 return CS->getElement() == DS;
4660 return false;
4661}
4662
Steve Narofff4b992a2008-10-28 20:29:00 +00004663//===----------------------------------------------------------------------===//
4664// Function Body / Expression rewriting
4665//===----------------------------------------------------------------------===//
4666
4667Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004668 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004669 isa<DoStmt>(S) || isa<ForStmt>(S))
4670 Stmts.push_back(S);
4671 else if (isa<ObjCForCollectionStmt>(S)) {
4672 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004673 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
John McCallfe96e0b2011-11-06 09:01:30 +00004676 // Pseudo-object operations and ivar references need special
4677 // treatment because we're going to recursively rewrite them.
4678 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4679 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4680 return RewritePropertyOrImplicitSetter(PseudoOp);
4681 } else {
4682 return RewritePropertyOrImplicitGetter(PseudoOp);
4683 }
4684 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4685 return RewriteObjCIvarRefExpr(IvarRefExpr);
4686 }
4687
Steve Narofff4b992a2008-10-28 20:29:00 +00004688 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004689
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00004691 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00004692 if (*CI) {
John McCallfe96e0b2011-11-06 09:01:30 +00004693 Stmt *childStmt = (*CI);
4694 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004695 if (newStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004696 *CI = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004697 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004698 }
Mike Stump11289f42009-09-09 15:08:12 +00004699
Steve Narofff4b992a2008-10-28 20:29:00 +00004700 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004701 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004702 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4703 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004704 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004705 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004706 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004708 Stmt *SaveCurrentBody = CurrentBody;
4709 CurrentBody = BE->getBody();
4710 PropParentMap = 0;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004711 // block literal on rhs of a property-dot-sytax assignment
4712 // must be replaced by its synthesize ast so getRewrittenText
4713 // works as expected. In this case, what actually ends up on RHS
4714 // is the blockTranscribed which is the helper function for the
4715 // block literal; as in: self.c = ^() {[ace ARR];};
4716 bool saveDisableReplaceStmt = DisableReplaceStmt;
4717 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004718 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004719 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004720 CurrentBody = SaveCurrentBody;
4721 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004722 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004723 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004724 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004725 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004726
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004727 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4728
Steve Narofff4b992a2008-10-28 20:29:00 +00004729 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004730 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004731 return blockTranscribed;
4732 }
4733 // Handle specific things.
4734 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4735 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004736
Steve Narofff4b992a2008-10-28 20:29:00 +00004737 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4738 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004739
Steve Narofff4b992a2008-10-28 20:29:00 +00004740 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4741 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004742
Steve Narofff4b992a2008-10-28 20:29:00 +00004743 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004744#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004745 // Before we rewrite it, put the original message expression in a comment.
4746 SourceLocation startLoc = MessExpr->getLocStart();
4747 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004748
Steve Narofff4b992a2008-10-28 20:29:00 +00004749 const char *startBuf = SM->getCharacterData(startLoc);
4750 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004751
Steve Narofff4b992a2008-10-28 20:29:00 +00004752 std::string messString;
4753 messString += "// ";
4754 messString.append(startBuf, endBuf-startBuf+1);
4755 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004756
4757 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004758 // InsertText(clang::SourceLocation, char const*, unsigned int).
4759 // InsertText(startLoc, messString.c_str(), messString.size());
4760 // Tried this, but it didn't work either...
4761 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004762#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004763 return RewriteMessageExpr(MessExpr);
4764 }
Mike Stump11289f42009-09-09 15:08:12 +00004765
Steve Narofff4b992a2008-10-28 20:29:00 +00004766 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4767 return RewriteObjCTryStmt(StmtTry);
4768
4769 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4770 return RewriteObjCSynchronizedStmt(StmtTry);
4771
4772 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4773 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004774
Steve Narofff4b992a2008-10-28 20:29:00 +00004775 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4776 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004777
4778 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004780 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004781 OrigStmtRange.getEnd());
4782 if (BreakStmt *StmtBreakStmt =
4783 dyn_cast<BreakStmt>(S))
4784 return RewriteBreakStmt(StmtBreakStmt);
4785 if (ContinueStmt *StmtContinueStmt =
4786 dyn_cast<ContinueStmt>(S))
4787 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004788
4789 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004790 // and cast exprs.
4791 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4792 // FIXME: What we're doing here is modifying the type-specifier that
4793 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004794 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004795 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4796 // the context of an ObjCForCollectionStmt. For example:
4797 // NSArray *someArray;
4798 // for (id <FooProtocol> index in someArray) ;
4799 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4800 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004801 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004802 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004803
Steve Narofff4b992a2008-10-28 20:29:00 +00004804 // Blocks rewrite rules.
4805 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4806 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004807 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004808 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004809 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004810 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004811 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004812 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004813 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004814 if (VD->hasAttr<BlocksAttr>()) {
4815 static unsigned uniqueByrefDeclCount = 0;
4816 assert(!BlockByRefDeclNo.count(ND) &&
4817 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4818 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004819 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004820 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004821 else
4822 RewriteTypeOfDecl(VD);
4823 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004824 }
Richard Smithdda56e42011-04-15 14:24:37 +00004825 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004826 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004827 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004828 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004829 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4830 }
4831 }
4832 }
Mike Stump11289f42009-09-09 15:08:12 +00004833
Steve Narofff4b992a2008-10-28 20:29:00 +00004834 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4835 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004836
4837 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004838 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4839 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004840 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4841 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004842 && "Statement stack mismatch");
4843 Stmts.pop_back();
4844 }
4845 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004846 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4847 ValueDecl *VD = DRE->getDecl();
4848 if (VD->hasAttr<BlocksAttr>())
4849 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004850 if (HasLocalVariableExternalStorage(VD))
4851 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004852 }
4853
Steve Narofff4b992a2008-10-28 20:29:00 +00004854 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004855 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004856 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004857 ReplaceStmt(S, BlockCall);
4858 return BlockCall;
4859 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004860 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004861 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004862 RewriteCastExpr(CE);
4863 }
4864#if 0
4865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004866 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4867 ICE->getSubExpr(),
4868 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004869 // Get the new text.
4870 std::string SStr;
4871 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004872 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004873 const std::string &Str = Buf.str();
4874
4875 printf("CAST = %s\n", &Str[0]);
4876 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4877 delete S;
4878 return Replacement;
4879 }
4880#endif
4881 // Return this stmt unmodified.
4882 return S;
4883}
4884
Steve Naroffe70a52a2009-12-05 15:55:59 +00004885void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4886 for (RecordDecl::field_iterator i = RD->field_begin(),
4887 e = RD->field_end(); i != e; ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00004888 FieldDecl *FD = *i;
Steve Naroffe70a52a2009-12-05 15:55:59 +00004889 if (isTopLevelBlockPointerType(FD->getType()))
4890 RewriteBlockPointerDecl(FD);
4891 if (FD->getType()->isObjCQualifiedIdType() ||
4892 FD->getType()->isObjCQualifiedInterfaceType())
4893 RewriteObjCQualifiedInterfaceTypes(FD);
4894 }
4895}
4896
Steve Narofff4b992a2008-10-28 20:29:00 +00004897/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4898/// main file of the input.
4899void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004900 switch (D->getKind()) {
4901 case Decl::Function: {
4902 FunctionDecl *FD = cast<FunctionDecl>(D);
4903 if (FD->isOverloadedOperator())
4904 return;
Mike Stump11289f42009-09-09 15:08:12 +00004905
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004906 // Since function prototypes don't have ParmDecl's, we check the function
4907 // prototype. This enables us to rewrite function declarations and
4908 // definitions using the same code.
4909 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004910
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004911 if (!FD->isThisDeclarationADefinition())
4912 break;
4913
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004914 // FIXME: If this should support Obj-C++, support CXXTryStmt
4915 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4916 CurFunctionDef = FD;
4917 CurFunctionDeclToDeclareForBlock = FD;
4918 CurrentBody = Body;
4919 Body =
4920 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4921 FD->setBody(Body);
4922 CurrentBody = 0;
4923 if (PropParentMap) {
4924 delete PropParentMap;
4925 PropParentMap = 0;
4926 }
4927 // This synthesizes and inserts the block "impl" struct, invoke function,
4928 // and any copy/dispose helper functions.
4929 InsertBlockLiteralsWithinFunction(FD);
4930 CurFunctionDef = 0;
4931 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004932 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004933 break;
Mike Stump11289f42009-09-09 15:08:12 +00004934 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004935 case Decl::ObjCMethod: {
4936 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4937 if (CompoundStmt *Body = MD->getCompoundBody()) {
4938 CurMethodDef = MD;
4939 CurrentBody = Body;
4940 Body =
4941 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4942 MD->setBody(Body);
4943 CurrentBody = 0;
4944 if (PropParentMap) {
4945 delete PropParentMap;
4946 PropParentMap = 0;
4947 }
4948 InsertBlockLiteralsWithinMethod(MD);
4949 CurMethodDef = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004950 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004951 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004952 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004953 case Decl::ObjCImplementation: {
4954 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4955 ClassImplementation.push_back(CI);
4956 break;
4957 }
4958 case Decl::ObjCCategoryImpl: {
4959 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4960 CategoryImplementation.push_back(CI);
4961 break;
4962 }
4963 case Decl::Var: {
4964 VarDecl *VD = cast<VarDecl>(D);
4965 RewriteObjCQualifiedInterfaceTypes(VD);
4966 if (isTopLevelBlockPointerType(VD->getType()))
4967 RewriteBlockPointerDecl(VD);
4968 else if (VD->getType()->isFunctionPointerType()) {
4969 CheckFunctionPointerDecl(VD->getType(), VD);
4970 if (VD->getInit()) {
4971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4972 RewriteCastExpr(CE);
4973 }
4974 }
4975 } else if (VD->getType()->isRecordType()) {
4976 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4977 if (RD->isCompleteDefinition())
4978 RewriteRecordBody(RD);
4979 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004980 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004981 GlobalVarDecl = VD;
4982 CurrentBody = VD->getInit();
4983 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4984 CurrentBody = 0;
4985 if (PropParentMap) {
4986 delete PropParentMap;
4987 PropParentMap = 0;
4988 }
4989 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4990 GlobalVarDecl = 0;
4991
4992 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004993 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004994 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004995 }
4996 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004997 break;
4998 }
4999 case Decl::TypeAlias:
5000 case Decl::Typedef: {
5001 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5002 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5003 RewriteBlockPointerDecl(TD);
5004 else if (TD->getUnderlyingType()->isFunctionPointerType())
5005 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5006 }
5007 break;
5008 }
5009 case Decl::CXXRecord:
5010 case Decl::Record: {
5011 RecordDecl *RD = cast<RecordDecl>(D);
5012 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00005013 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00005014 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00005015 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00005016 default:
5017 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00005018 }
5019 // Nothing yet.
5020}
5021
Chris Lattnercf169832009-03-28 04:11:33 +00005022void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00005023 if (Diags.hasErrorOccurred())
5024 return;
Mike Stump11289f42009-09-09 15:08:12 +00005025
Steve Narofff4b992a2008-10-28 20:29:00 +00005026 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00005027
Steve Naroffd9803712009-04-29 16:37:50 +00005028 // Here's a great place to add any extra declarations that may be needed.
5029 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00005030 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00005031 E = ProtocolExprDecls.end(); I != E; ++I)
5032 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5033
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005034 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005035 if (ClassImplementation.size() || CategoryImplementation.size())
5036 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005037
Steve Narofff4b992a2008-10-28 20:29:00 +00005038 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5039 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005040 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005041 Rewrite.getRewriteBufferFor(MainFileID)) {
5042 //printf("Changed:\n");
5043 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5044 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005045 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005046 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005047
Steve Naroffd9803712009-04-29 16:37:50 +00005048 if (ClassImplementation.size() || CategoryImplementation.size() ||
5049 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005050 // Rewrite Objective-c meta data*
5051 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00005052 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005053 // Emit metadata.
5054 *OutFile << ResultStr;
5055 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005056 OutFile->flush();
5057}
Fariborz Jahanian83077422011-12-08 18:25:15 +00005058
5059void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5060 InitializeCommon(context);
5061
5062 // declaring objc_selector outside the parameter list removes a silly
5063 // scope related warning...
5064 if (IsHeader)
5065 Preamble = "#pragma once\n";
5066 Preamble += "struct objc_selector; struct objc_class;\n";
5067 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5068 Preamble += "struct objc_object *superClass; ";
5069 if (LangOpts.MicrosoftExt) {
5070 // Add a constructor for creating temporary objects.
5071 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5072 ": ";
5073 Preamble += "object(o), superClass(s) {} ";
5074 }
5075 Preamble += "};\n";
5076 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5077 Preamble += "typedef struct objc_object Protocol;\n";
5078 Preamble += "#define _REWRITER_typedef_Protocol\n";
5079 Preamble += "#endif\n";
5080 if (LangOpts.MicrosoftExt) {
5081 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5082 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5083 } else
5084 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5086 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5088 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5090 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5092 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5094 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5096 Preamble += "(const char *);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5098 Preamble += "(struct objc_class *);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5100 Preamble += "(const char *);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5106 Preamble += "(struct objc_class *, struct objc_object *);\n";
5107 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005108 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5109 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005110 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5111 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5112 Preamble += "struct __objcFastEnumerationState {\n\t";
5113 Preamble += "unsigned long state;\n\t";
5114 Preamble += "void **itemsPtr;\n\t";
5115 Preamble += "unsigned long *mutationsPtr;\n\t";
5116 Preamble += "unsigned long extra[5];\n};\n";
5117 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5118 Preamble += "#define __FASTENUMERATIONSTATE\n";
5119 Preamble += "#endif\n";
5120 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5121 Preamble += "struct __NSConstantStringImpl {\n";
5122 Preamble += " int *isa;\n";
5123 Preamble += " int flags;\n";
5124 Preamble += " char *str;\n";
5125 Preamble += " long length;\n";
5126 Preamble += "};\n";
5127 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5129 Preamble += "#else\n";
5130 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5131 Preamble += "#endif\n";
5132 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5133 Preamble += "#endif\n";
5134 // Blocks preamble.
5135 Preamble += "#ifndef BLOCK_IMPL\n";
5136 Preamble += "#define BLOCK_IMPL\n";
5137 Preamble += "struct __block_impl {\n";
5138 Preamble += " void *isa;\n";
5139 Preamble += " int Flags;\n";
5140 Preamble += " int Reserved;\n";
5141 Preamble += " void *FuncPtr;\n";
5142 Preamble += "};\n";
5143 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5144 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5145 Preamble += "extern \"C\" __declspec(dllexport) "
5146 "void _Block_object_assign(void *, const void *, const int);\n";
5147 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5148 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5149 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5150 Preamble += "#else\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5152 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5153 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5154 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5155 Preamble += "#endif\n";
5156 Preamble += "#endif\n";
5157 if (LangOpts.MicrosoftExt) {
5158 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5159 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5160 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5161 Preamble += "#define __attribute__(X)\n";
5162 Preamble += "#endif\n";
5163 Preamble += "#define __weak\n";
5164 }
5165 else {
5166 Preamble += "#define __block\n";
5167 Preamble += "#define __weak\n";
5168 }
5169 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5170 // as this avoids warning in any 64bit/32bit compilation model.
5171 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5172}
5173
5174/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5175/// ivar offset.
5176void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5177 std::string &Result) {
5178 if (ivar->isBitField()) {
5179 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5180 // place all bitfields at offset 0.
5181 Result += "0";
5182 } else {
5183 Result += "__OFFSETOFIVAR__(struct ";
5184 Result += ivar->getContainingInterface()->getNameAsString();
5185 if (LangOpts.MicrosoftExt)
5186 Result += "_IMPL";
5187 Result += ", ";
5188 Result += ivar->getNameAsString();
5189 Result += ")";
5190 }
5191}
5192
5193/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5194void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5195 ObjCProtocolDecl *PDecl, StringRef prefix,
5196 StringRef ClassName, std::string &Result) {
5197 static bool objc_protocol_methods = false;
5198
5199 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005200 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005201 /* struct protocol_methods {
5202 SEL _cmd;
5203 char *method_types;
5204 }
5205 */
5206 Result += "\nstruct _protocol_methods {\n";
5207 Result += "\tstruct objc_selector *_cmd;\n";
5208 Result += "\tchar *method_types;\n";
5209 Result += "};\n";
5210
5211 objc_protocol_methods = true;
5212 }
5213 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005214 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005215 return;
5216
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005217 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5218 PDecl = Def;
5219
Fariborz Jahanian83077422011-12-08 18:25:15 +00005220 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5221 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5222 PDecl->instmeth_end());
5223 /* struct _objc_protocol_method_list {
5224 int protocol_method_count;
5225 struct protocol_methods protocols[];
5226 }
5227 */
5228 Result += "\nstatic struct {\n";
5229 Result += "\tint protocol_method_count;\n";
5230 Result += "\tstruct _protocol_methods protocol_methods[";
5231 Result += utostr(NumMethods);
5232 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5233 Result += PDecl->getNameAsString();
5234 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5235 "{\n\t" + utostr(NumMethods) + "\n";
5236
5237 // Output instance methods declared in this protocol.
5238 for (ObjCProtocolDecl::instmeth_iterator
5239 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5240 I != E; ++I) {
5241 if (I == PDecl->instmeth_begin())
5242 Result += "\t ,{{(struct objc_selector *)\"";
5243 else
5244 Result += "\t ,{(struct objc_selector *)\"";
5245 Result += (*I)->getSelector().getAsString();
5246 std::string MethodTypeString;
5247 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5248 Result += "\", \"";
5249 Result += MethodTypeString;
5250 Result += "\"}\n";
5251 }
5252 Result += "\t }\n};\n";
5253 }
5254
5255 // Output class methods declared in this protocol.
5256 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5257 PDecl->classmeth_end());
5258 if (NumMethods > 0) {
5259 /* struct _objc_protocol_method_list {
5260 int protocol_method_count;
5261 struct protocol_methods protocols[];
5262 }
5263 */
5264 Result += "\nstatic struct {\n";
5265 Result += "\tint protocol_method_count;\n";
5266 Result += "\tstruct _protocol_methods protocol_methods[";
5267 Result += utostr(NumMethods);
5268 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5269 Result += PDecl->getNameAsString();
5270 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5271 "{\n\t";
5272 Result += utostr(NumMethods);
5273 Result += "\n";
5274
5275 // Output instance methods declared in this protocol.
5276 for (ObjCProtocolDecl::classmeth_iterator
5277 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5278 I != E; ++I) {
5279 if (I == PDecl->classmeth_begin())
5280 Result += "\t ,{{(struct objc_selector *)\"";
5281 else
5282 Result += "\t ,{(struct objc_selector *)\"";
5283 Result += (*I)->getSelector().getAsString();
5284 std::string MethodTypeString;
5285 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5286 Result += "\", \"";
5287 Result += MethodTypeString;
5288 Result += "\"}\n";
5289 }
5290 Result += "\t }\n};\n";
5291 }
5292
5293 // Output:
5294 /* struct _objc_protocol {
5295 // Objective-C 1.0 extensions
5296 struct _objc_protocol_extension *isa;
5297 char *protocol_name;
5298 struct _objc_protocol **protocol_list;
5299 struct _objc_protocol_method_list *instance_methods;
5300 struct _objc_protocol_method_list *class_methods;
5301 };
5302 */
5303 static bool objc_protocol = false;
5304 if (!objc_protocol) {
5305 Result += "\nstruct _objc_protocol {\n";
5306 Result += "\tstruct _objc_protocol_extension *isa;\n";
5307 Result += "\tchar *protocol_name;\n";
5308 Result += "\tstruct _objc_protocol **protocol_list;\n";
5309 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5310 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5311 Result += "};\n";
5312
5313 objc_protocol = true;
5314 }
5315
5316 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5317 Result += PDecl->getNameAsString();
5318 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5319 "{\n\t0, \"";
5320 Result += PDecl->getNameAsString();
5321 Result += "\", 0, ";
5322 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5323 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5324 Result += PDecl->getNameAsString();
5325 Result += ", ";
5326 }
5327 else
5328 Result += "0, ";
5329 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5330 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5331 Result += PDecl->getNameAsString();
5332 Result += "\n";
5333 }
5334 else
5335 Result += "0\n";
5336 Result += "};\n";
5337
5338 // Mark this protocol as having been generated.
Douglas Gregor33b24292012-01-01 18:09:12 +00005339 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005340 llvm_unreachable("protocol already synthesized");
5341
5342}
5343
5344void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5345 const ObjCList<ObjCProtocolDecl> &Protocols,
5346 StringRef prefix, StringRef ClassName,
5347 std::string &Result) {
5348 if (Protocols.empty()) return;
5349
5350 for (unsigned i = 0; i != Protocols.size(); i++)
5351 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5352
5353 // Output the top lovel protocol meta-data for the class.
5354 /* struct _objc_protocol_list {
5355 struct _objc_protocol_list *next;
5356 int protocol_count;
5357 struct _objc_protocol *class_protocols[];
5358 }
5359 */
5360 Result += "\nstatic struct {\n";
5361 Result += "\tstruct _objc_protocol_list *next;\n";
5362 Result += "\tint protocol_count;\n";
5363 Result += "\tstruct _objc_protocol *class_protocols[";
5364 Result += utostr(Protocols.size());
5365 Result += "];\n} _OBJC_";
5366 Result += prefix;
5367 Result += "_PROTOCOLS_";
5368 Result += ClassName;
5369 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5370 "{\n\t0, ";
5371 Result += utostr(Protocols.size());
5372 Result += "\n";
5373
5374 Result += "\t,{&_OBJC_PROTOCOL_";
5375 Result += Protocols[0]->getNameAsString();
5376 Result += " \n";
5377
5378 for (unsigned i = 1; i != Protocols.size(); i++) {
5379 Result += "\t ,&_OBJC_PROTOCOL_";
5380 Result += Protocols[i]->getNameAsString();
5381 Result += "\n";
5382 }
5383 Result += "\t }\n};\n";
5384}
5385
5386void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5387 std::string &Result) {
5388 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5389
5390 // Explicitly declared @interface's are already synthesized.
5391 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005392 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005393 // produce correct synthesis as yet.
5394 RewriteObjCInternalStruct(CDecl, Result);
5395 }
5396
5397 // Build _objc_ivar_list metadata for classes ivars if needed
5398 unsigned NumIvars = !IDecl->ivar_empty()
5399 ? IDecl->ivar_size()
5400 : (CDecl ? CDecl->ivar_size() : 0);
5401 if (NumIvars > 0) {
5402 static bool objc_ivar = false;
5403 if (!objc_ivar) {
5404 /* struct _objc_ivar {
5405 char *ivar_name;
5406 char *ivar_type;
5407 int ivar_offset;
5408 };
5409 */
5410 Result += "\nstruct _objc_ivar {\n";
5411 Result += "\tchar *ivar_name;\n";
5412 Result += "\tchar *ivar_type;\n";
5413 Result += "\tint ivar_offset;\n";
5414 Result += "};\n";
5415
5416 objc_ivar = true;
5417 }
5418
5419 /* struct {
5420 int ivar_count;
5421 struct _objc_ivar ivar_list[nIvars];
5422 };
5423 */
5424 Result += "\nstatic struct {\n";
5425 Result += "\tint ivar_count;\n";
5426 Result += "\tstruct _objc_ivar ivar_list[";
5427 Result += utostr(NumIvars);
5428 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5429 Result += IDecl->getNameAsString();
5430 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5431 "{\n\t";
5432 Result += utostr(NumIvars);
5433 Result += "\n";
5434
5435 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5436 SmallVector<ObjCIvarDecl *, 8> IVars;
5437 if (!IDecl->ivar_empty()) {
5438 for (ObjCInterfaceDecl::ivar_iterator
5439 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5440 IV != IVEnd; ++IV)
David Blaikie40ed2972012-06-06 20:45:41 +00005441 IVars.push_back(*IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005442 IVI = IDecl->ivar_begin();
5443 IVE = IDecl->ivar_end();
5444 } else {
5445 IVI = CDecl->ivar_begin();
5446 IVE = CDecl->ivar_end();
5447 }
5448 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005449 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005450 Result += "\", \"";
5451 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005452 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005453 QuoteDoublequotes(TmpString, StrEncoding);
5454 Result += StrEncoding;
5455 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005456 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005457 Result += "}\n";
5458 for (++IVI; IVI != IVE; ++IVI) {
5459 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005460 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005461 Result += "\", \"";
5462 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005463 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005464 QuoteDoublequotes(TmpString, StrEncoding);
5465 Result += StrEncoding;
5466 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005467 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005468 Result += "}\n";
5469 }
5470
5471 Result += "\t }\n};\n";
5472 }
5473
5474 // Build _objc_method_list for class's instance methods if needed
5475 SmallVector<ObjCMethodDecl *, 32>
5476 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5477
5478 // If any of our property implementations have associated getters or
5479 // setters, produce metadata for them as well.
5480 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5481 PropEnd = IDecl->propimpl_end();
5482 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005483 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005484 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005485 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005486 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005487 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005488 if (!PD)
5489 continue;
5490 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5491 if (!Getter->isDefined())
5492 InstanceMethods.push_back(Getter);
5493 if (PD->isReadOnly())
5494 continue;
5495 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5496 if (!Setter->isDefined())
5497 InstanceMethods.push_back(Setter);
5498 }
5499 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5500 true, "", IDecl->getName(), Result);
5501
5502 // Build _objc_method_list for class's class methods if needed
5503 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5504 false, "", IDecl->getName(), Result);
5505
5506 // Protocols referenced in class declaration?
5507 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5508 "CLASS", CDecl->getName(), Result);
5509
5510 // Declaration of class/meta-class metadata
5511 /* struct _objc_class {
5512 struct _objc_class *isa; // or const char *root_class_name when metadata
5513 const char *super_class_name;
5514 char *name;
5515 long version;
5516 long info;
5517 long instance_size;
5518 struct _objc_ivar_list *ivars;
5519 struct _objc_method_list *methods;
5520 struct objc_cache *cache;
5521 struct objc_protocol_list *protocols;
5522 const char *ivar_layout;
5523 struct _objc_class_ext *ext;
5524 };
5525 */
5526 static bool objc_class = false;
5527 if (!objc_class) {
5528 Result += "\nstruct _objc_class {\n";
5529 Result += "\tstruct _objc_class *isa;\n";
5530 Result += "\tconst char *super_class_name;\n";
5531 Result += "\tchar *name;\n";
5532 Result += "\tlong version;\n";
5533 Result += "\tlong info;\n";
5534 Result += "\tlong instance_size;\n";
5535 Result += "\tstruct _objc_ivar_list *ivars;\n";
5536 Result += "\tstruct _objc_method_list *methods;\n";
5537 Result += "\tstruct objc_cache *cache;\n";
5538 Result += "\tstruct _objc_protocol_list *protocols;\n";
5539 Result += "\tconst char *ivar_layout;\n";
5540 Result += "\tstruct _objc_class_ext *ext;\n";
5541 Result += "};\n";
5542 objc_class = true;
5543 }
5544
5545 // Meta-class metadata generation.
5546 ObjCInterfaceDecl *RootClass = 0;
5547 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5548 while (SuperClass) {
5549 RootClass = SuperClass;
5550 SuperClass = SuperClass->getSuperClass();
5551 }
5552 SuperClass = CDecl->getSuperClass();
5553
5554 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5555 Result += CDecl->getNameAsString();
5556 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5557 "{\n\t(struct _objc_class *)\"";
5558 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5559 Result += "\"";
5560
5561 if (SuperClass) {
5562 Result += ", \"";
5563 Result += SuperClass->getNameAsString();
5564 Result += "\", \"";
5565 Result += CDecl->getNameAsString();
5566 Result += "\"";
5567 }
5568 else {
5569 Result += ", 0, \"";
5570 Result += CDecl->getNameAsString();
5571 Result += "\"";
5572 }
5573 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5574 // 'info' field is initialized to CLS_META(2) for metaclass
5575 Result += ", 0,2, sizeof(struct _objc_class), 0";
5576 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5577 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5578 Result += IDecl->getNameAsString();
5579 Result += "\n";
5580 }
5581 else
5582 Result += ", 0\n";
5583 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5584 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5585 Result += CDecl->getNameAsString();
5586 Result += ",0,0\n";
5587 }
5588 else
5589 Result += "\t,0,0,0,0\n";
5590 Result += "};\n";
5591
5592 // class metadata generation.
5593 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5594 Result += CDecl->getNameAsString();
5595 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5596 "{\n\t&_OBJC_METACLASS_";
5597 Result += CDecl->getNameAsString();
5598 if (SuperClass) {
5599 Result += ", \"";
5600 Result += SuperClass->getNameAsString();
5601 Result += "\", \"";
5602 Result += CDecl->getNameAsString();
5603 Result += "\"";
5604 }
5605 else {
5606 Result += ", 0, \"";
5607 Result += CDecl->getNameAsString();
5608 Result += "\"";
5609 }
5610 // 'info' field is initialized to CLS_CLASS(1) for class
5611 Result += ", 0,1";
5612 if (!ObjCSynthesizedStructs.count(CDecl))
5613 Result += ",0";
5614 else {
5615 // class has size. Must synthesize its size.
5616 Result += ",sizeof(struct ";
5617 Result += CDecl->getNameAsString();
5618 if (LangOpts.MicrosoftExt)
5619 Result += "_IMPL";
5620 Result += ")";
5621 }
5622 if (NumIvars > 0) {
5623 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5624 Result += CDecl->getNameAsString();
5625 Result += "\n\t";
5626 }
5627 else
5628 Result += ",0";
5629 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5630 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5631 Result += CDecl->getNameAsString();
5632 Result += ", 0\n\t";
5633 }
5634 else
5635 Result += ",0,0";
5636 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5637 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5638 Result += CDecl->getNameAsString();
5639 Result += ", 0,0\n";
5640 }
5641 else
5642 Result += ",0,0,0\n";
5643 Result += "};\n";
5644}
5645
5646void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5647 int ClsDefCount = ClassImplementation.size();
5648 int CatDefCount = CategoryImplementation.size();
5649
5650 // For each implemented class, write out all its meta data.
5651 for (int i = 0; i < ClsDefCount; i++)
5652 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5653
5654 // For each implemented category, write out all its meta data.
5655 for (int i = 0; i < CatDefCount; i++)
5656 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5657
5658 // Write objc_symtab metadata
5659 /*
5660 struct _objc_symtab
5661 {
5662 long sel_ref_cnt;
5663 SEL *refs;
5664 short cls_def_cnt;
5665 short cat_def_cnt;
5666 void *defs[cls_def_cnt + cat_def_cnt];
5667 };
5668 */
5669
5670 Result += "\nstruct _objc_symtab {\n";
5671 Result += "\tlong sel_ref_cnt;\n";
5672 Result += "\tSEL *refs;\n";
5673 Result += "\tshort cls_def_cnt;\n";
5674 Result += "\tshort cat_def_cnt;\n";
5675 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5676 Result += "};\n\n";
5677
5678 Result += "static struct _objc_symtab "
5679 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5680 Result += "\t0, 0, " + utostr(ClsDefCount)
5681 + ", " + utostr(CatDefCount) + "\n";
5682 for (int i = 0; i < ClsDefCount; i++) {
5683 Result += "\t,&_OBJC_CLASS_";
5684 Result += ClassImplementation[i]->getNameAsString();
5685 Result += "\n";
5686 }
5687
5688 for (int i = 0; i < CatDefCount; i++) {
5689 Result += "\t,&_OBJC_CATEGORY_";
5690 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5691 Result += "_";
5692 Result += CategoryImplementation[i]->getNameAsString();
5693 Result += "\n";
5694 }
5695
5696 Result += "};\n\n";
5697
5698 // Write objc_module metadata
5699
5700 /*
5701 struct _objc_module {
5702 long version;
5703 long size;
5704 const char *name;
5705 struct _objc_symtab *symtab;
5706 }
5707 */
5708
5709 Result += "\nstruct _objc_module {\n";
5710 Result += "\tlong version;\n";
5711 Result += "\tlong size;\n";
5712 Result += "\tconst char *name;\n";
5713 Result += "\tstruct _objc_symtab *symtab;\n";
5714 Result += "};\n\n";
5715 Result += "static struct _objc_module "
5716 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5717 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5718 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5719 Result += "};\n\n";
5720
5721 if (LangOpts.MicrosoftExt) {
5722 if (ProtocolExprDecls.size()) {
5723 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5724 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5725 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5726 E = ProtocolExprDecls.end(); I != E; ++I) {
5727 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5728 Result += (*I)->getNameAsString();
5729 Result += " = &_OBJC_PROTOCOL_";
5730 Result += (*I)->getNameAsString();
5731 Result += ";\n";
5732 }
5733 Result += "#pragma data_seg(pop)\n\n";
5734 }
5735 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5736 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5737 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5738 Result += "&_OBJC_MODULES;\n";
5739 Result += "#pragma data_seg(pop)\n\n";
5740 }
5741}
5742
5743/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5744/// implementation.
5745void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5746 std::string &Result) {
5747 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5748 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005749 ObjCCategoryDecl *CDecl
5750 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005751
5752 std::string FullCategoryName = ClassDecl->getNameAsString();
5753 FullCategoryName += '_';
5754 FullCategoryName += IDecl->getNameAsString();
5755
5756 // Build _objc_method_list for class's instance methods if needed
5757 SmallVector<ObjCMethodDecl *, 32>
5758 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5759
5760 // If any of our property implementations have associated getters or
5761 // setters, produce metadata for them as well.
5762 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5763 PropEnd = IDecl->propimpl_end();
5764 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005765 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005766 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005767 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005768 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005769 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005770 if (!PD)
5771 continue;
5772 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5773 InstanceMethods.push_back(Getter);
5774 if (PD->isReadOnly())
5775 continue;
5776 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5777 InstanceMethods.push_back(Setter);
5778 }
5779 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5780 true, "CATEGORY_", FullCategoryName.c_str(),
5781 Result);
5782
5783 // Build _objc_method_list for class's class methods if needed
5784 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5785 false, "CATEGORY_", FullCategoryName.c_str(),
5786 Result);
5787
5788 // Protocols referenced in class declaration?
5789 // Null CDecl is case of a category implementation with no category interface
5790 if (CDecl)
5791 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5792 FullCategoryName, Result);
5793 /* struct _objc_category {
5794 char *category_name;
5795 char *class_name;
5796 struct _objc_method_list *instance_methods;
5797 struct _objc_method_list *class_methods;
5798 struct _objc_protocol_list *protocols;
5799 // Objective-C 1.0 extensions
5800 uint32_t size; // sizeof (struct _objc_category)
5801 struct _objc_property_list *instance_properties; // category's own
5802 // @property decl.
5803 };
5804 */
5805
5806 static bool objc_category = false;
5807 if (!objc_category) {
5808 Result += "\nstruct _objc_category {\n";
5809 Result += "\tchar *category_name;\n";
5810 Result += "\tchar *class_name;\n";
5811 Result += "\tstruct _objc_method_list *instance_methods;\n";
5812 Result += "\tstruct _objc_method_list *class_methods;\n";
5813 Result += "\tstruct _objc_protocol_list *protocols;\n";
5814 Result += "\tunsigned int size;\n";
5815 Result += "\tstruct _objc_property_list *instance_properties;\n";
5816 Result += "};\n";
5817 objc_category = true;
5818 }
5819 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5820 Result += FullCategoryName;
5821 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5822 Result += IDecl->getNameAsString();
5823 Result += "\"\n\t, \"";
5824 Result += ClassDecl->getNameAsString();
5825 Result += "\"\n";
5826
5827 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5828 Result += "\t, (struct _objc_method_list *)"
5829 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5830 Result += FullCategoryName;
5831 Result += "\n";
5832 }
5833 else
5834 Result += "\t, 0\n";
5835 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5836 Result += "\t, (struct _objc_method_list *)"
5837 "&_OBJC_CATEGORY_CLASS_METHODS_";
5838 Result += FullCategoryName;
5839 Result += "\n";
5840 }
5841 else
5842 Result += "\t, 0\n";
5843
5844 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5845 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5846 Result += FullCategoryName;
5847 Result += "\n";
5848 }
5849 else
5850 Result += "\t, 0\n";
5851 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5852}
5853
5854// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5855/// class methods.
5856template<typename MethodIterator>
5857void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5858 MethodIterator MethodEnd,
5859 bool IsInstanceMethod,
5860 StringRef prefix,
5861 StringRef ClassName,
5862 std::string &Result) {
5863 if (MethodBegin == MethodEnd) return;
5864
5865 if (!objc_impl_method) {
5866 /* struct _objc_method {
5867 SEL _cmd;
5868 char *method_types;
5869 void *_imp;
5870 }
5871 */
5872 Result += "\nstruct _objc_method {\n";
5873 Result += "\tSEL _cmd;\n";
5874 Result += "\tchar *method_types;\n";
5875 Result += "\tvoid *_imp;\n";
5876 Result += "};\n";
5877
5878 objc_impl_method = true;
5879 }
5880
5881 // Build _objc_method_list for class's methods if needed
5882
5883 /* struct {
5884 struct _objc_method_list *next_method;
5885 int method_count;
5886 struct _objc_method method_list[];
5887 }
5888 */
5889 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5890 Result += "\nstatic struct {\n";
5891 Result += "\tstruct _objc_method_list *next_method;\n";
5892 Result += "\tint method_count;\n";
5893 Result += "\tstruct _objc_method method_list[";
5894 Result += utostr(NumMethods);
5895 Result += "];\n} _OBJC_";
5896 Result += prefix;
5897 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5898 Result += "_METHODS_";
5899 Result += ClassName;
5900 Result += " __attribute__ ((used, section (\"__OBJC, __";
5901 Result += IsInstanceMethod ? "inst" : "cls";
5902 Result += "_meth\")))= ";
5903 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5904
5905 Result += "\t,{{(SEL)\"";
5906 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5907 std::string MethodTypeString;
5908 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5909 Result += "\", \"";
5910 Result += MethodTypeString;
5911 Result += "\", (void *)";
5912 Result += MethodInternalNames[*MethodBegin];
5913 Result += "}\n";
5914 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5915 Result += "\t ,{(SEL)\"";
5916 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5917 std::string MethodTypeString;
5918 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5919 Result += "\", \"";
5920 Result += MethodTypeString;
5921 Result += "\", (void *)";
5922 Result += MethodInternalNames[*MethodBegin];
5923 Result += "}\n";
5924 }
5925 Result += "\t }\n};\n";
5926}
5927
5928Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5929 SourceRange OldRange = IV->getSourceRange();
5930 Expr *BaseExpr = IV->getBase();
5931
5932 // Rewrite the base, but without actually doing replaces.
5933 {
5934 DisableReplaceStmtScope S(*this);
5935 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5936 IV->setBase(BaseExpr);
5937 }
5938
5939 ObjCIvarDecl *D = IV->getDecl();
5940
5941 Expr *Replacement = IV;
5942 if (CurMethodDef) {
5943 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5944 const ObjCInterfaceType *iFaceDecl =
5945 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5946 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5947 // lookup which class implements the instance variable.
5948 ObjCInterfaceDecl *clsDeclared = 0;
5949 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5950 clsDeclared);
5951 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5952
5953 // Synthesize an explicit cast to gain access to the ivar.
5954 std::string RecName = clsDeclared->getIdentifier()->getName();
5955 RecName += "_IMPL";
5956 IdentifierInfo *II = &Context->Idents.get(RecName);
5957 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5958 SourceLocation(), SourceLocation(),
5959 II);
5960 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5961 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5962 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5963 CK_BitCast,
5964 IV->getBase());
5965 // Don't forget the parens to enforce the proper binding.
5966 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5967 OldRange.getEnd(),
5968 castExpr);
5969 if (IV->isFreeIvar() &&
Douglas Gregor0b144e12011-12-15 00:29:59 +00005970 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005971 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5972 IV->getLocation(),
5973 D->getType(),
5974 VK_LValue, OK_Ordinary);
5975 Replacement = ME;
5976 } else {
5977 IV->setBase(PE);
5978 }
5979 }
5980 } else { // we are outside a method.
5981 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5982
5983 // Explicit ivar refs need to have a cast inserted.
5984 // FIXME: consider sharing some of this code with the code above.
5985 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5986 const ObjCInterfaceType *iFaceDecl =
5987 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5988 // lookup which class implements the instance variable.
5989 ObjCInterfaceDecl *clsDeclared = 0;
5990 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5991 clsDeclared);
5992 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5993
5994 // Synthesize an explicit cast to gain access to the ivar.
5995 std::string RecName = clsDeclared->getIdentifier()->getName();
5996 RecName += "_IMPL";
5997 IdentifierInfo *II = &Context->Idents.get(RecName);
5998 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5999 SourceLocation(), SourceLocation(),
6000 II);
6001 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6002 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6003 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6004 CK_BitCast,
6005 IV->getBase());
6006 // Don't forget the parens to enforce the proper binding.
6007 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6008 IV->getBase()->getLocEnd(), castExpr);
6009 // Cannot delete IV->getBase(), since PE points to it.
6010 // Replace the old base with the cast. This is important when doing
6011 // embedded rewrites. For example, [newInv->_container addObject:0].
6012 IV->setBase(PE);
6013 }
6014 }
6015
6016 ReplaceStmtWithRange(IV, Replacement, OldRange);
6017 return Replacement;
6018}