blob: bca2099987ec07b8a3ae21c76a20e083f960fa5d [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"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000030#include <memory>
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 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000504
505 StringLiteral *getStringLiteral(StringRef Str) {
506 QualType StrType = Context->getConstantArrayType(
507 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
508 0);
509 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
510 /*Pascal=*/false, StrType, SourceLocation());
511 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000512 };
Fariborz Jahanian83077422011-12-08 18:25:15 +0000513
514 class RewriteObjCFragileABI : public RewriteObjC {
515 public:
516
517 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
518 DiagnosticsEngine &D, const LangOptions &LOpts,
519 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
520 D, LOpts,
521 silenceMacroWarn) {}
522
523 ~RewriteObjCFragileABI() {}
524 virtual void Initialize(ASTContext &context);
525
526 // Rewriting metadata
527 template<typename MethodIterator>
528 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
529 MethodIterator MethodEnd,
530 bool IsInstanceMethod,
531 StringRef prefix,
532 StringRef ClassName,
533 std::string &Result);
534 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
535 StringRef prefix,
536 StringRef ClassName,
537 std::string &Result);
538 virtual void RewriteObjCProtocolListMetaData(
539 const ObjCList<ObjCProtocolDecl> &Prots,
540 StringRef prefix, StringRef ClassName, std::string &Result);
541 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
542 std::string &Result);
543 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
544 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
545 std::string &Result);
546
547 // Rewriting ivar
548 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
549 std::string &Result);
550 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
551 };
Chris Lattnere99c8322007-10-11 00:43:27 +0000552}
553
Mike Stump11289f42009-09-09 15:08:12 +0000554void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
555 NamedDecl *D) {
John McCall424cec92011-01-19 06:33:43 +0000556 if (const FunctionProtoType *fproto
Abramo Bagnara6d810632010-12-14 22:11:44 +0000557 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000558 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
559 E = fproto->param_type_end();
560 I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000561 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000562 // All the args are checked/rewritten. Don't call twice!
563 RewriteBlockPointerDecl(D);
564 break;
565 }
566 }
567}
568
569void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000571 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000572 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000573}
574
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000575static bool IsHeaderFile(const std::string &Filename) {
576 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000577
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000578 if (DotPos == std::string::npos) {
579 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000580 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000581 }
Mike Stump11289f42009-09-09 15:08:12 +0000582
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000583 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
584 // C header: .h
585 // C++ header: .hh or .H;
586 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000587}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000588
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000589RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000590 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000591 bool silenceMacroWarn)
592 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
593 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000594 IsHeader = IsHeaderFile(inFile);
David Blaikie9c902b52011-09-25 23:23:43 +0000595 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000596 "rewriting sub-expression within a macro (may not be correct)");
David Blaikie9c902b52011-09-25 23:23:43 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000601}
602
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000603ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000604 raw_ostream* OS,
David Blaikie9c902b52011-09-25 23:23:43 +0000605 DiagnosticsEngine &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000606 const LangOptions &LOpts,
607 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000608 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000609}
Chris Lattnere99c8322007-10-11 00:43:27 +0000610
Fariborz Jahanian83077422011-12-08 18:25:15 +0000611void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000612 Context = &context;
613 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000614 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000615 MsgSendFunctionDecl = 0;
616 MsgSendSuperFunctionDecl = 0;
617 MsgSendStretFunctionDecl = 0;
618 MsgSendSuperStretFunctionDecl = 0;
619 MsgSendFpretFunctionDecl = 0;
620 GetClassFunctionDecl = 0;
621 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +0000622 GetSuperClassFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000623 SelGetUidFunctionDecl = 0;
624 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000625 ConstantStringClassReference = 0;
626 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000627 CurMethodDef = 0;
628 CurFunctionDef = 0;
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +0000629 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000630 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000631 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000632 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000633 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000634 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000635 SuperConstructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000636 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000637 PropParentMap = 0;
638 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000639 DisableReplaceStmt = false;
Fariborz Jahanianbc6811c2010-01-07 22:51:18 +0000640 objc_impl_method = false;
Mike Stump11289f42009-09-09 15:08:12 +0000641
Chris Lattner187f6262008-01-31 19:38:44 +0000642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000647
David Blaikiebbafb8a2012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner187f6262008-01-31 19:38:44 +0000649}
650
Chris Lattner3c799d72007-10-24 17:06:59 +0000651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000655void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremenek31e7f0f2010-02-05 21:28:51 +0000656 if (Diags.hasErrorOccurred())
657 return;
658
Chris Lattner0bd1c972007-10-16 21:07:07 +0000659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
Chandler Carruth35f53202011-07-25 16:49:02 +0000663 Loc = SM->getExpansionLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000664
Chris Lattner0bd1c972007-10-16 21:07:07 +0000665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000670 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000672 // declared in <Foundation/NSString.h>
Daniel Dunbar56df9772010-08-17 22:39:59 +0000673 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffa397efd2007-11-03 11:27:19 +0000674 ConstantStringClassReference = FVD;
675 return;
676 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000677 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
678 if (ID->isThisDeclarationADefinition())
679 RewriteInterfaceDecl(ID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000680 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000681 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000682 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000683 if (PD->isThisDeclarationADefinition())
684 RewriteProtocolDecl(PD);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000685 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
686 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000687 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
688 DIEnd = LSD->decls_end();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000689 DI != DIEnd; ) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000690 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
691 if (!IFace->isThisDeclarationADefinition()) {
692 SmallVector<Decl *, 8> DG;
693 SourceLocation StartLoc = IFace->getLocStart();
694 do {
695 if (isa<ObjCInterfaceDecl>(*DI) &&
696 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
697 StartLoc == (*DI)->getLocStart())
698 DG.push_back(*DI);
699 else
700 break;
701
Douglas Gregordc9166c2011-12-15 20:29:51 +0000702 ++DI;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000703 } while (DI != DIEnd);
704 RewriteForwardClassDecl(DG);
705 continue;
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000706 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000707 }
Douglas Gregorf6102672012-01-01 21:23:57 +0000708
709 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
710 if (!Proto->isThisDeclarationADefinition()) {
711 SmallVector<Decl *, 8> DG;
712 SourceLocation StartLoc = Proto->getLocStart();
713 do {
714 if (isa<ObjCProtocolDecl>(*DI) &&
715 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
716 StartLoc == (*DI)->getLocStart())
717 DG.push_back(*DI);
718 else
719 break;
720
721 ++DI;
722 } while (DI != DIEnd);
723 RewriteForwardProtocolDecl(DG);
724 continue;
725 }
726 }
727
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000728 HandleTopLevelSingleDecl(*DI);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000729 ++DI;
730 }
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000731 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000732 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000733 if (SM->isWrittenInMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000734 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000735}
736
Chris Lattner3c799d72007-10-24 17:06:59 +0000737//===----------------------------------------------------------------------===//
738// Syntactic (non-AST) Rewriting Code
739//===----------------------------------------------------------------------===//
740
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000741void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000742 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000743 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramereb92dc02010-03-16 14:14:31 +0000744 const char *MainBufStart = MainBuf.begin();
745 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian80258362008-01-19 00:30:35 +0000746 size_t ImportLen = strlen("import");
Mike Stump11289f42009-09-09 15:08:12 +0000747
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000748 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000749 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
750 if (*BufPtr == '#') {
751 if (++BufPtr == MainBufEnd)
752 return;
753 while (*BufPtr == ' ' || *BufPtr == '\t')
754 if (++BufPtr == MainBufEnd)
755 return;
756 if (!strncmp(BufPtr, "import", ImportLen)) {
757 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000758 SourceLocation ImportLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000759 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000760 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian80258362008-01-19 00:30:35 +0000761 BufPtr += ImportLen;
762 }
763 }
764 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000765}
766
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000767static std::string getIvarAccessString(ObjCIvarDecl *OID) {
768 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000769 std::string S;
770 S = "((struct ";
771 S += ClassDecl->getIdentifier()->getName();
772 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000773 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000774 return S;
775}
776
Steve Naroffc038b3a2008-12-02 17:36:43 +0000777void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
778 ObjCImplementationDecl *IMD,
779 ObjCCategoryImplDecl *CID) {
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000780 static bool objcGetPropertyDefined = false;
781 static bool objcSetPropertyDefined = false;
Steve Naroffe1908e32008-12-01 20:33:01 +0000782 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000783 InsertText(startLoc, "// ");
Steve Naroff9af94912008-12-02 15:48:25 +0000784 const char *startBuf = SM->getCharacterData(startLoc);
785 assert((*startBuf == '@') && "bogus @synthesize location");
786 const char *semiBuf = strchr(startBuf, ';');
787 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000788 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +0000789 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000790
791 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
792 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000793
Steve Naroff9af94912008-12-02 15:48:25 +0000794 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000795 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000796 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000797
Steve Naroff003d00e2008-12-02 16:05:55 +0000798 if (!OID)
799 return;
Bill Wendling44426052012-12-20 19:22:21 +0000800 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000801 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendling44426052012-12-20 19:22:21 +0000802 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
803 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000804 ObjCPropertyDecl::OBJC_PR_copy));
805 std::string Getr;
806 if (GenGetProperty && !objcGetPropertyDefined) {
807 objcGetPropertyDefined = true;
808 // FIXME. Is this attribute correct in all cases?
809 Getr = "\nextern \"C\" __declspec(dllimport) "
810 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000811 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000812 RewriteObjCMethodDecl(OID->getContainingInterface(),
813 PD->getGetterMethodDecl(), Getr);
814 Getr += "{ ";
815 // Synthesize an explicit cast to gain access to the ivar.
816 // See objc-act.c:objc_synthesize_new_getter() for details.
817 if (GenGetProperty) {
818 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
819 Getr += "typedef ";
820 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000821 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000822 FPRetType);
823 Getr += " _TYPE";
824 if (FPRetType) {
825 Getr += ")"; // close the precedence "scope" for "*".
826
827 // Now, emit the argument types (if any).
828 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
829 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000830 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000831 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000832 std::string ParamStr =
833 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000834 Getr += ParamStr;
835 }
836 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000837 if (FT->getNumParams())
838 Getr += ", ";
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000839 Getr += "...";
840 }
841 Getr += ")";
842 } else
843 Getr += "()";
844 }
845 Getr += ";\n";
846 Getr += "return (_TYPE)";
847 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000848 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000849 Getr += ", 1)";
850 }
851 else
852 Getr += "return " + getIvarAccessString(OID);
853 Getr += "; }";
854 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000855 }
Fariborz Jahanian7c299bc2010-10-19 23:47:54 +0000856
857 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroff9af94912008-12-02 15:48:25 +0000858 return;
Mike Stump11289f42009-09-09 15:08:12 +0000859
Steve Naroff9af94912008-12-02 15:48:25 +0000860 // Generate the 'setter' function.
861 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +0000862 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000863 ObjCPropertyDecl::OBJC_PR_copy);
864 if (GenSetProperty && !objcSetPropertyDefined) {
865 objcSetPropertyDefined = true;
866 // FIXME. Is this attribute correct in all cases?
867 Setr = "\nextern \"C\" __declspec(dllimport) "
868 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
869 }
870
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000871 RewriteObjCMethodDecl(OID->getContainingInterface(),
872 PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000873 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000874 // Synthesize an explicit cast to initialize the ivar.
Steve Narofff326f402008-12-03 00:56:33 +0000875 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000876 if (GenSetProperty) {
877 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian68e628e2011-12-05 18:43:13 +0000878 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000879 Setr += ", (id)";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000880 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000881 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +0000882 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000883 Setr += "0, ";
884 else
885 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +0000886 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000887 Setr += "1)";
888 else
889 Setr += "0)";
890 }
891 else {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +0000892 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar56df9772010-08-17 22:39:59 +0000893 Setr += PD->getName();
Fariborz Jahanianec201dc2010-02-26 01:42:20 +0000894 }
Steve Naroff003d00e2008-12-02 16:05:55 +0000895 Setr += "; }";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000896 InsertText(onePastSemiLoc, Setr);
Steve Naroffe1908e32008-12-01 20:33:01 +0000897}
Chris Lattner16a0de42007-10-11 18:38:32 +0000898
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000899static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
900 std::string &typedefString) {
901 typedefString += "#ifndef _REWRITER_typedef_";
902 typedefString += ForwardDecl->getNameAsString();
903 typedefString += "\n";
904 typedefString += "#define _REWRITER_typedef_";
905 typedefString += ForwardDecl->getNameAsString();
906 typedefString += "\n";
907 typedefString += "typedef struct objc_object ";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += ";\n#endif\n";
910}
911
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000912void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000913 const std::string &typedefString) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000914 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000915 const char *startBuf = SM->getCharacterData(startLoc);
916 const char *semiPtr = strchr(startBuf, ';');
917 // Replace the @class with typedefs corresponding to the classes.
918 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
919}
920
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000921void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000922 std::string typedefString;
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000923 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000924 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000925 if (I == D.begin()) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000926 // Translate to typedef's that forward reference structs with the same name
927 // as the class. As a convenience, we include the original declaration
928 // as a comment.
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000929 typedefString += "// @class ";
930 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian1c2cb6d2010-01-11 22:48:40 +0000931 typedefString += ";\n";
Fariborz Jahanian3a039e32011-08-27 20:50:59 +0000932 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000933 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff574440f2007-10-24 22:48:43 +0000934 }
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000935 DeclGroupRef::iterator I = D.begin();
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000936 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000937}
Mike Stump11289f42009-09-09 15:08:12 +0000938
Craig Topper5603df42013-07-05 19:34:19 +0000939void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000940 std::string typedefString;
941 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000942 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahanianabc11aa2011-08-29 22:21:46 +0000943 if (i == 0) {
944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
946 typedefString += ";\n";
947 }
948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
949 }
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000950 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattner3c799d72007-10-24 17:06:59 +0000951}
952
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000953void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000954 // When method is a synthesized one, such as a getter/setter there is
955 // nothing to rewrite.
Fariborz Jahaniane1378a42011-09-09 20:35:22 +0000956 if (Method->isImplicit())
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000957 return;
Steve Naroff3ce37a62007-12-14 23:37:57 +0000958 SourceLocation LocStart = Method->getLocStart();
959 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000960
Chandler Carruthd48db212011-07-25 21:09:52 +0000961 if (SM->getExpansionLineNumber(LocEnd) >
962 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000963 InsertText(LocStart, "#if 0\n");
964 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff3ce37a62007-12-14 23:37:57 +0000965 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000966 InsertText(LocStart, "// ");
Steve Naroff5448cf62007-10-30 13:30:57 +0000967 }
968}
969
Mike Stump11289f42009-09-09 15:08:12 +0000970void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahanianda8ec2b2010-01-21 17:36:00 +0000971 SourceLocation Loc = prop->getAtLoc();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000973 ReplaceText(Loc, 0, "// ");
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000974 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000975}
976
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000977void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000978 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000979
Steve Naroff5448cf62007-10-30 13:30:57 +0000980 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +0000982
Aaron Ballmand174edf2014-03-13 19:11:50 +0000983 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +0000984 RewriteProperty(I);
Fariborz Jahanian68ebe632010-02-10 01:15:09 +0000985
Aaron Ballmanf26acce2014-03-13 19:50:17 +0000986 for (auto *I : CatDecl->instance_methods())
987 RewriteMethodDeclaration(I);
Mike Stump11289f42009-09-09 15:08:12 +0000988 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000989 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000990 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000991 RewriteMethodDeclaration(*I);
992
Steve Naroff5448cf62007-10-30 13:30:57 +0000993 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +0000994 ReplaceText(CatDecl->getAtEndRange().getBegin(),
995 strlen("@end"), "/* @end */");
Steve Naroff5448cf62007-10-30 13:30:57 +0000996}
997
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000998void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Narofff921385f2007-10-30 16:42:30 +0000999 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00001000 assert(PDecl->isThisDeclarationADefinition());
1001
Steve Narofff921385f2007-10-30 16:42:30 +00001002 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001003 ReplaceText(LocStart, 0, "// ");
Mike Stump11289f42009-09-09 15:08:12 +00001004
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001005 for (auto *I : PDecl->instance_methods())
1006 RewriteMethodDeclaration(I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001007 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001008 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001009 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001010 RewriteMethodDeclaration(*I);
1011
Aaron Ballmand174edf2014-03-13 19:11:50 +00001012 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001013 RewriteProperty(I);
Fariborz Jahanianaa0f2b32010-09-24 18:36:58 +00001014
Steve Narofff921385f2007-10-30 16:42:30 +00001015 // Lastly, comment out the @end.
Ted Kremenekc7c64312010-01-07 01:20:12 +00001016 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001017 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroffa509f042007-11-14 15:03:57 +00001018
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001019 // Must comment out @optional/@required
1020 const char *startBuf = SM->getCharacterData(LocStart);
1021 const char *endBuf = SM->getCharacterData(LocEnd);
1022 for (const char *p = startBuf; p < endBuf; p++) {
1023 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001024 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001025 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump11289f42009-09-09 15:08:12 +00001026
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001027 }
1028 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001029 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001030 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump11289f42009-09-09 15:08:12 +00001031
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +00001032 }
1033 }
Steve Narofff921385f2007-10-30 16:42:30 +00001034}
1035
Douglas Gregorf6102672012-01-01 21:23:57 +00001036void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1037 SourceLocation LocStart = (*D.begin())->getLocStart();
1038 if (LocStart.isInvalid())
1039 llvm_unreachable("Invalid SourceLocation");
1040 // FIXME: handle forward protocol that are declared across multiple lines.
1041 ReplaceText(LocStart, 0, "// ");
1042}
1043
1044void
Craig Topper5603df42013-07-05 19:34:19 +00001045RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001046 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffc17b0562007-11-14 03:37:28 +00001047 if (LocStart.isInvalid())
David Blaikie83d382b2011-09-23 05:06:16 +00001048 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001049 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001050 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +00001051}
1052
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001053void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1054 const FunctionType *&FPRetType) {
1055 if (T->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +00001056 ResultStr += "id";
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001057 else if (T->isFunctionPointerType() ||
1058 T->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +00001059 // needs special handling, since pointer-to-functions have special
1060 // syntax (where a decaration models use).
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001061 QualType retType = T;
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001062 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001063 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001064 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001065 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001066 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001067 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001068 ResultStr +=
1069 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Naroff1fa7bd12008-12-11 19:29:16 +00001070 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +00001071 }
1072 } else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001073 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001074}
1075
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001076void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1077 ObjCMethodDecl *OMD,
Fariborz Jahanianec201dc2010-02-26 01:42:20 +00001078 std::string &ResultStr) {
1079 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1080 const FunctionType *FPRetType = 0;
1081 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001082 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian7262fca2008-01-10 01:39:52 +00001083 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +00001084
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001085 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +00001086 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001087
Douglas Gregorffca3a22009-01-09 17:18:27 +00001088 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +00001089 NameStr += "_I_";
1090 else
1091 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +00001092
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001093 NameStr += IDecl->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001094 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +00001095
1096 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +00001097 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001098 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +00001099 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001100 }
Mike Stump11289f42009-09-09 15:08:12 +00001101 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +00001102 {
1103 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001104 int len = selString.size();
1105 for (int i = 0; i < len; i++)
1106 if (selString[i] == ':')
1107 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +00001108 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001109 }
Fariborz Jahanian56338352007-11-13 21:02:00 +00001110 // Remember this name for metadata emission
1111 MethodInternalNames[OMD] = NameStr;
1112 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +00001113
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001114 // Rewrite arguments
1115 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +00001116
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001117 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +00001118 if (OMD->isInstanceMethod()) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001119 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001120 selfTy = Context->getPointerType(selfTy);
Francois Pichet0706d202011-09-17 17:15:52 +00001121 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001122 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroffdc5b6b22008-03-12 00:25:36 +00001123 ResultStr += "struct ";
1124 }
1125 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001126 ResultStr += IDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00001127 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001128 }
1129 else
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00001130 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregorc0b07282011-09-27 22:38:19 +00001131 Context->getPrintingPolicy());
Mike Stump11289f42009-09-09 15:08:12 +00001132
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001133 ResultStr += " self, ";
Douglas Gregorc0b07282011-09-27 22:38:19 +00001134 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001135 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +00001136
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001137 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001138 for (const auto *PDecl : OMD->params()) {
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
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001185 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001186 std::string ResultStr;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001187 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001188 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001189 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001190
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001191 const char *startBuf = SM->getCharacterData(LocStart);
1192 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001193 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001194 }
Mike Stump11289f42009-09-09 15:08:12 +00001195
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001196 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001197 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1198 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001199 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001200 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001201 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian1cee0ad2010-10-16 00:29:27 +00001202 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001203 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001204 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001205
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001208 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001209 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001210 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001211 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001212 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001213 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001214 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001215 }
1216
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001217 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001218}
1219
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001220void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001221 std::string ResultStr;
Douglas Gregordc9166c2011-12-15 20:29:51 +00001222 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001223 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001224 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001225 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001226 ResultStr += "\n";
1227 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001228 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001229 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001230 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001231 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001232 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001233 // Mark this typedef as having been generated.
Douglas Gregordc9166c2011-12-15 20:29:51 +00001234 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff2f55b982007-11-01 03:35:41 +00001235 }
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00001236 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001237
Aaron Ballmand174edf2014-03-13 19:11:50 +00001238 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001239 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001240 for (auto *I : ClassDecl->instance_methods())
1241 RewriteMethodDeclaration(I);
Mike Stump11289f42009-09-09 15:08:12 +00001242 for (ObjCInterfaceDecl::classmeth_iterator
1243 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001244 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001245 RewriteMethodDeclaration(*I);
1246
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001247 // Lastly, comment out the @end.
Fariborz Jahanian427ee8b2010-05-24 17:22:38 +00001248 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1249 "/* @end */");
Steve Naroff161a92b2007-10-26 20:53:56 +00001250}
1251
John McCallfe96e0b2011-11-06 09:01:30 +00001252Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1253 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001254
John McCallfe96e0b2011-11-06 09:01:30 +00001255 // We just magically know some things about the structure of this
1256 // expression.
1257 ObjCMessageExpr *OldMsg =
1258 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1259 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump11289f42009-09-09 15:08:12 +00001260
John McCallfe96e0b2011-11-06 09:01:30 +00001261 // Because the rewriter doesn't allow us to rewrite rewritten code,
1262 // we need to suppress rewriting the sub-statements.
1263 Expr *Base, *RHS;
1264 {
1265 DisableReplaceStmtScope S(*this);
1266
1267 // Rebuild the base expression if we have one.
1268 Base = 0;
1269 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1270 Base = OldMsg->getInstanceReceiver();
1271 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1272 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1273 }
1274
1275 // Rebuild the RHS.
1276 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1277 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1278 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1279 }
1280
1281 // TODO: avoid this copy.
1282 SmallVector<SourceLocation, 1> SelLocs;
1283 OldMsg->getSelectorLocs(SelLocs);
1284
Chad Rosier598f3d22012-01-06 20:05:14 +00001285 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001286 switch (OldMsg->getReceiverKind()) {
1287 case ObjCMessageExpr::Class:
1288 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1289 OldMsg->getValueKind(),
1290 OldMsg->getLeftLoc(),
1291 OldMsg->getClassReceiverTypeInfo(),
1292 OldMsg->getSelector(),
1293 SelLocs,
1294 OldMsg->getMethodDecl(),
1295 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001296 OldMsg->getRightLoc(),
1297 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001298 break;
1299
1300 case ObjCMessageExpr::Instance:
1301 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1302 OldMsg->getValueKind(),
1303 OldMsg->getLeftLoc(),
1304 Base,
1305 OldMsg->getSelector(),
1306 SelLocs,
1307 OldMsg->getMethodDecl(),
1308 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001309 OldMsg->getRightLoc(),
1310 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001311 break;
1312
1313 case ObjCMessageExpr::SuperClass:
1314 case ObjCMessageExpr::SuperInstance:
1315 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1316 OldMsg->getValueKind(),
1317 OldMsg->getLeftLoc(),
1318 OldMsg->getSuperLoc(),
1319 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1320 OldMsg->getSuperType(),
1321 OldMsg->getSelector(),
1322 SelLocs,
1323 OldMsg->getMethodDecl(),
1324 RHS,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001325 OldMsg->getRightLoc(),
1326 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001327 break;
1328 }
1329
1330 Stmt *Replacement = SynthMessageExpr(NewMsg);
1331 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1332 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001333}
1334
John McCallfe96e0b2011-11-06 09:01:30 +00001335Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1336 SourceRange OldRange = PseudoOp->getSourceRange();
1337
1338 // We just magically know some things about the structure of this
1339 // expression.
1340 ObjCMessageExpr *OldMsg =
1341 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1342
1343 // Because the rewriter doesn't allow us to rewrite rewritten code,
1344 // we need to suppress rewriting the sub-statements.
1345 Expr *Base = 0;
1346 {
1347 DisableReplaceStmtScope S(*this);
1348
1349 // Rebuild the base expression if we have one.
1350 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1351 Base = OldMsg->getInstanceReceiver();
1352 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1353 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCallb7bd14f2010-12-02 01:19:52 +00001354 }
Fariborz Jahanianbb40ea42010-10-20 16:07:20 +00001355 }
Steve Narofff326f402008-12-03 00:56:33 +00001356
John McCallfe96e0b2011-11-06 09:01:30 +00001357 // Intentionally empty.
1358 SmallVector<SourceLocation, 1> SelLocs;
1359 SmallVector<Expr*, 1> Args;
Steve Naroff1042ff32008-12-08 16:43:47 +00001360
Chad Rosier598f3d22012-01-06 20:05:14 +00001361 ObjCMessageExpr *NewMsg = 0;
John McCallfe96e0b2011-11-06 09:01:30 +00001362 switch (OldMsg->getReceiverKind()) {
1363 case ObjCMessageExpr::Class:
1364 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1365 OldMsg->getValueKind(),
1366 OldMsg->getLeftLoc(),
1367 OldMsg->getClassReceiverTypeInfo(),
1368 OldMsg->getSelector(),
1369 SelLocs,
1370 OldMsg->getMethodDecl(),
1371 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001372 OldMsg->getRightLoc(),
1373 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001374 break;
1375
1376 case ObjCMessageExpr::Instance:
1377 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1378 OldMsg->getValueKind(),
1379 OldMsg->getLeftLoc(),
1380 Base,
1381 OldMsg->getSelector(),
1382 SelLocs,
1383 OldMsg->getMethodDecl(),
1384 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001385 OldMsg->getRightLoc(),
1386 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001387 break;
1388
1389 case ObjCMessageExpr::SuperClass:
1390 case ObjCMessageExpr::SuperInstance:
1391 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1392 OldMsg->getValueKind(),
1393 OldMsg->getLeftLoc(),
1394 OldMsg->getSuperLoc(),
1395 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1396 OldMsg->getSuperType(),
1397 OldMsg->getSelector(),
1398 SelLocs,
1399 OldMsg->getMethodDecl(),
1400 Args,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001401 OldMsg->getRightLoc(),
1402 OldMsg->isImplicit());
John McCallfe96e0b2011-11-06 09:01:30 +00001403 break;
Steve Naroff1042ff32008-12-08 16:43:47 +00001404 }
John McCallfe96e0b2011-11-06 09:01:30 +00001405
1406 Stmt *Replacement = SynthMessageExpr(NewMsg);
1407 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1408 return Replacement;
Steve Narofff326f402008-12-03 00:56:33 +00001409}
1410
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001411/// SynthCountByEnumWithState - To print:
1412/// ((unsigned int (*)
1413/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001414/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001415/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001416/// "countByEnumeratingWithState:objects:count:"),
1417/// &enumState,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001418/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001419///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001420void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001421 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1422 "id *, unsigned int))(void *)objc_msgSend)";
1423 buf += "\n\t\t";
1424 buf += "((id)l_collection,\n\t\t";
1425 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1426 buf += "\n\t\t";
1427 buf += "&enumState, "
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001428 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001429}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001430
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001431/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1432/// statement to exit to its outer synthesized loop.
1433///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001434Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001435 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1436 return S;
1437 // replace break with goto __break_label
1438 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001439
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001440 SourceLocation startLoc = S->getLocStart();
1441 buf = "goto __break_label_";
1442 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001443 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001444
1445 return 0;
1446}
1447
1448/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1449/// statement to continue with its inner synthesized loop.
1450///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001451Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001452 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1453 return S;
1454 // replace continue with goto __continue_label
1455 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001456
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001457 SourceLocation startLoc = S->getLocStart();
1458 buf = "goto __continue_label_";
1459 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001460 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump11289f42009-09-09 15:08:12 +00001461
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001462 return 0;
1463}
1464
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001465/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001466/// It rewrites:
1467/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001468
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001469/// Into:
1470/// {
Mike Stump11289f42009-09-09 15:08:12 +00001471/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001472/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001473/// id __rw_items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001474/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001475/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001476/// objects:__rw_items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001477/// if (limit) {
1478/// unsigned long startMutations = *enumState.mutationsPtr;
1479/// do {
1480/// unsigned long counter = 0;
1481/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001482/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001483/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001484/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001485/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001486/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001487/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001488/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001489/// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001490/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001491/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001492/// }
1493/// else
1494/// elem = nil;
1495/// }
1496///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001497Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001498 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001499 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001500 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001501 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001502 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001503 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001504
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001505 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001506 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001507 StringRef elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001508 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001509 std::string buf;
1510 buf = "\n{\n\t";
1511 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1512 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001513 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001514 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001515 if (ElementType->isObjCQualifiedIdType() ||
1516 ElementType->isObjCQualifiedInterfaceType())
1517 // Simply use 'id' for all qualified types.
1518 elementTypeAsString = "id";
1519 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001520 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001521 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001522 buf += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00001523 elementName = D->getName();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001524 buf += elementName;
1525 buf += ";\n\t";
1526 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001527 else {
1528 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar56df9772010-08-17 22:39:59 +00001529 elementName = DR->getDecl()->getName();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001530 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1531 if (VD->getType()->isObjCQualifiedIdType() ||
1532 VD->getType()->isObjCQualifiedInterfaceType())
1533 // Simply use 'id' for all qualified types.
1534 elementTypeAsString = "id";
1535 else
Douglas Gregorc0b07282011-09-27 22:38:19 +00001536 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001539 // struct __objcFastEnumerationState enumState = { 0 };
1540 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001541 // id __rw_items[16];
1542 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001543 // id l_collection = (id)
1544 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001545 // Find start location of 'collection' the hard way!
1546 const char *startCollectionBuf = startBuf;
1547 startCollectionBuf += 3; // skip 'for'
1548 startCollectionBuf = strchr(startCollectionBuf, '(');
1549 startCollectionBuf++; // skip '('
1550 // find 'in' and skip it.
1551 while (*startCollectionBuf != ' ' ||
1552 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1553 (*(startCollectionBuf+3) != ' ' &&
1554 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1555 startCollectionBuf++;
1556 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001557
1558 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001559 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001560 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001561 SourceLocation rightParenLoc = S->getRParenLoc();
1562 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001563 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001564 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001565
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001566 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001567 // objects:__rw_items count:16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001568 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001569 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001570 // ((unsigned int (*)
1571 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001572 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001573 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001574 // "countByEnumeratingWithState:objects:count:"),
1575 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001576 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001577 buf += "unsigned long limit =\n\t\t";
1578 SynthCountByEnumWithState(buf);
1579 buf += ";\n\t";
1580 /// if (limit) {
1581 /// unsigned long startMutations = *enumState.mutationsPtr;
1582 /// do {
1583 /// unsigned long counter = 0;
1584 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001585 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001586 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001587 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001588 buf += "if (limit) {\n\t";
1589 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1590 buf += "do {\n\t\t";
1591 buf += "unsigned long counter = 0;\n\t\t";
1592 buf += "do {\n\t\t\t";
1593 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1594 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1595 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001596 buf += " = (";
1597 buf += elementTypeAsString;
1598 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001599 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001600 ReplaceText(lparenLoc, 1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001602 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001603 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001604 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahaniane0e65052011-11-09 17:41:43 +00001605 /// objects:__rw_items count:16]);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001606 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001607 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001608 /// }
1609 /// else
1610 /// elem = nil;
1611 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001612 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001613 buf = ";\n\t";
1614 buf += "__continue_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
1616 buf += ": ;";
1617 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001618 buf += "} while (counter < limit);\n\t";
1619 buf += "} while (limit = ";
1620 SynthCountByEnumWithState(buf);
1621 buf += ");\n\t";
1622 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001623 buf += " = ((";
1624 buf += elementTypeAsString;
1625 buf += ")0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001626 buf += "__break_label_";
1627 buf += utostr(ObjCBcLabelNo.back());
1628 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001629 buf += "}\n\t";
1630 buf += "else\n\t\t";
1631 buf += elementName;
Fariborz Jahanian39d70942010-01-08 01:29:44 +00001632 buf += " = ((";
1633 buf += elementTypeAsString;
1634 buf += ")0);\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001635 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001636
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001637 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001638 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001639 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001640 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001641 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001642 } else {
1643 /* Need to treat single statements specially. For example:
1644 *
1645 * for (A *a in b) if (stuff()) break;
1646 * for (A *a in b) xxxyy;
1647 *
1648 * The following code simply scans ahead to the semi to find the actual end.
1649 */
1650 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1651 const char *semiBuf = strchr(stmtBuf, ';');
1652 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001653 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001654 InsertText(endBodyLoc, buf);
Steve Narofff0ff8792008-07-21 18:26:02 +00001655 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001656 Stmts.pop_back();
1657 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001658 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001659}
1660
Mike Stump11289f42009-09-09 15:08:12 +00001661/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001662/// This routine rewrites @synchronized(expr) stmt;
1663/// into:
1664/// objc_sync_enter(expr);
1665/// @try stmt @finally { objc_sync_exit(expr); }
1666///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001667Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001668 // Get the start location and compute the semi location.
1669 SourceLocation startLoc = S->getLocStart();
1670 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001671
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001672 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001673
1674 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001675 buf = "objc_sync_enter((id)";
1676 const char *lparenBuf = startBuf;
1677 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001678 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001679 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1680 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001681 // been rewritten! (which implies the SourceLocation's are invalid).
1682 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001683 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001684 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001685 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001686 buf = ");\n";
1687 // declare a new scope with two variables, _stack and _rethrow.
1688 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1689 buf += "int buf[18/*32-bit i386*/];\n";
1690 buf += "char *pointers[4];} _stack;\n";
1691 buf += "id volatile _rethrow = 0;\n";
1692 buf += "objc_exception_try_enter(&_stack);\n";
1693 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001694 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001695 startLoc = S->getSynchBody()->getLocEnd();
1696 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Steve Naroffad7013b2008-08-19 13:04:19 +00001698 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001699 SourceLocation lastCurlyLoc = startLoc;
1700 buf = "}\nelse {\n";
1701 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001702 buf += "}\n";
1703 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001704 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001705
1706 std::string syncBuf;
1707 syncBuf += " objc_sync_exit(";
John McCall9320b872011-09-09 05:25:32 +00001708
1709 Expr *syncExpr = S->getSynchExpr();
1710 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1711 ? CK_BitCast :
1712 syncExpr->getType()->isBlockPointerType()
1713 ? CK_BlockPointerToObjCPointerCast
1714 : CK_CPointerToObjCPointerCast;
1715 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1716 CK, syncExpr);
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001717 std::string syncExprBufS;
1718 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Richard Smith235341b2012-08-16 03:56:14 +00001719 syncExpr->printPretty(syncExprBuf, 0, PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001720 syncBuf += syncExprBuf.str();
1721 syncBuf += ");";
1722
1723 buf += syncBuf;
1724 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001725 buf += "}\n";
1726 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001727
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001728 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001729
1730 bool hasReturns = false;
1731 HasReturnStmts(S->getSynchBody(), hasReturns);
1732 if (hasReturns)
1733 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1734
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001735 return 0;
1736}
1737
Steve Naroffec60b432009-12-05 21:43:12 +00001738void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1739{
Steve Naroff6d6da252008-12-05 17:03:39 +00001740 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001741 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff6d6da252008-12-05 17:03:39 +00001742 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001743 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001744
Steve Naroffec60b432009-12-05 21:43:12 +00001745 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001746 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001747 TryFinallyContainsReturnDiag);
1748 }
1749 return;
1750}
1751
Steve Naroffec60b432009-12-05 21:43:12 +00001752void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1753{
1754 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001755 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001756 if (*CI)
1757 HasReturnStmts(*CI, hasReturns);
1758
1759 if (isa<ReturnStmt>(S))
1760 hasReturns = true;
1761 return;
1762}
1763
1764void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1765 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001766 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001767 if (*CI) {
1768 RewriteTryReturnStmts(*CI);
1769 }
1770 if (isa<ReturnStmt>(S)) {
1771 SourceLocation startLoc = S->getLocStart();
1772 const char *startBuf = SM->getCharacterData(startLoc);
1773
1774 const char *semiBuf = strchr(startBuf, ';');
1775 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001776 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001777
1778 std::string buf;
1779 buf = "{ objc_exception_try_exit(&_stack); return";
1780
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001781 ReplaceText(startLoc, 6, buf);
1782 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001783 }
1784 return;
1785}
1786
1787void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1788 // Perform a bottom up traversal of all children.
John McCall8322c3a2011-02-13 04:07:26 +00001789 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001790 if (*CI) {
1791 RewriteSyncReturnStmts(*CI, syncExitBuf);
1792 }
1793 if (isa<ReturnStmt>(S)) {
1794 SourceLocation startLoc = S->getLocStart();
1795 const char *startBuf = SM->getCharacterData(startLoc);
1796
1797 const char *semiBuf = strchr(startBuf, ';');
1798 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001799 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffec60b432009-12-05 21:43:12 +00001800
1801 std::string buf;
1802 buf = "{ objc_exception_try_exit(&_stack);";
1803 buf += syncExitBuf;
1804 buf += " return";
1805
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001806 ReplaceText(startLoc, 6, buf);
1807 InsertText(onePastSemiLoc, "}");
Steve Naroffec60b432009-12-05 21:43:12 +00001808 }
1809 return;
1810}
1811
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001812Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001813 // Get the start location and compute the semi location.
1814 SourceLocation startLoc = S->getLocStart();
1815 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001816
Steve Naroffbf478ec2007-11-07 04:08:17 +00001817 assert((*startBuf == '@') && "bogus @try location");
1818
1819 std::string buf;
1820 // declare a new scope with two variables, _stack and _rethrow.
1821 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1822 buf += "int buf[18/*32-bit i386*/];\n";
1823 buf += "char *pointers[4];} _stack;\n";
1824 buf += "id volatile _rethrow = 0;\n";
1825 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001826 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001827
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001828 ReplaceText(startLoc, 4, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Steve Naroffbf478ec2007-11-07 04:08:17 +00001830 startLoc = S->getTryBody()->getLocEnd();
1831 startBuf = SM->getCharacterData(startLoc);
1832
1833 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001834
Steve Naroffbf478ec2007-11-07 04:08:17 +00001835 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor96c79492010-04-23 22:50:49 +00001836 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001837 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffce2dca12008-07-16 15:31:30 +00001838 buf = " /* @catch begin */ else {\n";
1839 buf += " id _caught = objc_exception_extract(&_stack);\n";
1840 buf += " objc_exception_try_enter (&_stack);\n";
1841 buf += " if (_setjmp(_stack.buf))\n";
1842 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1843 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001844
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001845 InsertText(startLoc, buf);
Steve Narofffac18fe2008-09-09 19:59:12 +00001846 } else { /* no catch list */
1847 buf = "}\nelse {\n";
1848 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1849 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001850 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffce2dca12008-07-16 15:31:30 +00001851 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001852 Stmt *lastCatchBody = 0;
Douglas Gregor96c79492010-04-23 22:50:49 +00001853 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1854 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregor46a572b2010-04-26 16:46:50 +00001855 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001856
Douglas Gregor96c79492010-04-23 22:50:49 +00001857 if (I == 0)
Steve Naroffbf478ec2007-11-07 04:08:17 +00001858 buf = "if ("; // we are generating code for the first catch clause
1859 else
1860 buf = "else if (";
Douglas Gregor96c79492010-04-23 22:50:49 +00001861 startLoc = Catch->getLocStart();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001862 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001863
Steve Naroffbf478ec2007-11-07 04:08:17 +00001864 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001865
Steve Naroffbf478ec2007-11-07 04:08:17 +00001866 const char *lParenLoc = strchr(startBuf, '(');
1867
Douglas Gregor96c79492010-04-23 22:50:49 +00001868 if (Catch->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001869 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001870 lastCatchBody = Catch->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001871 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1872 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor96c79492010-04-23 22:50:49 +00001873 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001874 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001875 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001876
Steve Naroffedb5bc62008-02-01 20:02:07 +00001877 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001878 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001879 } else if (catchDecl) {
1880 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001881 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001882 buf += "1) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001883 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall96fa4842010-05-17 21:00:27 +00001884 } else if (const ObjCObjectPointerType *Ptr =
1885 t->getAs<ObjCObjectPointerType>()) {
1886 // Should be a pointer to a class.
1887 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1888 if (IDecl) {
Steve Naroff16018582007-11-07 18:43:40 +00001889 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall96fa4842010-05-17 21:00:27 +00001890 buf += IDecl->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001891 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001892 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroffbf478ec2007-11-07 04:08:17 +00001893 }
1894 }
1895 // Now rewrite the body...
Douglas Gregor96c79492010-04-23 22:50:49 +00001896 lastCatchBody = Catch->getCatchBody();
1897 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001898 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1899 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1900 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1901 assert((*rParenBuf == ')') && "bogus @catch paren location");
1902 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001903
Mike Stump11289f42009-09-09 15:08:12 +00001904 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001905 // declares the @catch parameter).
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001906 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff371b8fb2009-03-03 19:52:17 +00001907 } else {
David Blaikie83d382b2011-09-23 05:06:16 +00001908 llvm_unreachable("@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001909 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001910 }
1911 // Complete the catch list...
1912 if (lastCatchBody) {
1913 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001914 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1915 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001916
Steve Naroff4adbe312008-09-11 15:29:03 +00001917 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001918 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff4adbe312008-09-11 15:29:03 +00001919 buf = "} /* last catch end */\n";
1920 buf += "else {\n";
1921 buf += " _rethrow = _caught;\n";
1922 buf += " objc_exception_try_exit(&_stack);\n";
1923 buf += "} } /* @catch end */\n";
1924 if (!S->getFinallyStmt())
1925 buf += "}\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001926 InsertText(bodyLoc, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001927
Steve Naroffbf478ec2007-11-07 04:08:17 +00001928 // Set lastCurlyLoc
1929 lastCurlyLoc = lastCatchBody->getLocEnd();
1930 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001931 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001932 startLoc = finalStmt->getLocStart();
1933 startBuf = SM->getCharacterData(startLoc);
1934 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001935
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001936 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump11289f42009-09-09 15:08:12 +00001937
Steve Naroffbf478ec2007-11-07 04:08:17 +00001938 Stmt *body = finalStmt->getFinallyBody();
1939 SourceLocation startLoc = body->getLocStart();
1940 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001941 assert(*SM->getCharacterData(startLoc) == '{' &&
1942 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001943 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001944 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001945
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001946 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001947 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001948 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001949 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump11289f42009-09-09 15:08:12 +00001950
Steve Naroffbf478ec2007-11-07 04:08:17 +00001951 // Set lastCurlyLoc
1952 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001953
Steve Naroff6d6da252008-12-05 17:03:39 +00001954 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001955 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001956 } else { /* no finally clause - make sure we synthesize an implicit one */
1957 buf = "{ /* implicit finally clause */\n";
1958 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1959 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1960 buf += "}";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001961 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffec60b432009-12-05 21:43:12 +00001962
1963 // Now check for any return/continue/go statements within the @try.
1964 // The implicit finally clause won't called if the @try contains any
1965 // jump statements.
1966 bool hasReturns = false;
1967 HasReturnStmts(S->getTryBody(), hasReturns);
1968 if (hasReturns)
1969 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001970 }
1971 // Now emit the final closing curly brace...
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001972 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001973 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001974 return 0;
1975}
1976
Mike Stump11289f42009-09-09 15:08:12 +00001977// This can't be done with ReplaceStmt(S, ThrowExpr), since
1978// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001979// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001981 // Get the start location and compute the semi location.
1982 SourceLocation startLoc = S->getLocStart();
1983 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001984
Steve Naroffa733c7f2007-11-07 15:32:26 +00001985 assert((*startBuf == '@') && "bogus @throw location");
1986
1987 std::string buf;
1988 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001989 if (S->getThrowExpr())
1990 buf = "objc_exception_throw(";
1991 else // add an implicit argument
1992 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001993
Steve Naroff29788342008-07-25 15:41:30 +00001994 // handle "@ throw" correctly.
1995 const char *wBuf = strchr(startBuf, 'w');
1996 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00001997 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump11289f42009-09-09 15:08:12 +00001998
Steve Naroffa733c7f2007-11-07 15:32:26 +00001999 const char *semiBuf = strchr(startBuf, ';');
2000 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002001 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002002 ReplaceText(semiLoc, 1, ");");
Steve Naroffa733c7f2007-11-07 15:32:26 +00002003 return 0;
2004}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00002005
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002006Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00002007 // Create a new string expression.
Anders Carlssond8499822007-10-29 05:01:08 +00002008 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00002009 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002010 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002011 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00002012
Chris Lattner4431a1b2007-11-30 22:53:43 +00002013 // Replace this subexpr in the parent.
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002014 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00002015 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00002016}
2017
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002018Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00002019 if (!SelGetUidFunctionDecl)
2020 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00002021 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2022 // Create a call to sel_registerName("selName").
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002023 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002024 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00002025 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2026 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002027 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002028 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00002029 return SelExp;
2030}
2031
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002032CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002033 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2034 SourceLocation EndLoc) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002035 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00002036 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002037
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002038 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002039 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2040 VK_LValue, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002041
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002042 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00002043 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson975979382010-04-23 22:18:37 +00002044 ImplicitCastExpr *ICE =
John McCallf608deb2010-11-15 09:46:46 +00002045 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00002046 DRE, 0, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCall9dd450b2009-09-21 23:43:11 +00002048 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00002049
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002050 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002051 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCall7decc9e2010-11-18 06:31:45 +00002052 FT->getCallResultType(*Context),
2053 VK_RValue, EndLoc);
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002054 return Exp;
Steve Naroff574440f2007-10-24 22:48:43 +00002055}
2056
Steve Naroff50d42052007-11-01 13:24:47 +00002057static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2058 const char *&startRef, const char *&endRef) {
2059 while (startBuf < endBuf) {
2060 if (*startBuf == '<')
2061 startRef = startBuf; // mark the start.
2062 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00002063 if (startRef && *startRef == '<') {
2064 endRef = startBuf; // mark the end.
2065 return true;
2066 }
2067 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002068 }
2069 startBuf++;
2070 }
2071 return false;
2072}
2073
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002074static void scanToNextArgument(const char *&argRef) {
2075 int angle = 0;
2076 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2077 if (*argRef == '<')
2078 angle++;
2079 else if (*argRef == '>')
2080 angle--;
2081 argRef++;
2082 }
2083 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2084}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002085
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002086bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian80c54b02010-02-03 21:29:28 +00002087 if (T->isObjCQualifiedIdType())
2088 return true;
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002089 if (const PointerType *PT = T->getAs<PointerType>()) {
2090 if (PT->getPointeeType()->isObjCQualifiedIdType())
2091 return true;
2092 }
2093 if (T->isObjCObjectPointerType()) {
2094 T = T->getPointeeType();
2095 return T->isObjCQualifiedInterfaceType();
2096 }
Fariborz Jahanian7bf13c42010-09-30 20:41:32 +00002097 if (T->isArrayType()) {
2098 QualType ElemTy = Context->getBaseElementType(T);
2099 return needToScanForQualifiers(ElemTy);
2100 }
Fariborz Jahanian06769f92010-02-02 18:35:07 +00002101 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00002102}
2103
Steve Naroff873bd842008-07-29 18:15:38 +00002104void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2105 QualType Type = E->getType();
2106 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00002107 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00002108
Steve Naroffdbfc6932008-11-19 21:15:47 +00002109 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2110 Loc = ECE->getLParenLoc();
2111 EndLoc = ECE->getRParenLoc();
2112 } else {
2113 Loc = E->getLocStart();
2114 EndLoc = E->getLocEnd();
2115 }
2116 // This will defend against trying to rewrite synthesized expressions.
2117 if (Loc.isInvalid() || EndLoc.isInvalid())
2118 return;
2119
Steve Naroff873bd842008-07-29 18:15:38 +00002120 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00002121 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00002122 const char *startRef = 0, *endRef = 0;
2123 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2124 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002125 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2126 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff873bd842008-07-29 18:15:38 +00002127 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002128 InsertText(LessLoc, "/*");
2129 InsertText(GreaterLoc, "*/");
Steve Naroff873bd842008-07-29 18:15:38 +00002130 }
2131 }
2132}
2133
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002134void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002135 SourceLocation Loc;
2136 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002137 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002138 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2139 Loc = VD->getLocation();
2140 Type = VD->getType();
2141 }
2142 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2143 Loc = FD->getLocation();
2144 // Check for ObjC 'id' and class types that have been adorned with protocol
2145 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00002146 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002147 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002148 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002149 if (!proto)
2150 return;
Alp Toker314cc812014-01-25 16:55:45 +00002151 Type = proto->getReturnType();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002152 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00002153 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2154 Loc = FD->getLocation();
2155 Type = FD->getType();
2156 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002157 else
2158 return;
Mike Stump11289f42009-09-09 15:08:12 +00002159
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002160 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00002161 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002162
Steve Naroff50d42052007-11-01 13:24:47 +00002163 const char *endBuf = SM->getCharacterData(Loc);
2164 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002165 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002166 startBuf--; // scan backward (from the decl location) for return type.
2167 const char *startRef = 0, *endRef = 0;
2168 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2169 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002170 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2171 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002172 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002173 InsertText(LessLoc, "/*");
2174 InsertText(GreaterLoc, "*/");
Steve Naroff37e011c2007-10-31 04:38:33 +00002175 }
2176 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002177 if (!proto)
2178 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002179 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002180 const char *startBuf = SM->getCharacterData(Loc);
2181 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002182 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2183 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroff50d42052007-11-01 13:24:47 +00002184 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002185
Steve Naroff50d42052007-11-01 13:24:47 +00002186 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002187 // scan forward (from the decl location) for argument types.
2188 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002189 const char *startRef = 0, *endRef = 0;
2190 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2191 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002192 SourceLocation LessLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002193 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002194 SourceLocation GreaterLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002195 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002196 // Comment out the protocol references.
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002197 InsertText(LessLoc, "/*");
2198 InsertText(GreaterLoc, "*/");
Steve Naroff50d42052007-11-01 13:24:47 +00002199 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002200 startBuf = ++endBuf;
2201 }
2202 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002203 // If the function name is derived from a macro expansion, then the
2204 // argument buffer will not follow the name. Need to speak with Chris.
2205 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002206 startBuf++; // scan forward (from the decl location) for argument types.
2207 startBuf++;
2208 }
Steve Naroff50d42052007-11-01 13:24:47 +00002209 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002210}
2211
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002212void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2213 QualType QT = ND->getType();
2214 const Type* TypePtr = QT->getAs<Type>();
2215 if (!isa<TypeOfExprType>(TypePtr))
2216 return;
2217 while (isa<TypeOfExprType>(TypePtr)) {
2218 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2219 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2220 TypePtr = QT->getAs<Type>();
2221 }
2222 // FIXME. This will not work for multiple declarators; as in:
2223 // __typeof__(a) b,c,d;
Douglas Gregorc0b07282011-09-27 22:38:19 +00002224 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002225 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2226 const char *startBuf = SM->getCharacterData(DeclLoc);
2227 if (ND->getInit()) {
2228 std::string Name(ND->getNameAsString());
2229 TypeAsString += " " + Name + " = ";
2230 Expr *E = ND->getInit();
2231 SourceLocation startLoc;
2232 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2233 startLoc = ECE->getLParenLoc();
2234 else
2235 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00002236 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002237 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002238 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002239 }
2240 else {
2241 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00002242 X = SM->getExpansionLoc(X);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002243 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002244 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00002245 }
2246}
2247
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002248// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002249void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002250 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002251 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002252 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002253 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002254 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002255 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002256 SourceLocation(),
2257 SourceLocation(),
2258 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002259 SC_Extern);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002260}
2261
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002262void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002263 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002264 if (FD->getIdentifier() &&
Daniel Dunbar56df9772010-08-17 22:39:59 +00002265 FD->getName() == "sel_registerName") {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002266 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002267 return;
2268 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002269 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002270}
2271
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002272void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregorc0b07282011-09-27 22:38:19 +00002273 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002274 const char *argPtr = TypeString.c_str();
2275 if (!strchr(argPtr, '^')) {
2276 Str += TypeString;
2277 return;
2278 }
2279 while (*argPtr) {
2280 Str += (*argPtr == '^' ? '*' : *argPtr);
2281 argPtr++;
2282 }
2283}
2284
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002285// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbar8ab6c542010-06-30 19:16:53 +00002286void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2287 ValueDecl *VD) {
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002288 QualType Type = VD->getType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002289 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00002290 const char *argPtr = TypeString.c_str();
2291 int paren = 0;
2292 while (*argPtr) {
2293 switch (*argPtr) {
2294 case '(':
2295 Str += *argPtr;
2296 paren++;
2297 break;
2298 case ')':
2299 Str += *argPtr;
2300 paren--;
2301 break;
2302 case '^':
2303 Str += '*';
2304 if (paren == 1)
2305 Str += VD->getNameAsString();
2306 break;
2307 default:
2308 Str += *argPtr;
2309 break;
2310 }
2311 argPtr++;
2312 }
2313}
2314
2315
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002316void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2317 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2318 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2319 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2320 if (!proto)
2321 return;
Alp Toker314cc812014-01-25 16:55:45 +00002322 QualType Type = proto->getReturnType();
Douglas Gregorc0b07282011-09-27 22:38:19 +00002323 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002324 FdStr += " ";
Daniel Dunbar56df9772010-08-17 22:39:59 +00002325 FdStr += FD->getName();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002326 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002327 unsigned numArgs = proto->getNumParams();
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002328 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002329 QualType ArgType = proto->getParamType(i);
Fariborz Jahaniana459c442010-02-12 17:52:31 +00002330 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002331 if (i+1 < numArgs)
2332 FdStr += ", ";
2333 }
2334 FdStr += ");\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00002335 InsertText(FunLocStart, FdStr);
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00002336 CurFunctionDeclToDeclareForBlock = 0;
2337}
2338
Benjamin Kramer60509af2013-09-09 14:48:42 +00002339// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2340void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2341 if (SuperConstructorFunctionDecl)
Steve Naroff17978c42008-03-11 17:37:02 +00002342 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002343 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002344 SmallVector<QualType, 16> ArgTys;
Steve Naroff17978c42008-03-11 17:37:02 +00002345 QualType argT = Context->getObjCIdType();
2346 assert(!argT.isNull() && "Can't find 'id' type");
2347 ArgTys.push_back(argT);
2348 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002349 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002350 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002351 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002352 SourceLocation(),
2353 SourceLocation(),
2354 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002355 0, SC_Extern);
Steve Naroff17978c42008-03-11 17:37:02 +00002356}
2357
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002358// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002359void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002360 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002361 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002362 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002363 assert(!argT.isNull() && "Can't find 'id' type");
2364 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002365 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002366 assert(!argT.isNull() && "Can't find 'SEL' type");
2367 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002368 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002369 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002370 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002371 SourceLocation(),
2372 SourceLocation(),
2373 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002374 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002375}
2376
Steve Naroff7fa2f042007-11-15 10:28:18 +00002377// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002378void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002379 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002380 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002381 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002382 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002383 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002384 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2385 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2386 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002387 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002388 assert(!argT.isNull() && "Can't find 'SEL' type");
2389 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002390 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002391 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002392 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002393 SourceLocation(),
2394 SourceLocation(),
2395 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002396 SC_Extern);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002397}
2398
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002399// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002400void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002401 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002402 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002403 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002404 assert(!argT.isNull() && "Can't find 'id' type");
2405 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002406 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002407 assert(!argT.isNull() && "Can't find 'SEL' type");
2408 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002409 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002410 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002411 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002412 SourceLocation(),
2413 SourceLocation(),
2414 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002415 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002416}
2417
Mike Stump11289f42009-09-09 15:08:12 +00002418// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002419// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002420void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002421 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002422 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002423 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara6150c882010-05-11 21:36:43 +00002424 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002425 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002426 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002427 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2428 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2429 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002430 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002431 assert(!argT.isNull() && "Can't find 'SEL' type");
2432 ArgTys.push_back(argT);
Fariborz Jahanianff4d5e42011-10-11 23:02:37 +00002433 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002434 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002435 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002436 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002437 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002438 msgSendIdent,
2439 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002440 SC_Extern);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002441}
2442
Steve Naroff2e4e3852008-05-08 22:02:18 +00002443// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002444void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002445 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002446 SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002447 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002448 assert(!argT.isNull() && "Can't find 'id' type");
2449 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002450 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002451 assert(!argT.isNull() && "Can't find 'SEL' type");
2452 ArgTys.push_back(argT);
John McCalldb40c7f2010-12-14 08:05:40 +00002453 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002454 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002455 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002456 SourceLocation(),
2457 SourceLocation(),
2458 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002459 SC_Extern);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002460}
2461
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002462// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002463void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002464 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002465 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002466 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002467 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002468 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002469 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002470 SourceLocation(),
2471 SourceLocation(),
2472 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002473 SC_Extern);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002474}
2475
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002476// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2477void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2478 IdentifierInfo *getSuperClassIdent =
2479 &Context->Idents.get("class_getSuperclass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002480 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002481 ArgTys.push_back(Context->getObjCClassType());
John McCalldb40c7f2010-12-14 08:05:40 +00002482 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002483 ArgTys);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002484 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002485 SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002486 SourceLocation(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002487 getSuperClassIdent,
2488 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002489 SC_Extern);
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002490}
2491
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002492// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002493void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002494 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002495 SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002496 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalldb40c7f2010-12-14 08:05:40 +00002497 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002498 ArgTys);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002499 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002500 SourceLocation(),
2501 SourceLocation(),
2502 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002503 0, SC_Extern);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002504}
2505
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002506Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002507 QualType strType = getConstantStringStructType();
2508
2509 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002510
2511 std::string tmpName = InFileName;
2512 unsigned i;
2513 for (i=0; i < tmpName.length(); i++) {
2514 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002515 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002516 if (!isAlphanumeric(c))
Steve Naroffa6141f02008-05-31 03:35:42 +00002517 tmpName[i] = '_';
2518 }
2519 S += tmpName;
2520 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002521 S += utostr(NumObjCStringLiterals++);
2522
Steve Naroff00a31762008-03-27 22:29:16 +00002523 Preamble += "static __NSConstantStringImpl " + S;
2524 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2525 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002526 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002527 std::string prettyBufS;
2528 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002529 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002530 Preamble += prettyBuf.str();
2531 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002532 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002533
2534 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00002535 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002536 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002537 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002538 SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00002539 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002540 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002541 VK_RValue, OK_Ordinary,
2542 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002543 // cast to NSConstantString *
John McCall97513962010-01-15 18:39:57 +00002544 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall9320b872011-09-09 05:25:32 +00002545 CK_CPointerToObjCPointerCast, Unop);
Chris Lattner2e0d2602008-01-31 19:37:57 +00002546 ReplaceStmt(Exp, cast);
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002547 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002548 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002549}
2550
Steve Naroff7fa2f042007-11-15 10:28:18 +00002551// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002552QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002553 if (!SuperStructDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002554 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002555 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002556 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002557 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002558
Steve Naroff7fa2f042007-11-15 10:28:18 +00002559 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002560 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002561 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002562 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002563
Steve Naroff7fa2f042007-11-15 10:28:18 +00002564 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002565 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002566 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002567 SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002568 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002569 FieldTypes[i], 0,
2570 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002571 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00002572 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002573 }
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregord5058122010-02-11 01:19:42 +00002575 SuperStructDecl->completeDefinition();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002576 }
2577 return Context->getTagDeclType(SuperStructDecl);
2578}
2579
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002580QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002581 if (!ConstantStringDecl) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00002582 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002583 SourceLocation(), SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002584 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002585 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002586
Steve Naroffce8e8862008-03-15 00:55:56 +00002587 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002588 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002589 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002590 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002591 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002592 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002593 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002594 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002595
Steve Naroffce8e8862008-03-15 00:55:56 +00002596 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002597 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002598 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2599 ConstantStringDecl,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002600 SourceLocation(),
Douglas Gregor91f84212008-12-11 16:49:14 +00002601 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002602 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002603 /*BitWidth=*/0,
Richard Smith938f40b2011-06-11 17:19:42 +00002604 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002605 ICIS_NoInit));
Douglas Gregor91f84212008-12-11 16:49:14 +00002606 }
2607
Douglas Gregord5058122010-02-11 01:19:42 +00002608 ConstantStringDecl->completeDefinition();
Steve Naroffce8e8862008-03-15 00:55:56 +00002609 }
2610 return Context->getTagDeclType(ConstantStringDecl);
2611}
2612
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002613CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2614 QualType msgSendType,
2615 QualType returnType,
2616 SmallVectorImpl<QualType> &ArgTypes,
2617 SmallVectorImpl<Expr*> &MsgExprs,
2618 ObjCMethodDecl *Method) {
2619 // Create a reference to the objc_msgSend_stret() declaration.
2620 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2621 false, msgSendType,
2622 VK_LValue, SourceLocation());
2623 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2624 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2625 Context->getPointerType(Context->VoidTy),
2626 CK_BitCast, STDRE);
2627 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002628 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2629 Method ? Method->isVariadic()
2630 : false);
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002631 castType = Context->getPointerType(castType);
2632 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2633 cast);
2634
2635 // Don't forget the parens to enforce the proper binding.
2636 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2637
2638 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002639 CallExpr *STCE = new (Context) CallExpr(
2640 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00002641 return STCE;
2642
2643}
2644
2645
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002646Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2647 SourceLocation StartLoc,
2648 SourceLocation EndLoc) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002649 if (!SelGetUidFunctionDecl)
2650 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002651 if (!MsgSendFunctionDecl)
2652 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002653 if (!MsgSendSuperFunctionDecl)
2654 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002655 if (!MsgSendStretFunctionDecl)
2656 SynthMsgSendStretFunctionDecl();
2657 if (!MsgSendSuperStretFunctionDecl)
2658 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002659 if (!MsgSendFpretFunctionDecl)
2660 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002661 if (!GetClassFunctionDecl)
2662 SynthGetClassFunctionDecl();
Fariborz Jahaniana4a925f2010-03-10 21:17:41 +00002663 if (!GetSuperClassFunctionDecl)
2664 SynthGetSuperClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002665 if (!GetMetaClassFunctionDecl)
2666 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002667
Steve Naroff7fa2f042007-11-15 10:28:18 +00002668 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002669 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2670 // May need to use objc_msgSend_stret() as well.
2671 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002672 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00002673 QualType resultType = mDecl->getReturnType();
Douglas Gregor8385a062010-04-26 21:31:17 +00002674 if (resultType->isRecordType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002675 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002676 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002677 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002678 }
Mike Stump11289f42009-09-09 15:08:12 +00002679
Steve Naroff574440f2007-10-24 22:48:43 +00002680 // Synthesize a call to objc_msgSend().
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002681 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002682 switch (Exp->getReceiverKind()) {
2683 case ObjCMessageExpr::SuperClass: {
2684 MsgSendFlavor = MsgSendSuperFunctionDecl;
2685 if (MsgSendStretFlavor)
2686 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2687 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregor9a129192010-04-21 00:45:42 +00002689 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00002690
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 SmallVector<Expr*, 4> InitExprs;
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002692
Douglas Gregor9a129192010-04-21 00:45:42 +00002693 // set the receiver to self, the first argument to all methods.
2694 InitExprs.push_back(
2695 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002696 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002697 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002698 false,
John McCall7decc9e2010-11-18 06:31:45 +00002699 Context->getObjCIdType(),
2700 VK_RValue,
2701 SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002702 ); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002703
Douglas Gregor9a129192010-04-21 00:45:42 +00002704 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002705 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002706 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002707 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2708 &ClsExprs[0],
2709 ClsExprs.size(),
2710 StartLoc,
2711 EndLoc);
2712 // (Class)objc_getClass("CurrentClass")
2713 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2714 Context->getObjCClassType(),
Fariborz Jahaniana4b2a862011-12-21 19:48:07 +00002715 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002716 ClsExprs.clear();
2717 ClsExprs.push_back(ArgExpr);
2718 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2719 &ClsExprs[0], ClsExprs.size(),
2720 StartLoc, EndLoc);
2721
2722 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2723 // To turn off a warning, type-cast to 'id'
2724 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2725 NoTypeInfoCStyleCastExpr(Context,
2726 Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002727 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002728 // struct objc_super
2729 QualType superType = getSuperStructType();
2730 Expr *SuperRep;
Steve Naroffd9803712009-04-29 16:37:50 +00002731
Francois Pichet0706d202011-09-17 17:15:52 +00002732 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002733 SynthSuperConstructorFunctionDecl();
2734 // Simulate a constructor call...
2735 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002736 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002737 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002738 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002739 superType, VK_LValue,
2740 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002741 // The code for super is a little tricky to prevent collision with
2742 // the structure definition in the header. The rewriter has it's own
2743 // internal definition (__rw_objc_super) that is uses. This is why
2744 // we need the cast below. For example:
2745 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2746 //
John McCalle3027922010-08-25 11:45:40 +00002747 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002748 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002749 VK_RValue, OK_Ordinary,
2750 SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002751 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2752 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002753 CK_BitCast, SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002754 } else {
Douglas Gregor9a129192010-04-21 00:45:42 +00002755 // (struct objc_super) { <exprs from above> }
2756 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002757 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002758 SourceLocation());
2759 TypeSourceInfo *superTInfo
2760 = Context->getTrivialTypeSourceInfo(superType);
2761 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002762 superType, VK_LValue,
2763 ILE, false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002764 // struct objc_super *
John McCalle3027922010-08-25 11:45:40 +00002765 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002766 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002767 VK_RValue, OK_Ordinary,
2768 SourceLocation());
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002769 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002770 MsgExprs.push_back(SuperRep);
2771 break;
Steve Naroffe7f18192007-11-14 23:54:14 +00002772 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002773
2774 case ObjCMessageExpr::Class: {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002775 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002776 ObjCInterfaceDecl *Class
John McCall96fa4842010-05-17 21:00:27 +00002777 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor9a129192010-04-21 00:45:42 +00002778 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002779 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002780 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2781 &ClsExprs[0],
2782 ClsExprs.size(),
2783 StartLoc, EndLoc);
2784 MsgExprs.push_back(Cls);
2785 break;
2786 }
2787
2788 case ObjCMessageExpr::SuperInstance:{
2789 MsgSendFlavor = MsgSendSuperFunctionDecl;
2790 if (MsgSendStretFlavor)
2791 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2792 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2793 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002794 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor9a129192010-04-21 00:45:42 +00002795
2796 InitExprs.push_back(
2797 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002798 CK_BitCast,
Douglas Gregor9a129192010-04-21 00:45:42 +00002799 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00002800 false,
John McCall7decc9e2010-11-18 06:31:45 +00002801 Context->getObjCIdType(),
2802 VK_RValue, SourceLocation()))
Douglas Gregor9a129192010-04-21 00:45:42 +00002803 ); // set the 'receiver'.
2804
2805 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002806 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002807 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor9a129192010-04-21 00:45:42 +00002808 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2809 &ClsExprs[0],
2810 ClsExprs.size(),
2811 StartLoc, EndLoc);
2812 // (Class)objc_getClass("CurrentClass")
2813 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2814 Context->getObjCClassType(),
John McCallf608deb2010-11-15 09:46:46 +00002815 CK_BitCast, Cls);
Douglas Gregor9a129192010-04-21 00:45:42 +00002816 ClsExprs.clear();
2817 ClsExprs.push_back(ArgExpr);
2818 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2819 &ClsExprs[0], ClsExprs.size(),
2820 StartLoc, EndLoc);
2821
2822 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2823 // To turn off a warning, type-cast to 'id'
2824 InitExprs.push_back(
2825 // set 'super class', using class_getSuperclass().
2826 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCallf608deb2010-11-15 09:46:46 +00002827 CK_BitCast, Cls));
Douglas Gregor9a129192010-04-21 00:45:42 +00002828 // struct objc_super
2829 QualType superType = getSuperStructType();
2830 Expr *SuperRep;
2831
Francois Pichet0706d202011-09-17 17:15:52 +00002832 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00002833 SynthSuperConstructorFunctionDecl();
2834 // Simulate a constructor call...
2835 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00002836 false, superType, VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00002837 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00002838 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00002839 superType, VK_LValue, SourceLocation());
Douglas Gregor9a129192010-04-21 00:45:42 +00002840 // The code for super is a little tricky to prevent collision with
2841 // the structure definition in the header. The rewriter has it's own
2842 // internal definition (__rw_objc_super) that is uses. This is why
2843 // we need the cast below. For example:
2844 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2845 //
John McCalle3027922010-08-25 11:45:40 +00002846 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor9a129192010-04-21 00:45:42 +00002847 Context->getPointerType(SuperRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00002848 VK_RValue, OK_Ordinary,
Douglas Gregor9a129192010-04-21 00:45:42 +00002849 SourceLocation());
2850 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2851 Context->getPointerType(superType),
John McCallf608deb2010-11-15 09:46:46 +00002852 CK_BitCast, SuperRep);
Douglas Gregor9a129192010-04-21 00:45:42 +00002853 } else {
2854 // (struct objc_super) { <exprs from above> }
2855 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002856 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor9a129192010-04-21 00:45:42 +00002857 SourceLocation());
2858 TypeSourceInfo *superTInfo
2859 = Context->getTrivialTypeSourceInfo(superType);
2860 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCall7decc9e2010-11-18 06:31:45 +00002861 superType, VK_RValue, ILE,
2862 false);
Douglas Gregor9a129192010-04-21 00:45:42 +00002863 }
2864 MsgExprs.push_back(SuperRep);
2865 break;
2866 }
2867
2868 case ObjCMessageExpr::Instance: {
2869 // Remove all type-casts because it may contain objc-style types; e.g.
2870 // Foo<Proto> *.
2871 Expr *recExpr = Exp->getInstanceReceiver();
2872 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2873 recExpr = CE->getSubExpr();
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002874 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2875 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2876 ? CK_BlockPointerToObjCPointerCast
2877 : CK_CPointerToObjCPointerCast;
2878
Douglas Gregor9a129192010-04-21 00:45:42 +00002879 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanian942bbce2011-10-07 17:17:45 +00002880 CK, recExpr);
Douglas Gregor9a129192010-04-21 00:45:42 +00002881 MsgExprs.push_back(recExpr);
2882 break;
2883 }
2884 }
2885
Steve Naroffa397efd2007-11-03 11:27:19 +00002886 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002887 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002888 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff574440f2007-10-24 22:48:43 +00002889 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00002890 &SelExprs[0], SelExprs.size(),
2891 StartLoc,
2892 EndLoc);
Steve Naroff574440f2007-10-24 22:48:43 +00002893 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002894
Steve Naroff574440f2007-10-24 22:48:43 +00002895 // Now push any user supplied arguments.
2896 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002897 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002898 // Make all implicit casts explicit...ICE comes in handy:-)
2899 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2900 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahanian8f490332011-02-26 01:31:36 +00002901 QualType type = ICE->getType();
2902 if (needToScanForQualifiers(type))
2903 type = Context->getObjCIdType();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00002904 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002905 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian9e7dbd12011-08-04 23:58:03 +00002906 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall9320b872011-09-09 05:25:32 +00002907 CastKind CK;
2908 if (SubExpr->getType()->isIntegralType(*Context) &&
2909 type->isBooleanType()) {
2910 CK = CK_IntegralToBoolean;
2911 } else if (type->isObjCObjectPointerType()) {
2912 if (SubExpr->getType()->isBlockPointerType()) {
2913 CK = CK_BlockPointerToObjCPointerCast;
2914 } else if (SubExpr->getType()->isPointerType()) {
2915 CK = CK_CPointerToObjCPointerCast;
2916 } else {
2917 CK = CK_BitCast;
2918 }
2919 } else {
2920 CK = CK_BitCast;
2921 }
2922
2923 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002924 }
2925 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002926 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002927 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002928 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002929 userExpr = CE->getSubExpr();
John McCall9320b872011-09-09 05:25:32 +00002930 CastKind CK;
2931 if (userExpr->getType()->isIntegralType(*Context)) {
2932 CK = CK_IntegralToPointer;
2933 } else if (userExpr->getType()->isBlockPointerType()) {
2934 CK = CK_BlockPointerToObjCPointerCast;
2935 } else if (userExpr->getType()->isPointerType()) {
2936 CK = CK_CPointerToObjCPointerCast;
2937 } else {
2938 CK = CK_BitCast;
2939 }
John McCall97513962010-01-15 18:39:57 +00002940 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall9320b872011-09-09 05:25:32 +00002941 CK, userExpr);
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002942 }
Mike Stump11289f42009-09-09 15:08:12 +00002943 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002944 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002945 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2946 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00002947 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002948 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002949 }
Steve Narofff36987c2007-11-04 22:37:50 +00002950 // Generate the funky cast.
2951 CastExpr *cast;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002952 SmallVector<QualType, 8> ArgTypes;
Steve Narofff36987c2007-11-04 22:37:50 +00002953 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002954
Steve Narofff36987c2007-11-04 22:37:50 +00002955 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002956 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2957 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2958 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002959 ArgTypes.push_back(Context->getObjCIdType());
2960 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002961 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002962 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00002963 for (const auto *PI : OMD->params()) {
2964 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002965 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00002966 : PI->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002967 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002968 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff98eb8d12007-11-05 14:36:37 +00002969 ArgTypes.push_back(t);
2970 }
Fariborz Jahanian9f0bc572011-09-10 17:01:56 +00002971 returnType = Exp->getType();
2972 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00002973 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Narofff36987c2007-11-04 22:37:50 +00002974 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002975 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002976 }
2977 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002978 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002979
Steve Narofff36987c2007-11-04 22:37:50 +00002980 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00002981 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCall7decc9e2010-11-18 06:31:45 +00002982 VK_LValue, SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002983
Mike Stump11289f42009-09-09 15:08:12 +00002984 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002985 // If we don't do this cast, we get the following bizarre warning/note:
2986 // xx.m:13: warning: function called through a non-compatible type
2987 // xx.m:13: note: if this code is reached, the program will abort
John McCall97513962010-01-15 18:39:57 +00002988 cast = NoTypeInfoCStyleCastExpr(Context,
2989 Context->getPointerType(Context->VoidTy),
John McCallf608deb2010-11-15 09:46:46 +00002990 CK_BitCast, DRE);
Mike Stump11289f42009-09-09 15:08:12 +00002991
Steve Narofff36987c2007-11-04 22:37:50 +00002992 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00002993 // If we don't have a method decl, force a variadic cast.
2994 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalldb40c7f2010-12-14 08:05:40 +00002995 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002996 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Narofff36987c2007-11-04 22:37:50 +00002997 castType = Context->getPointerType(castType);
John McCallf608deb2010-11-15 09:46:46 +00002998 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00002999 cast);
Steve Narofff36987c2007-11-04 22:37:50 +00003000
3001 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003002 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump11289f42009-09-09 15:08:12 +00003003
John McCall9dd450b2009-09-21 23:43:11 +00003004 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003005 CallExpr *CE = new (Context)
3006 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003007 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003008 if (MsgSendStretFlavor) {
3009 // We have the method which returns a struct/union. Must also generate
3010 // call to objc_msgSend_stret and hang both varieties on a conditional
3011 // expression which dictate which one to envoke depending on size of
3012 // method's return type.
Fariborz Jahaniand9c8aac2012-06-28 21:20:35 +00003013
3014 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3015 msgSendType, returnType,
3016 ArgTypes, MsgExprs,
3017 Exp->getMethodDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003018
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003019 // Build sizeof(returnType)
Peter Collingbournee190dee2011-03-11 19:24:49 +00003020 UnaryExprOrTypeTraitExpr *sizeofExpr =
3021 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3022 Context->getTrivialTypeSourceInfo(returnType),
3023 Context->getSizeType(), SourceLocation(),
3024 SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003025 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3026 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3027 // For X86 it is more complicated and some kind of target specific routine
3028 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00003029 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00003030 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00003031 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3032 llvm::APInt(IntSize, 8),
3033 Context->IntTy,
3034 SourceLocation());
John McCall7decc9e2010-11-18 06:31:45 +00003035 BinaryOperator *lessThanExpr =
3036 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00003037 VK_RValue, OK_Ordinary, SourceLocation(),
3038 false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003039 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00003040 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00003041 new (Context) ConditionalOperator(lessThanExpr,
3042 SourceLocation(), CE,
John McCallc07a0c72011-02-17 10:25:35 +00003043 SourceLocation(), STCE,
John McCall4bc41ae2010-11-18 19:01:18 +00003044 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003045 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3046 CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00003047 }
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003048 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003049 return ReplacingStmt;
3050}
3051
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003052Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanianb8f018d2010-02-22 20:48:10 +00003053 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3054 Exp->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00003055
Steve Naroff574440f2007-10-24 22:48:43 +00003056 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00003057 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00003058
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003059 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00003060 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00003061}
3062
Steve Naroffd9803712009-04-29 16:37:50 +00003063// typedef struct objc_object Protocol;
3064QualType RewriteObjC::getProtocolType() {
3065 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00003066 TypeSourceInfo *TInfo
3067 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00003068 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnarab3185b02011-03-06 15:48:19 +00003069 SourceLocation(), SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00003070 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00003071 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00003072 }
3073 return Context->getTypeDeclType(ProtocolTypeDecl);
3074}
3075
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003076/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00003077/// a synthesized/forward data reference (to the protocol's metadata).
3078/// The forward references (and metadata) are generated in
3079/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003080Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00003081 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3082 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00003083 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003084 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003085 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003086 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3087 VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00003088 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroffd9803712009-04-29 16:37:50 +00003089 Context->getPointerType(DRE->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00003090 VK_RValue, OK_Ordinary, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00003091 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCallf608deb2010-11-15 09:46:46 +00003092 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003093 DerefExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00003094 ReplaceStmt(Exp, castExpr);
Douglas Gregor33b24292012-01-01 18:09:12 +00003095 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf3f903a2010-10-11 21:29:12 +00003096 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00003097 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00003098
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00003099}
3100
Mike Stump11289f42009-09-09 15:08:12 +00003101bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003102 const char *endBuf) {
3103 while (startBuf < endBuf) {
3104 if (*startBuf == '#') {
3105 // Skip whitespace.
3106 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3107 ;
3108 if (!strncmp(startBuf, "if", strlen("if")) ||
3109 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3110 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3111 !strncmp(startBuf, "define", strlen("define")) ||
3112 !strncmp(startBuf, "undef", strlen("undef")) ||
3113 !strncmp(startBuf, "else", strlen("else")) ||
3114 !strncmp(startBuf, "elif", strlen("elif")) ||
3115 !strncmp(startBuf, "endif", strlen("endif")) ||
3116 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3117 !strncmp(startBuf, "include", strlen("include")) ||
3118 !strncmp(startBuf, "import", strlen("import")) ||
3119 !strncmp(startBuf, "include_next", strlen("include_next")))
3120 return true;
3121 }
3122 startBuf++;
3123 }
3124 return false;
3125}
3126
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003127/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003128/// an objective-c class with ivars.
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00003129void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003130 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003131 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar56df9772010-08-17 22:39:59 +00003132 assert(CDecl->getName() != "" &&
Douglas Gregor77324f32008-11-17 14:58:09 +00003133 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003134 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003135 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00003136 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003137 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003138 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00003139 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor16408322011-12-15 22:34:59 +00003140 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump11289f42009-09-09 15:08:12 +00003141
Steve Naroffdde78982007-11-14 19:25:57 +00003142 const char *startBuf = SM->getCharacterData(LocStart);
3143 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003144
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003145 // If no ivars and no root or if its root, directly or indirectly,
3146 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregordc9166c2011-12-15 20:29:51 +00003147 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003148 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00003149 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003150 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003151 return;
3152 }
Mike Stump11289f42009-09-09 15:08:12 +00003153
3154 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003155 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00003156 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003157 Result += CDecl->getNameAsString();
Francois Pichet0706d202011-09-17 17:15:52 +00003158 if (LangOpts.MicrosoftExt)
Steve Naroffa1e115e2008-03-10 23:16:54 +00003159 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00003160
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003161 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00003162 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00003163 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003164 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003165 // If the buffer contains preprocessor directives, we do more fine-grained
3166 // rewrites. This is intended to fix code that looks like (which occurs in
3167 // NSURL.h, for example):
3168 //
3169 // #ifdef XYZ
3170 // @interface Foo : NSObject
3171 // #else
3172 // @interface FooBar : NSObject
3173 // #endif
3174 // {
3175 // int i;
3176 // }
3177 // @end
3178 //
3179 // This clause is segregated to avoid breaking the common case.
3180 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00003181 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00003182 CDecl->getAtStartLoc();
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003183 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00003184 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003185
Chris Lattnerf5b77512009-02-20 18:18:36 +00003186 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003187 // advance to the end of the referenced protocols.
3188 while (endHeader < cursor && *endHeader != '>') endHeader++;
3189 endHeader++;
3190 }
3191 // rewrite the original header
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003192 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003193 } else {
3194 // rewrite the original header *without* disturbing the '{'
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003195 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00003196 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003197 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00003198 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003199 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003200 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003201 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003202 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003203
Steve Naroffdde78982007-11-14 19:25:57 +00003204 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00003205 SourceLocation OnePastCurly =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003206 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003207 InsertText(OnePastCurly, Result);
Steve Naroffdde78982007-11-14 19:25:57 +00003208 }
3209 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00003210
Steve Naroffdde78982007-11-14 19:25:57 +00003211 // Now comment out any visibility specifiers.
3212 while (cursor < endBuf) {
3213 if (*cursor == '@') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003214 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00003215 // Skip whitespace.
3216 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3217 /*scan*/;
3218
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003219 // FIXME: presence of @public, etc. inside comment results in
3220 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00003221 if (!strncmp(cursor, "public", strlen("public")) ||
3222 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00003223 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003224 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003225 InsertText(atLoc, "// ");
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003226 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003227 // FIXME: If there are cases where '<' is used in ivar declaration part
3228 // of user code, then scan the ivar list and use needToScanForQualifiers
3229 // for type checking.
3230 else if (*cursor == '<') {
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003231 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003232 InsertText(atLoc, "/* ");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003233 cursor = strchr(cursor, '>');
3234 cursor++;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003235 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003236 InsertText(atLoc, " */");
Steve Naroff295570a2008-10-30 12:09:33 +00003237 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003238 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003239 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanianc6225532007-11-14 22:26:25 +00003240 }
Steve Naroffdde78982007-11-14 19:25:57 +00003241 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00003242 }
Steve Naroffdde78982007-11-14 19:25:57 +00003243 // Don't forget to add a ';'!!
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003244 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Naroffdde78982007-11-14 19:25:57 +00003245 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00003246 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00003247 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003248 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00003249 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003250 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00003251 Result += "_IVARS;\n};\n";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003252 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003253 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003254 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003255 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikie83d382b2011-09-23 05:06:16 +00003256 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003257}
3258
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003259//===----------------------------------------------------------------------===//
3260// Meta Data Emission
3261//===----------------------------------------------------------------------===//
3262
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003263
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003264/// RewriteImplementations - This routine rewrites all method implementations
3265/// and emits meta-data.
3266
Steve Narofff8cfd162008-11-13 20:07:04 +00003267void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003268 int ClsDefCount = ClassImplementation.size();
3269 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003270
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003271 // Rewrite implemented methods
3272 for (int i = 0; i < ClsDefCount; i++)
3273 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003274
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003275 for (int i = 0; i < CatDefCount; i++)
3276 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003277}
Mike Stump11289f42009-09-09 15:08:12 +00003278
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003279void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3280 const std::string &Name,
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003281 ValueDecl *VD, bool def) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003282 assert(BlockByRefDeclNo.count(VD) &&
3283 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanianee504a02011-01-27 23:18:15 +00003284 if (def)
3285 ResultStr += "struct ";
3286 ResultStr += "__Block_byref_" + Name +
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003287 "_" + utostr(BlockByRefDeclNo[VD]) ;
3288}
3289
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003290static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3291 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3292 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3293 return false;
3294}
3295
Steve Naroff677ab3a2008-10-27 17:20:55 +00003296std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003297 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003298 std::string Tag) {
3299 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00003300 QualType RT = AFT->getReturnType();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003301 std::string StructRef = "struct " + Tag;
Douglas Gregorc0b07282011-09-27 22:38:19 +00003302 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar56df9772010-08-17 22:39:59 +00003303 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003304
Steve Naroff677ab3a2008-10-27 17:20:55 +00003305 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003306
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003307 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003308 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003309 // block (to reference imported block decl refs).
3310 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003311 } else if (BD->param_empty()) {
3312 S += "(" + StructRef + " *__cself)";
3313 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003314 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003315 assert(FT && "SynthesizeBlockFunc: No function proto");
3316 S += '(';
3317 // first add the implicit argument.
3318 S += StructRef + " *__cself, ";
3319 std::string ParamStr;
3320 for (BlockDecl::param_iterator AI = BD->param_begin(),
3321 E = BD->param_end(); AI != E; ++AI) {
3322 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003323 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003324 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00003325 (void)convertBlockPointerToFunctionPointer(QT);
3326 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003327 S += ParamStr;
3328 }
3329 if (FT->isVariadic()) {
3330 if (!BD->param_empty()) S += ", ";
3331 S += "...";
3332 }
3333 S += ')';
3334 }
3335 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003336
Steve Naroff677ab3a2008-10-27 17:20:55 +00003337 // Create local declarations to avoid rewriting all closure decl ref exprs.
3338 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00003339 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003340 E = BlockByRefDecls.end(); I != E; ++I) {
3341 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003342 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003343 std::string TypeString;
3344 RewriteByRefString(TypeString, Name, (*I));
3345 TypeString += " *";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003346 Name = TypeString + Name;
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003347 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003348 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003349 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003350 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003351 E = BlockByCopyDecls.end(); I != E; ++I) {
3352 S += " ";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003353 // Handle nested closure invocation. For example:
3354 //
3355 // void (^myImportedClosure)(void);
3356 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003357 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003358 // void (^anotherClosure)(void);
3359 // anotherClosure = ^(void) {
3360 // myImportedClosure(); // import and invoke the closure
3361 // };
3362 //
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003363 if (isTopLevelBlockPointerType((*I)->getType())) {
3364 RewriteBlockPointerTypeVariable(S, (*I));
3365 S += " = (";
3366 RewriteBlockPointerType(S, (*I)->getType());
3367 S += ")";
3368 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3369 }
3370 else {
Fariborz Jahanianb6a68c02010-02-16 17:26:03 +00003371 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003372 QualType QT = (*I)->getType();
3373 if (HasLocalVariableExternalStorage(*I))
3374 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003375 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane1ff1232010-02-16 16:21:26 +00003376 S += Name + " = __cself->" +
3377 (*I)->getNameAsString() + "; // bound by copy\n";
3378 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003379 }
3380 std::string RewrittenStr = RewrittenBlockExprs[CE];
3381 const char *cstr = RewrittenStr.c_str();
3382 while (*cstr++ != '{') ;
3383 S += cstr;
3384 S += "\n";
3385 return S;
3386}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003387
Steve Naroff677ab3a2008-10-27 17:20:55 +00003388std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003389 StringRef funcName,
Steve Naroff677ab3a2008-10-27 17:20:55 +00003390 std::string Tag) {
3391 std::string StructRef = "struct " + Tag;
3392 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003393
Steve Naroff677ab3a2008-10-27 17:20:55 +00003394 S += funcName;
3395 S += "_block_copy_" + utostr(i);
3396 S += "(" + StructRef;
3397 S += "*dst, " + StructRef;
3398 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003399 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003400 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003401 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003402 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003403 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003404 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003405 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003406 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003407 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003408 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003409 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003410 else
3411 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003412 }
Fariborz Jahaniancbdcfe82009-12-23 20:32:38 +00003413 S += "}\n";
3414
Steve Naroff677ab3a2008-10-27 17:20:55 +00003415 S += "\nstatic void __";
3416 S += funcName;
3417 S += "_block_dispose_" + utostr(i);
3418 S += "(" + StructRef;
3419 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003420 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003421 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003422 ValueDecl *VD = (*I);
Steve Naroff61d879e2008-12-16 15:50:30 +00003423 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003424 S += (*I)->getNameAsString();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003425 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian4bf727d2009-12-23 21:18:41 +00003426 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003427 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanianbce9ee22011-07-30 01:07:55 +00003428 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniand560ed72011-07-30 01:21:41 +00003429 else
3430 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003431 }
Mike Stump11289f42009-09-09 15:08:12 +00003432 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003433 return S;
3434}
3435
Steve Naroff30484702009-12-06 21:14:13 +00003436std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3437 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003438 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003439 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003440
Steve Naroff677ab3a2008-10-27 17:20:55 +00003441 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003442 S += " struct " + Desc;
3443 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003444
Steve Naroff30484702009-12-06 21:14:13 +00003445 Constructor += "(void *fp, "; // Invoke function pointer.
3446 Constructor += "struct " + Desc; // Descriptor pointer.
3447 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003448
Steve Naroff677ab3a2008-10-27 17:20:55 +00003449 if (BlockDeclRefs.size()) {
3450 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003451 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003452 E = BlockByCopyDecls.end(); I != E; ++I) {
3453 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003454 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003455 std::string ArgName = "_" + FieldName;
3456 // Handle nested closure invocation. For example:
3457 //
3458 // void (^myImportedBlock)(void);
3459 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003460 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003461 // void (^anotherBlock)(void);
3462 // anotherBlock = ^(void) {
3463 // myImportedBlock(); // import and invoke the closure
3464 // };
3465 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003466 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003467 S += "struct __block_impl *";
3468 Constructor += ", void *" + ArgName;
3469 } else {
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003470 QualType QT = (*I)->getType();
3471 if (HasLocalVariableExternalStorage(*I))
3472 QT = Context->getPointerType(QT);
Douglas Gregorc0b07282011-09-27 22:38:19 +00003473 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3474 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff677ab3a2008-10-27 17:20:55 +00003475 Constructor += ", " + ArgName;
3476 }
3477 S += FieldName + ";\n";
3478 }
3479 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00003480 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003481 E = BlockByRefDecls.end(); I != E; ++I) {
3482 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003483 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003484 std::string ArgName = "_" + FieldName;
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003485 {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00003486 std::string TypeString;
3487 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian02e07732009-12-23 02:07:37 +00003488 TypeString += " *";
3489 FieldName = TypeString + FieldName;
3490 ArgName = TypeString + ArgName;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003491 Constructor += ", " + ArgName;
3492 }
3493 S += FieldName + "; // by ref\n";
3494 }
3495 // Finish writing the constructor.
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003496 Constructor += ", int flags=0)";
3497 // Initialize all "by copy" arguments.
3498 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00003499 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003500 E = BlockByCopyDecls.end(); I != E; ++I) {
3501 std::string Name = (*I)->getNameAsString();
3502 if (firsTime) {
3503 Constructor += " : ";
3504 firsTime = false;
3505 }
3506 else
3507 Constructor += ", ";
3508 if (isTopLevelBlockPointerType((*I)->getType()))
3509 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3510 else
3511 Constructor += Name + "(_" + Name + ")";
3512 }
3513 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00003514 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003515 E = BlockByRefDecls.end(); I != E; ++I) {
3516 std::string Name = (*I)->getNameAsString();
3517 if (firsTime) {
3518 Constructor += " : ";
3519 firsTime = false;
3520 }
3521 else
3522 Constructor += ", ";
Fariborz Jahanianc6078c82011-04-01 23:08:13 +00003523 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahaniane6a4e392010-07-28 23:27:30 +00003524 }
3525
3526 Constructor += " {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003527 if (GlobalVarDecl)
3528 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3529 else
3530 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003531 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003532
Steve Naroff30484702009-12-06 21:14:13 +00003533 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003534 } else {
3535 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003536 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003537 if (GlobalVarDecl)
3538 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3539 else
3540 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003541 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3542 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003543 }
3544 Constructor += " ";
3545 Constructor += "}\n";
3546 S += Constructor;
3547 S += "};\n";
3548 return S;
3549}
3550
Steve Naroff30484702009-12-06 21:14:13 +00003551std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3552 std::string ImplTag, int i,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003553 StringRef FunName,
Steve Naroff30484702009-12-06 21:14:13 +00003554 unsigned hasCopy) {
3555 std::string S = "\nstatic struct " + DescTag;
3556
3557 S += " {\n unsigned long reserved;\n";
3558 S += " unsigned long Block_size;\n";
3559 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003560 S += " void (*copy)(struct ";
3561 S += ImplTag; S += "*, struct ";
3562 S += ImplTag; S += "*);\n";
3563
3564 S += " void (*dispose)(struct ";
3565 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003566 }
3567 S += "} ";
3568
3569 S += DescTag + "_DATA = { 0, sizeof(struct ";
3570 S += ImplTag + ")";
3571 if (hasCopy) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00003572 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3573 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff30484702009-12-06 21:14:13 +00003574 }
3575 S += "};\n";
3576 return S;
3577}
3578
Steve Naroff677ab3a2008-10-27 17:20:55 +00003579void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003580 StringRef FunName) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003581 // Insert declaration for the function in which block literal is used.
Fariborz Jahanian5c26eee2010-01-15 18:14:52 +00003582 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00003583 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003584 bool RewriteSC = (GlobalVarDecl &&
3585 !Blocks.empty() &&
John McCall8e7d6562010-08-26 03:08:43 +00003586 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003587 GlobalVarDecl->getType().getCVRQualifiers());
3588 if (RewriteSC) {
3589 std::string SC(" void __");
3590 SC += GlobalVarDecl->getNameAsString();
3591 SC += "() {}";
3592 InsertText(FunLocStart, SC);
3593 }
3594
Steve Naroff677ab3a2008-10-27 17:20:55 +00003595 // Insert closures that were part of the function.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003596 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3597 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003598 // Need to copy-in the inner copied-in variables not actually used in this
3599 // block.
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003600 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00003601 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003602 ValueDecl *VD = Exp->getDecl();
3603 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00003604 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003605 BlockByCopyDeclsPtrSet.insert(VD);
3606 BlockByCopyDecls.push_back(VD);
3607 }
John McCall113bee02012-03-10 09:33:50 +00003608 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003609 BlockByRefDeclsPtrSet.insert(VD);
3610 BlockByRefDecls.push_back(VD);
3611 }
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003612 // imported objects in the inner blocks not used in the outer
3613 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00003614 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanianfc8315f2010-10-05 18:05:06 +00003615 VD->getType()->isObjCObjectPointerType() ||
3616 VD->getType()->isBlockPointerType())
3617 ImportedBlockDecls.insert(VD);
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003618 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003619
Daniel Dunbar56df9772010-08-17 22:39:59 +00003620 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3621 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003622
Steve Naroff30484702009-12-06 21:14:13 +00003623 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003624
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003625 InsertText(FunLocStart, CI);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003626
Steve Naroff30484702009-12-06 21:14:13 +00003627 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003628
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003629 InsertText(FunLocStart, CF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003630
3631 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003632 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003633 InsertText(FunLocStart, HF);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003634 }
Steve Naroff30484702009-12-06 21:14:13 +00003635 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3636 ImportedBlockDecls.size() > 0);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003637 InsertText(FunLocStart, BD);
Mike Stump11289f42009-09-09 15:08:12 +00003638
Steve Naroff677ab3a2008-10-27 17:20:55 +00003639 BlockDeclRefs.clear();
3640 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003641 BlockByRefDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003642 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00003643 BlockByCopyDeclsPtrSet.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003644 ImportedBlockDecls.clear();
3645 }
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003646 if (RewriteSC) {
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003647 // Must insert any 'const/volatile/static here. Since it has been
3648 // removed as result of rewriting of block literals.
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003649 std::string SC;
John McCall8e7d6562010-08-26 03:08:43 +00003650 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003651 SC = "static ";
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003652 if (GlobalVarDecl->getType().isConstQualified())
3653 SC += "const ";
3654 if (GlobalVarDecl->getType().isVolatileQualified())
3655 SC += "volatile ";
Fariborz Jahanian535c9c02010-03-04 21:35:37 +00003656 if (GlobalVarDecl->getType().isRestrictQualified())
3657 SC += "restrict ";
3658 InsertText(FunLocStart, SC);
Fariborz Jahanian8bb35c42010-03-04 18:54:29 +00003659 }
3660
Steve Naroff677ab3a2008-10-27 17:20:55 +00003661 Blocks.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003662 InnerDeclRefsCount.clear();
3663 InnerDeclRefs.clear();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003664 RewrittenBlockExprs.clear();
3665}
3666
3667void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3668 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003669 StringRef FuncName = FD->getName();
Mike Stump11289f42009-09-09 15:08:12 +00003670
Steve Naroff677ab3a2008-10-27 17:20:55 +00003671 SynthesizeBlockLiterals(FunLocStart, FuncName);
3672}
3673
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003674static void BuildUniqueMethodName(std::string &Name,
3675 ObjCMethodDecl *MD) {
3676 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar56df9772010-08-17 22:39:59 +00003677 Name = IFace->getName();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003678 Name += "__" + MD->getSelector().getAsString();
3679 // Convert colons to underscores.
3680 std::string::size_type loc = 0;
3681 while ((loc = Name.find(":", loc)) != std::string::npos)
3682 Name.replace(loc, 1, "_");
3683}
3684
Steve Naroff677ab3a2008-10-27 17:20:55 +00003685void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003686 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3687 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianb5f99c32010-01-29 01:55:49 +00003688 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00003689 std::string FuncName;
3690 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar56df9772010-08-17 22:39:59 +00003691 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003692}
3693
3694void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00003695 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff677ab3a2008-10-27 17:20:55 +00003696 if (*CI) {
3697 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3698 GetBlockDeclRefExprs(CBE->getBody());
3699 else
3700 GetBlockDeclRefExprs(*CI);
3701 }
3702 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003703 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3704 if (DRE->refersToEnclosingLocal()) {
3705 // FIXME: Handle enums.
3706 if (!isa<FunctionDecl>(DRE->getDecl()))
3707 BlockDeclRefs.push_back(DRE);
3708 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3709 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003710 }
John McCall113bee02012-03-10 09:33:50 +00003711 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003712
Steve Naroff677ab3a2008-10-27 17:20:55 +00003713 return;
3714}
3715
Craig Topper5603df42013-07-05 19:34:19 +00003716void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3717 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003718 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall8322c3a2011-02-13 04:07:26 +00003719 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003720 if (*CI) {
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003721 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3722 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003723 GetInnerBlockDeclRefExprs(CBE->getBody(),
3724 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003725 InnerContexts);
3726 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003727 else
3728 GetInnerBlockDeclRefExprs(*CI,
3729 InnerBlockDeclRefs,
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003730 InnerContexts);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003731
3732 }
3733 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00003734 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3735 if (DRE->refersToEnclosingLocal()) {
3736 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3737 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3738 InnerBlockDeclRefs.push_back(DRE);
3739 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3740 if (Var->isFunctionOrMethodVarDecl())
3741 ImportedLocalExternalDecls.insert(Var);
3742 }
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003743 }
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00003744
Fariborz Jahanian8652be02010-02-24 22:48:18 +00003745 return;
3746}
3747
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003748/// convertFunctionTypeOfBlocks - This routine converts a function type
3749/// whose result type may be a block pointer or whose argument type(s)
Chris Lattner57540c52011-04-15 05:22:18 +00003750/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003751/// all block pointers to function pointers.
3752QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3753 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3754 // FTP will be null for closures that don't take arguments.
3755 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003756 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00003757 QualType Res = FT->getReturnType();
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003758 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003759
3760 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003761 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3762 E = FTP->param_type_end();
3763 I && (I != E); ++I) {
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003764 QualType t = *I;
3765 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian31b8a9d2010-05-25 17:12:52 +00003766 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003767 HasBlockType = true;
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003768 ArgTypes.push_back(t);
3769 }
3770 }
3771 QualType FuncType;
3772 // FIXME. Does this work if block takes no argument but has a return type
3773 // which is of block type?
3774 if (HasBlockType)
Jordan Rose5c382722013-03-08 21:51:21 +00003775 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian19c62402010-05-25 15:56:08 +00003776 else FuncType = QualType(FT, 0);
3777 return FuncType;
3778}
3779
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003780Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003781 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003782 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003783
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003784 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003785 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003786 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003787 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003788 }
3789 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3790 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3791 }
3792 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3793 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3794 else if (const ConditionalOperator *CEXPR =
3795 dyn_cast<ConditionalOperator>(BlockExp)) {
3796 Expr *LHSExp = CEXPR->getLHS();
3797 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3798 Expr *RHSExp = CEXPR->getRHS();
3799 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3800 Expr *CONDExp = CEXPR->getCond();
3801 ConditionalOperator *CondExpr =
3802 new (Context) ConditionalOperator(CONDExp,
3803 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00003804 SourceLocation(), cast<Expr>(RHSStmt),
John McCall4bc41ae2010-11-18 19:01:18 +00003805 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00003806 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00003807 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3808 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +00003809 } else if (const PseudoObjectExpr *POE
3810 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3811 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003812 } else {
3813 assert(1 && "RewriteBlockClass: Bad type");
3814 }
3815 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00003816 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003817 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003818 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003819 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003820
Abramo Bagnara6150c882010-05-11 21:36:43 +00003821 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00003822 SourceLocation(), SourceLocation(),
Steve Naroff350b6652008-10-30 10:07:53 +00003823 &Context->Idents.get("__block_impl"));
3824 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00003825
Steve Naroff350b6652008-10-30 10:07:53 +00003826 // Generate a funky cast.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003827 SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00003828
Steve Naroff350b6652008-10-30 10:07:53 +00003829 // Push the block argument type.
3830 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003831 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00003832 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
3833 E = FTP->param_type_end();
3834 I && (I != E); ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003835 QualType t = *I;
3836 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003837 if (!convertBlockPointerToFunctionPointer(t))
3838 convertToUnqualifiedObjCType(t);
Steve Naroff350b6652008-10-30 10:07:53 +00003839 ArgTypes.push_back(t);
3840 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003841 }
Steve Naroff350b6652008-10-30 10:07:53 +00003842 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003843 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump11289f42009-09-09 15:08:12 +00003844
Steve Naroff350b6652008-10-30 10:07:53 +00003845 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00003846
John McCall97513962010-01-15 18:39:57 +00003847 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCallf608deb2010-11-15 09:46:46 +00003848 CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00003849 const_cast<Expr*>(BlockExp));
Steve Naroff350b6652008-10-30 10:07:53 +00003850 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00003851 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3852 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00003853 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregor91f84212008-12-11 16:49:14 +00003855 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003856 SourceLocation(),
3857 &Context->Idents.get("FuncPtr"),
3858 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003859 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003860 ICIS_NoInit);
Ted Kremenek5a201952009-02-07 01:47:29 +00003861 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003862 FD->getType(), VK_LValue,
3863 OK_Ordinary);
Mike Stump11289f42009-09-09 15:08:12 +00003864
Fariborz Jahanian90d2e572010-11-05 18:34:46 +00003865
John McCall97513962010-01-15 18:39:57 +00003866 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCallf608deb2010-11-15 09:46:46 +00003867 CK_BitCast, ME);
Ted Kremenek5a201952009-02-07 01:47:29 +00003868 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00003869
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003870 SmallVector<Expr*, 8> BlkExprs;
Steve Naroff350b6652008-10-30 10:07:53 +00003871 // Add the implicit argument.
3872 BlkExprs.push_back(BlkCast);
3873 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003874 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003875 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00003876 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003877 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00003878 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCall7decc9e2010-11-18 06:31:45 +00003879 Exp->getType(), VK_RValue,
3880 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00003881 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003882}
3883
Steve Naroffd9803712009-04-29 16:37:50 +00003884// We need to return the rewritten expression to handle cases where the
3885// BlockDeclRefExpr is embedded in another expression being rewritten.
3886// For example:
3887//
3888// int main() {
3889// __block Foo *f;
3890// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00003891//
Steve Naroffd9803712009-04-29 16:37:50 +00003892// void (^myblock)() = ^() {
3893// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3894// i = 77;
3895// };
3896//}
John McCall113bee02012-03-10 09:33:50 +00003897Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian25c07fa2009-12-23 19:26:34 +00003898 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003899 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00003900 ValueDecl *VD = DeclRefExp->getDecl();
3901 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003902
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003903 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00003904 SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003905 &Context->Idents.get("__forwarding"),
3906 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003907 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003908 ICIS_NoInit);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003909 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3910 FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003911 FD->getType(), VK_LValue,
3912 OK_Ordinary);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003913
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003914 StringRef Name = VD->getName();
Abramo Bagnaradff19302011-03-08 08:55:46 +00003915 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003916 &Context->Idents.get(Name),
3917 Context->VoidPtrTy, 0,
Richard Smith938f40b2011-06-11 17:19:42 +00003918 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003919 ICIS_NoInit);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003920 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCall7decc9e2010-11-18 06:31:45 +00003921 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003922
3923
3924
Steve Narofff26a1d42009-02-02 17:19:26 +00003925 // Need parens to enforce precedence.
Fariborz Jahanian5bba75f2011-04-01 19:19:28 +00003926 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3927 DeclRefExp->getExprLoc(),
Fariborz Jahanian7df39802009-12-23 19:22:33 +00003928 ME);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00003929 ReplaceStmt(DeclRefExp, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00003930 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003931}
3932
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003933// Rewrites the imported local variable V with external storage
3934// (static, extern, etc.) as *V
3935//
3936Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3937 ValueDecl *VD = DRE->getDecl();
3938 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3939 if (!ImportedLocalExternalDecls.count(Var))
3940 return DRE;
John McCall7decc9e2010-11-18 06:31:45 +00003941 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3942 VK_LValue, OK_Ordinary,
3943 DRE->getLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00003944 // Need parens to enforce precedence.
3945 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3946 Exp);
3947 ReplaceStmt(DRE, PE);
3948 return PE;
3949}
3950
Steve Naroffc989a7b2008-11-03 23:29:32 +00003951void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3952 SourceLocation LocStart = CE->getLParenLoc();
3953 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00003954
3955 // Need to avoid trying to rewrite synthesized casts.
3956 if (LocStart.isInvalid())
3957 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00003958 // Need to avoid trying to rewrite casts contained in macros.
3959 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3960 return;
Mike Stump11289f42009-09-09 15:08:12 +00003961
Steve Naroff677ab3a2008-10-27 17:20:55 +00003962 const char *startBuf = SM->getCharacterData(LocStart);
3963 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003964 QualType QT = CE->getType();
3965 const Type* TypePtr = QT->getAs<Type>();
3966 if (isa<TypeOfExprType>(TypePtr)) {
3967 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3968 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3969 std::string TypeAsString = "(";
Fariborz Jahanianf5067912010-02-18 01:20:22 +00003970 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003971 TypeAsString += ")";
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003972 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanianf3b9b952010-01-19 21:48:35 +00003973 return;
3974 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003975 // advance the location to startArgList.
3976 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00003977
Steve Naroff677ab3a2008-10-27 17:20:55 +00003978 while (*argPtr++ && (argPtr < endBuf)) {
3979 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00003980 case '^':
3981 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003982 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00003983 ReplaceText(LocStart, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00003984 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003985 }
3986 }
3987 return;
3988}
3989
3990void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3991 SourceLocation DeclLoc = FD->getLocation();
3992 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003993
Steve Naroff677ab3a2008-10-27 17:20:55 +00003994 // We have 1 or more arguments that have closure pointers.
3995 const char *startBuf = SM->getCharacterData(DeclLoc);
3996 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00003997
Steve Naroff677ab3a2008-10-27 17:20:55 +00003998 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00003999
Steve Naroff677ab3a2008-10-27 17:20:55 +00004000 parenCount++;
4001 // advance the location to startArgList.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004002 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004003 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004004
Steve Naroff677ab3a2008-10-27 17:20:55 +00004005 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004006
Steve Naroff677ab3a2008-10-27 17:20:55 +00004007 while (*argPtr++ && parenCount) {
4008 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004009 case '^':
4010 // Replace the '^' with '*'.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004011 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004012 ReplaceText(DeclLoc, 1, "*");
Mike Stump281d6d72010-01-20 02:03:14 +00004013 break;
4014 case '(':
4015 parenCount++;
4016 break;
4017 case ')':
4018 parenCount--;
4019 break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004020 }
4021 }
4022 return;
4023}
4024
4025bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004026 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004027 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004028 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004029 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004030 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004031 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004032 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004033 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004034 }
4035 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004036 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4037 E = FTP->param_type_end();
4038 I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004039 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 return true;
4041 }
4042 return false;
4043}
4044
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004045bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4046 const FunctionProtoType *FTP;
4047 const PointerType *PT = QT->getAs<PointerType>();
4048 if (PT) {
4049 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4050 } else {
4051 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4052 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4053 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4054 }
4055 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004056 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4057 E = FTP->param_type_end();
4058 I != E; ++I) {
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004059 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004060 return true;
Fariborz Jahanian733dde62010-11-03 23:50:34 +00004061 if ((*I)->isObjCObjectPointerType() &&
4062 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4063 return true;
4064 }
4065
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004066 }
4067 return false;
4068}
4069
Ted Kremenek5a201952009-02-07 01:47:29 +00004070void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4071 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004072 const char *argPtr = strchr(Name, '(');
4073 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004074
Steve Naroff677ab3a2008-10-27 17:20:55 +00004075 LParen = argPtr; // output the start.
4076 argPtr++; // skip past the left paren.
4077 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004078
Steve Naroff677ab3a2008-10-27 17:20:55 +00004079 while (*argPtr && parenCount) {
4080 switch (*argPtr) {
Mike Stump281d6d72010-01-20 02:03:14 +00004081 case '(': parenCount++; break;
4082 case ')': parenCount--; break;
4083 default: break;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004084 }
4085 if (parenCount) argPtr++;
4086 }
4087 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4088 RParen = argPtr; // output the end
4089}
4090
4091void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4092 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4093 RewriteBlockPointerFunctionArgs(FD);
4094 return;
Mike Stump11289f42009-09-09 15:08:12 +00004095 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004096 // Handle Variables and Typedefs.
4097 SourceLocation DeclLoc = ND->getLocation();
4098 QualType DeclT;
4099 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4100 DeclT = VD->getType();
Richard Smithdda56e42011-04-15 14:24:37 +00004101 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004102 DeclT = TDD->getUnderlyingType();
4103 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4104 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004105 else
David Blaikie83d382b2011-09-23 05:06:16 +00004106 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004107
Steve Naroff677ab3a2008-10-27 17:20:55 +00004108 const char *startBuf = SM->getCharacterData(DeclLoc);
4109 const char *endBuf = startBuf;
4110 // scan backward (from the decl location) for the end of the previous decl.
4111 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4112 startBuf--;
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004113 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004114 std::string buf;
4115 unsigned OrigLength=0;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004116 // *startBuf != '^' if we are dealing with a pointer to function that
4117 // may take block argument types (which will be handled below).
4118 if (*startBuf == '^') {
4119 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004120 buf = '*';
4121 startBuf++;
4122 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004123 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004124 while (*startBuf != ')') {
4125 buf += *startBuf;
4126 startBuf++;
4127 OrigLength++;
4128 }
4129 buf += ')';
4130 OrigLength++;
4131
4132 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4133 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004134 // Replace the '^' with '*' for arguments.
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004135 // Replace id<P> with id/*<>*/
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 DeclLoc = ND->getLocation();
4137 startBuf = SM->getCharacterData(DeclLoc);
4138 const char *argListBegin, *argListEnd;
4139 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4140 while (argListBegin < argListEnd) {
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004141 if (*argListBegin == '^')
4142 buf += '*';
4143 else if (*argListBegin == '<') {
4144 buf += "/*";
4145 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00004146 OrigLength++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004147 while (*argListBegin != '>') {
4148 buf += *argListBegin++;
4149 OrigLength++;
4150 }
4151 buf += *argListBegin;
4152 buf += "*/";
Steve Naroff677ab3a2008-10-27 17:20:55 +00004153 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004154 else
4155 buf += *argListBegin;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004156 argListBegin++;
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004157 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004158 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004159 buf += ')';
4160 OrigLength++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004161 }
Fariborz Jahanian147e1cb2010-11-03 23:29:24 +00004162 ReplaceText(Start, OrigLength, buf);
4163
Steve Naroff677ab3a2008-10-27 17:20:55 +00004164 return;
4165}
4166
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004167
4168/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4169/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4170/// struct Block_byref_id_object *src) {
4171/// _Block_object_assign (&_dest->object, _src->object,
4172/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4173/// [|BLOCK_FIELD_IS_WEAK]) // object
4174/// _Block_object_assign(&_dest->object, _src->object,
4175/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4176/// [|BLOCK_FIELD_IS_WEAK]) // block
4177/// }
4178/// And:
4179/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4180/// _Block_object_dispose(_src->object,
4181/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4182/// [|BLOCK_FIELD_IS_WEAK]) // object
4183/// _Block_object_dispose(_src->object,
4184/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4185/// [|BLOCK_FIELD_IS_WEAK]) // block
4186/// }
4187
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004188std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4189 int flag) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004190 std::string S;
Benjamin Kramere056cea2010-01-10 19:57:50 +00004191 if (CopyDestroyCache.count(flag))
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004192 return S;
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004193 CopyDestroyCache.insert(flag);
4194 S = "static void __Block_byref_id_object_copy_";
4195 S += utostr(flag);
4196 S += "(void *dst, void *src) {\n";
4197
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004198 // offset into the object pointer is computed as:
4199 // void * + void* + int + int + void* + void *
4200 unsigned IntSize =
4201 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4202 unsigned VoidPtrSize =
4203 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4204
Ken Dyckd9c83e62011-04-30 16:08:27 +00004205 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004206 S += " _Block_object_assign((char*)dst + ";
4207 S += utostr(offset);
4208 S += ", *(void * *) ((char*)src + ";
4209 S += utostr(offset);
4210 S += "), ";
4211 S += utostr(flag);
4212 S += ");\n}\n";
4213
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004214 S += "static void __Block_byref_id_object_dispose_";
4215 S += utostr(flag);
4216 S += "(void *src) {\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004217 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4218 S += utostr(offset);
4219 S += "), ";
4220 S += utostr(flag);
4221 S += ");\n}\n";
4222 return S;
4223}
4224
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004225/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4226/// the declaration into:
4227/// struct __Block_byref_ND {
4228/// void *__isa; // NULL for everything except __weak pointers
4229/// struct __Block_byref_ND *__forwarding;
4230/// int32_t __flags;
4231/// int32_t __size;
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004232/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4233/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004234/// typex ND;
4235/// };
4236///
4237/// It then replaces declaration of ND variable with:
4238/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4239/// __size=sizeof(struct __Block_byref_ND),
4240/// ND=initializer-if-any};
4241///
4242///
4243void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahaniane2dd5422010-01-14 00:35:56 +00004244 // Insert declaration for the function in which block literal is
4245 // used.
4246 if (CurFunctionDeclToDeclareForBlock)
4247 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004248 int flag = 0;
4249 int isa = 0;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004250 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahanian6005bd82010-02-26 22:49:11 +00004251 if (DeclLoc.isInvalid())
4252 // If type location is missing, it is because of missing type (a warning).
4253 // Use variable's location which is good for this case.
4254 DeclLoc = ND->getLocation();
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004255 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004256 SourceLocation X = ND->getLocEnd();
Chandler Carruth35f53202011-07-25 16:49:02 +00004257 X = SM->getExpansionLoc(X);
Fariborz Jahanian92368a12009-12-30 20:38:08 +00004258 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004259 std::string Name(ND->getNameAsString());
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004260 std::string ByrefType;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004261 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004262 ByrefType += " {\n";
4263 ByrefType += " void *__isa;\n";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004264 RewriteByRefString(ByrefType, Name, ND);
4265 ByrefType += " *__forwarding;\n";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004266 ByrefType += " int __flags;\n";
4267 ByrefType += " int __size;\n";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004268 // Add void *__Block_byref_id_object_copy;
4269 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004270 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00004271 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004272 if (HasCopyAndDispose) {
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004273 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4274 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004275 }
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004276
4277 QualType T = Ty;
4278 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregorc0b07282011-09-27 22:38:19 +00004279 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004280
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004281 ByrefType += " " + Name + ";\n";
4282 ByrefType += "};\n";
4283 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004284 SourceLocation FunLocStart;
4285 if (CurFunctionDef)
4286 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4287 else {
4288 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4289 FunLocStart = CurMethodDef->getLocStart();
4290 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004291 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004292 if (Ty.isObjCGCWeak()) {
4293 flag |= BLOCK_FIELD_IS_WEAK;
4294 isa = 1;
4295 }
4296
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004297 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004298 flag = BLOCK_BYREF_CALLER;
4299 QualType Ty = ND->getType();
4300 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4301 if (Ty->isBlockPointerType())
4302 flag |= BLOCK_FIELD_IS_BLOCK;
4303 else
4304 flag |= BLOCK_FIELD_IS_OBJECT;
4305 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004306 if (!HF.empty())
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004307 InsertText(FunLocStart, HF);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004308 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004309
4310 // struct __Block_byref_ND ND =
4311 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4312 // initializer-if-any};
4313 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanianf7945432010-01-05 18:15:57 +00004314 unsigned flags = 0;
4315 if (HasCopyAndDispose)
4316 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004317 Name = ND->getNameAsString();
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004318 ByrefType.clear();
4319 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004320 std::string ForwardingCastType("(");
4321 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004322 if (!hasInit) {
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004323 ByrefType += " " + Name + " = {(void*)";
4324 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004325 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004326 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004327 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004328 ByrefType += "sizeof(";
4329 RewriteByRefString(ByrefType, Name, ND);
4330 ByrefType += ")";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004331 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004332 ByrefType += ", __Block_byref_id_object_copy_";
4333 ByrefType += utostr(flag);
4334 ByrefType += ", __Block_byref_id_object_dispose_";
4335 ByrefType += utostr(flag);
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004336 }
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004337 ByrefType += "};\n";
Fariborz Jahanianff51d4e2011-03-31 22:49:32 +00004338 unsigned nameSize = Name.size();
4339 // for block or function pointer declaration. Name is aleady
4340 // part of the declaration.
4341 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4342 nameSize = 1;
4343 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004344 }
4345 else {
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004346 SourceLocation startLoc;
4347 Expr *E = ND->getInit();
4348 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4349 startLoc = ECE->getLParenLoc();
4350 else
4351 startLoc = E->getLocStart();
Chandler Carruth35f53202011-07-25 16:49:02 +00004352 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004353 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004354 ByrefType += " " + Name;
Fariborz Jahanianfaf85c02010-01-16 19:36:43 +00004355 ByrefType += " = {(void*)";
Fariborz Jahanian7fac6552010-01-05 19:21:35 +00004356 ByrefType += utostr(isa);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004357 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004358 ByrefType += utostr(flags);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004359 ByrefType += ", ";
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004360 ByrefType += "sizeof(";
4361 RewriteByRefString(ByrefType, Name, ND);
4362 ByrefType += "), ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004363 if (HasCopyAndDispose) {
Fariborz Jahaniane3891582010-01-05 18:04:40 +00004364 ByrefType += "__Block_byref_id_object_copy_";
4365 ByrefType += utostr(flag);
4366 ByrefType += ", __Block_byref_id_object_dispose_";
4367 ByrefType += utostr(flag);
4368 ByrefType += ", ";
Fariborz Jahanian8c07e752010-01-05 01:16:51 +00004369 }
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004370 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroff13468372009-12-23 17:24:33 +00004371
4372 // Complete the newly synthesized compound expression by inserting a right
4373 // curly brace before the end of the declaration.
4374 // FIXME: This approach avoids rewriting the initializer expression. It
4375 // also assumes there is only one declarator. For example, the following
4376 // isn't currently supported by this routine (in general):
4377 //
4378 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4379 //
Fariborz Jahanian34c85982010-07-21 17:36:39 +00004380 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4381 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroff13468372009-12-23 17:24:33 +00004382 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4383 SourceLocation semiLoc =
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00004384 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroff13468372009-12-23 17:24:33 +00004385
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004386 InsertText(semiLoc, "}");
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004387 }
Fariborz Jahanian81203462009-12-22 00:48:54 +00004388 return;
4389}
4390
Mike Stump11289f42009-09-09 15:08:12 +00004391void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004392 // Add initializers for any closure decl refs.
4393 GetBlockDeclRefExprs(Exp->getBody());
4394 if (BlockDeclRefs.size()) {
4395 // Unique all "by copy" declarations.
4396 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004397 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004398 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4399 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4400 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4401 }
4402 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004403 // Unique all "by ref" declarations.
4404 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004405 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004406 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4407 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4408 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4409 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004410 }
4411 // Find any imported blocks...they will need special attention.
4412 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004413 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004414 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian9bbc1482010-02-26 21:46:27 +00004415 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff677ab3a2008-10-27 17:20:55 +00004416 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff677ab3a2008-10-27 17:20:55 +00004417 }
4418}
4419
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004420FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004421 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004422 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004423 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4424 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004425 false, false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004426}
4427
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004428Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00004429 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004430 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofff4b992a2008-10-28 20:29:00 +00004431 Blocks.push_back(Exp);
4432
4433 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004434
4435 // Add inner imported variables now used in current block.
4436 int countOfInnerDecls = 0;
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004437 if (!InnerBlockDeclRefs.empty()) {
4438 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00004439 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004440 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00004441 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004442 // We need to save the copied-in variables in nested
4443 // blocks because it is needed at the end for some of the API generations.
4444 // See SynthesizeBlockLiterals routine.
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004445 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4446 BlockDeclRefs.push_back(Exp);
4447 BlockByCopyDeclsPtrSet.insert(VD);
4448 BlockByCopyDecls.push_back(VD);
4449 }
John McCall113bee02012-03-10 09:33:50 +00004450 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004451 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4452 BlockDeclRefs.push_back(Exp);
4453 BlockByRefDeclsPtrSet.insert(VD);
4454 BlockByRefDecls.push_back(VD);
4455 }
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004456 }
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004457 // Find any imported blocks...they will need special attention.
4458 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00004459 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanianbe730c92010-02-26 22:36:30 +00004460 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4461 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4462 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004463 }
4464 InnerDeclRefsCount.push_back(countOfInnerDecls);
4465
Steve Narofff4b992a2008-10-28 20:29:00 +00004466 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004467
Steve Narofff4b992a2008-10-28 20:29:00 +00004468 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004469 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahanianc3bdefa2010-02-10 20:18:25 +00004470 else if (CurMethodDef)
4471 BuildUniqueMethodName(FuncName, CurMethodDef);
4472 else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004473 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004474
Steve Narofff4b992a2008-10-28 20:29:00 +00004475 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004476
Steve Narofff4b992a2008-10-28 20:29:00 +00004477 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4478 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004479
Steve Narofff4b992a2008-10-28 20:29:00 +00004480 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian19c62402010-05-25 15:56:08 +00004481 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4482 QualType FType = Context->getPointerType(BFT);
Steve Narofff4b992a2008-10-28 20:29:00 +00004483
4484 FunctionDecl *FD;
4485 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004486
Benjamin Kramer60509af2013-09-09 14:48:42 +00004487 // Simulate a constructor call...
Daniel Dunbar56df9772010-08-17 22:39:59 +00004488 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00004489 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCall7decc9e2010-11-18 06:31:45 +00004490 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004491
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004492 SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004493
Steve Naroffe2514232008-10-29 21:23:59 +00004494 // Initialize the block function.
Daniel Dunbar56df9772010-08-17 22:39:59 +00004495 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00004496 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4497 VK_LValue, SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004498 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004499 CK_BitCast, Arg);
Mike Stump11289f42009-09-09 15:08:12 +00004500 InitExprs.push_back(castExpr);
4501
Steve Naroff30484702009-12-06 21:14:13 +00004502 // Initialize the block descriptor.
4503 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004504
Abramo Bagnaradff19302011-03-08 08:55:46 +00004505 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4506 SourceLocation(), SourceLocation(),
4507 &Context->Idents.get(DescData.c_str()),
4508 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004509 SC_Static);
John McCall7decc9e2010-11-18 06:31:45 +00004510 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00004511 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCall7decc9e2010-11-18 06:31:45 +00004512 Context->VoidPtrTy,
4513 VK_LValue,
4514 SourceLocation()),
4515 UO_AddrOf,
4516 Context->getPointerType(Context->VoidPtrTy),
4517 VK_RValue, OK_Ordinary,
4518 SourceLocation());
Steve Naroff30484702009-12-06 21:14:13 +00004519 InitExprs.push_back(DescRefExpr);
4520
Steve Narofff4b992a2008-10-28 20:29:00 +00004521 // Add initializers for any closure decl refs.
4522 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004523 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004524 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004525 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004526 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004527 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004528 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar56df9772010-08-17 22:39:59 +00004529 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004530 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004531 SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004532 if (HasLocalVariableExternalStorage(*I)) {
4533 QualType QT = (*I)->getType();
4534 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004535 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4536 OK_Ordinary, SourceLocation());
Fariborz Jahanian36680dd2010-05-24 18:32:56 +00004537 }
Steve Naroffa5c0db82008-12-11 21:05:33 +00004538 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004539 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004540 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004541 SourceLocation());
John McCall97513962010-01-15 18:39:57 +00004542 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCallf608deb2010-11-15 09:46:46 +00004543 CK_BitCast, Arg);
Steve Narofff4b992a2008-10-28 20:29:00 +00004544 } else {
Daniel Dunbar56df9772010-08-17 22:39:59 +00004545 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004546 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004547 SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004548 if (HasLocalVariableExternalStorage(*I)) {
4549 QualType QT = (*I)->getType();
4550 QT = Context->getPointerType(QT);
John McCall7decc9e2010-11-18 06:31:45 +00004551 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4552 OK_Ordinary, SourceLocation());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004553 }
4554
Steve Narofff4b992a2008-10-28 20:29:00 +00004555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004557 }
4558 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004559 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004560 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004561 ValueDecl *ND = (*I);
4562 std::string Name(ND->getNameAsString());
4563 std::string RecName;
Fariborz Jahanianee504a02011-01-27 23:18:15 +00004564 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004565 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4566 + sizeof("struct"));
Abramo Bagnara6150c882010-05-11 21:36:43 +00004567 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00004568 SourceLocation(), SourceLocation(),
4569 II);
Fariborz Jahanianb8355e32010-02-04 00:07:58 +00004570 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4571 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4572
Daniel Dunbar56df9772010-08-17 22:39:59 +00004573 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00004574 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCall7decc9e2010-11-18 06:31:45 +00004575 SourceLocation());
Fariborz Jahanian9cd649d2011-02-16 22:37:10 +00004576 bool isNestedCapturedVar = false;
4577 if (block)
4578 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4579 ce = block->capture_end(); ci != ce; ++ci) {
4580 const VarDecl *variable = ci->getVariable();
4581 if (variable == ND && ci->isNested()) {
4582 assert (ci->isByRef() &&
4583 "SynthBlockInitExpr - captured block variable is not byref");
4584 isNestedCapturedVar = true;
4585 break;
4586 }
4587 }
4588 // captured nested byref variable has its address passed. Do not take
4589 // its address again.
4590 if (!isNestedCapturedVar)
4591 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCall7decc9e2010-11-18 06:31:45 +00004592 Context->getPointerType(Exp->getType()),
4593 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004594 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump11289f42009-09-09 15:08:12 +00004595 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004596 }
4597 }
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004598 if (ImportedBlockDecls.size()) {
4599 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4600 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff30484702009-12-06 21:14:13 +00004601 unsigned IntSize =
4602 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004603 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4604 Context->IntTy, SourceLocation());
Fariborz Jahanian65e6bd62009-12-23 21:52:32 +00004605 InitExprs.push_back(FlagExp);
Steve Naroff30484702009-12-06 21:14:13 +00004606 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004607 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCall7decc9e2010-11-18 06:31:45 +00004608 FType, VK_LValue, SourceLocation());
John McCalle3027922010-08-25 11:45:40 +00004609 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004610 Context->getPointerType(NewRep->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00004611 VK_RValue, OK_Ordinary, SourceLocation());
John McCallf608deb2010-11-15 09:46:46 +00004612 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall97513962010-01-15 18:39:57 +00004613 NewRep);
Steve Narofff4b992a2008-10-28 20:29:00 +00004614 BlockDeclRefs.clear();
4615 BlockByRefDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004616 BlockByRefDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004617 BlockByCopyDecls.clear();
Fariborz Jahanian4c4ca5a2010-02-11 23:35:57 +00004618 BlockByCopyDeclsPtrSet.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004619 ImportedBlockDecls.clear();
4620 return NewRep;
4621}
4622
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004623bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4624 if (const ObjCForCollectionStmt * CS =
4625 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4626 return CS->getElement() == DS;
4627 return false;
4628}
4629
Steve Narofff4b992a2008-10-28 20:29:00 +00004630//===----------------------------------------------------------------------===//
4631// Function Body / Expression rewriting
4632//===----------------------------------------------------------------------===//
4633
4634Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004635 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004636 isa<DoStmt>(S) || isa<ForStmt>(S))
4637 Stmts.push_back(S);
4638 else if (isa<ObjCForCollectionStmt>(S)) {
4639 Stmts.push_back(S);
Chris Lattnerb71980f2010-01-09 21:45:57 +00004640 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004641 }
Mike Stump11289f42009-09-09 15:08:12 +00004642
John McCallfe96e0b2011-11-06 09:01:30 +00004643 // Pseudo-object operations and ivar references need special
4644 // treatment because we're going to recursively rewrite them.
4645 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4646 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4647 return RewritePropertyOrImplicitSetter(PseudoOp);
4648 } else {
4649 return RewritePropertyOrImplicitGetter(PseudoOp);
4650 }
4651 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4652 return RewriteObjCIvarRefExpr(IvarRefExpr);
4653 }
4654
Steve Narofff4b992a2008-10-28 20:29:00 +00004655 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004656
Steve Narofff4b992a2008-10-28 20:29:00 +00004657 // Perform a bottom up rewrite of all children.
John McCall8322c3a2011-02-13 04:07:26 +00004658 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofff4b992a2008-10-28 20:29:00 +00004659 if (*CI) {
John McCallfe96e0b2011-11-06 09:01:30 +00004660 Stmt *childStmt = (*CI);
4661 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004662 if (newStmt) {
John McCallfe96e0b2011-11-06 09:01:30 +00004663 *CI = newStmt;
Fariborz Jahanianfae2e8d2011-04-11 21:17:02 +00004664 }
Nick Lewycky508ef2c2010-10-31 21:07:24 +00004665 }
Mike Stump11289f42009-09-09 15:08:12 +00004666
Steve Narofff4b992a2008-10-28 20:29:00 +00004667 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00004668 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004669 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4670 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004671 ImportedLocalExternalDecls.clear();
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004672 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanianf4609d42010-03-01 23:36:21 +00004673 InnerBlockDeclRefs, InnerContexts);
Steve Narofff4b992a2008-10-28 20:29:00 +00004674 // Rewrite the block body in place.
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004675 Stmt *SaveCurrentBody = CurrentBody;
4676 CurrentBody = BE->getBody();
4677 PropParentMap = 0;
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004678 // block literal on rhs of a property-dot-sytax assignment
4679 // must be replaced by its synthesize ast so getRewrittenText
4680 // works as expected. In this case, what actually ends up on RHS
4681 // is the blockTranscribed which is the helper function for the
4682 // block literal; as in: self.c = ^() {[ace ARR];};
4683 bool saveDisableReplaceStmt = DisableReplaceStmt;
4684 DisableReplaceStmt = false;
Steve Narofff4b992a2008-10-28 20:29:00 +00004685 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004686 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanian086a24a2010-11-08 18:37:50 +00004687 CurrentBody = SaveCurrentBody;
4688 PropParentMap = 0;
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004689 ImportedLocalExternalDecls.clear();
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianc7c346f2011-08-02 20:28:46 +00004691 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroffd8907b72008-10-29 18:15:37 +00004692 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004693
Fariborz Jahanian8652be02010-02-24 22:48:18 +00004694 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4695
Steve Narofff4b992a2008-10-28 20:29:00 +00004696 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004697 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004698 return blockTranscribed;
4699 }
4700 // Handle specific things.
4701 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4702 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004703
Steve Narofff4b992a2008-10-28 20:29:00 +00004704 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4705 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004706
Steve Narofff4b992a2008-10-28 20:29:00 +00004707 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4708 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004709
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004711#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004712 // Before we rewrite it, put the original message expression in a comment.
4713 SourceLocation startLoc = MessExpr->getLocStart();
4714 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004715
Steve Narofff4b992a2008-10-28 20:29:00 +00004716 const char *startBuf = SM->getCharacterData(startLoc);
4717 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004718
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 std::string messString;
4720 messString += "// ";
4721 messString.append(startBuf, endBuf-startBuf+1);
4722 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004723
4724 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004725 // InsertText(clang::SourceLocation, char const*, unsigned int).
4726 // InsertText(startLoc, messString.c_str(), messString.size());
4727 // Tried this, but it didn't work either...
4728 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004729#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004730 return RewriteMessageExpr(MessExpr);
4731 }
Mike Stump11289f42009-09-09 15:08:12 +00004732
Steve Narofff4b992a2008-10-28 20:29:00 +00004733 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4734 return RewriteObjCTryStmt(StmtTry);
4735
4736 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4737 return RewriteObjCSynchronizedStmt(StmtTry);
4738
4739 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4740 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004741
Steve Narofff4b992a2008-10-28 20:29:00 +00004742 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4743 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004744
4745 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004746 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004747 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004748 OrigStmtRange.getEnd());
4749 if (BreakStmt *StmtBreakStmt =
4750 dyn_cast<BreakStmt>(S))
4751 return RewriteBreakStmt(StmtBreakStmt);
4752 if (ContinueStmt *StmtContinueStmt =
4753 dyn_cast<ContinueStmt>(S))
4754 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004755
4756 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 // and cast exprs.
4758 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4759 // FIXME: What we're doing here is modifying the type-specifier that
4760 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004761 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004762 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4763 // the context of an ObjCForCollectionStmt. For example:
4764 // NSArray *someArray;
4765 // for (id <FooProtocol> index in someArray) ;
4766 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4767 // and it depends on the original text locations/positions.
Fariborz Jahanian74405b02011-02-24 21:29:21 +00004768 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004769 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004770
Steve Narofff4b992a2008-10-28 20:29:00 +00004771 // Blocks rewrite rules.
4772 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4773 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004774 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004775 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004776 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004777 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004778 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004779 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004780 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004781 if (VD->hasAttr<BlocksAttr>()) {
4782 static unsigned uniqueByrefDeclCount = 0;
4783 assert(!BlockByRefDeclNo.count(ND) &&
4784 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4785 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian02e07732009-12-23 02:07:37 +00004786 RewriteByRefVar(VD);
Fariborz Jahanian195ac2d2010-01-14 23:05:52 +00004787 }
Fariborz Jahanianbbf43202010-02-10 18:54:22 +00004788 else
4789 RewriteTypeOfDecl(VD);
4790 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004791 }
Richard Smithdda56e42011-04-15 14:24:37 +00004792 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004793 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004794 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004795 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004796 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4797 }
4798 }
4799 }
Mike Stump11289f42009-09-09 15:08:12 +00004800
Steve Narofff4b992a2008-10-28 20:29:00 +00004801 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4802 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004803
4804 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004805 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4806 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004807 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4808 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004809 && "Statement stack mismatch");
4810 Stmts.pop_back();
4811 }
4812 // Handle blocks rewriting.
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004813 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4814 ValueDecl *VD = DRE->getDecl();
4815 if (VD->hasAttr<BlocksAttr>())
4816 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian3a106e72010-03-11 18:20:03 +00004817 if (HasLocalVariableExternalStorage(VD))
4818 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahaniand6cba502010-01-04 19:50:07 +00004819 }
4820
Steve Narofff4b992a2008-10-28 20:29:00 +00004821 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004822 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004823 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004824 ReplaceStmt(S, BlockCall);
4825 return BlockCall;
4826 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004827 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004828 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004829 RewriteCastExpr(CE);
4830 }
4831#if 0
4832 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004833 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4834 ICE->getSubExpr(),
4835 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004836 // Get the new text.
4837 std::string SStr;
4838 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004839 Replacement->printPretty(Buf);
Steve Narofff4b992a2008-10-28 20:29:00 +00004840 const std::string &Str = Buf.str();
4841
4842 printf("CAST = %s\n", &Str[0]);
4843 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4844 delete S;
4845 return Replacement;
4846 }
4847#endif
4848 // Return this stmt unmodified.
4849 return S;
4850}
4851
Steve Naroffe70a52a2009-12-05 15:55:59 +00004852void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00004853 for (auto *FD : RD->fields()) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004854 if (isTopLevelBlockPointerType(FD->getType()))
4855 RewriteBlockPointerDecl(FD);
4856 if (FD->getType()->isObjCQualifiedIdType() ||
4857 FD->getType()->isObjCQualifiedInterfaceType())
4858 RewriteObjCQualifiedInterfaceTypes(FD);
4859 }
4860}
4861
Steve Narofff4b992a2008-10-28 20:29:00 +00004862/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4863/// main file of the input.
4864void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004865 switch (D->getKind()) {
4866 case Decl::Function: {
4867 FunctionDecl *FD = cast<FunctionDecl>(D);
4868 if (FD->isOverloadedOperator())
4869 return;
Mike Stump11289f42009-09-09 15:08:12 +00004870
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004871 // Since function prototypes don't have ParmDecl's, we check the function
4872 // prototype. This enables us to rewrite function declarations and
4873 // definitions using the same code.
4874 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004875
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00004876 if (!FD->isThisDeclarationADefinition())
4877 break;
4878
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004879 // FIXME: If this should support Obj-C++, support CXXTryStmt
4880 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4881 CurFunctionDef = FD;
4882 CurFunctionDeclToDeclareForBlock = FD;
4883 CurrentBody = Body;
4884 Body =
4885 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4886 FD->setBody(Body);
4887 CurrentBody = 0;
4888 if (PropParentMap) {
4889 delete PropParentMap;
4890 PropParentMap = 0;
4891 }
4892 // This synthesizes and inserts the block "impl" struct, invoke function,
4893 // and any copy/dispose helper functions.
4894 InsertBlockLiteralsWithinFunction(FD);
4895 CurFunctionDef = 0;
4896 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004897 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004898 break;
Mike Stump11289f42009-09-09 15:08:12 +00004899 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004900 case Decl::ObjCMethod: {
4901 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4902 if (CompoundStmt *Body = MD->getCompoundBody()) {
4903 CurMethodDef = MD;
4904 CurrentBody = Body;
4905 Body =
4906 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4907 MD->setBody(Body);
4908 CurrentBody = 0;
4909 if (PropParentMap) {
4910 delete PropParentMap;
4911 PropParentMap = 0;
4912 }
4913 InsertBlockLiteralsWithinMethod(MD);
4914 CurMethodDef = 0;
Steve Naroff1042ff32008-12-08 16:43:47 +00004915 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004916 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004917 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004918 case Decl::ObjCImplementation: {
4919 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4920 ClassImplementation.push_back(CI);
4921 break;
4922 }
4923 case Decl::ObjCCategoryImpl: {
4924 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4925 CategoryImplementation.push_back(CI);
4926 break;
4927 }
4928 case Decl::Var: {
4929 VarDecl *VD = cast<VarDecl>(D);
4930 RewriteObjCQualifiedInterfaceTypes(VD);
4931 if (isTopLevelBlockPointerType(VD->getType()))
4932 RewriteBlockPointerDecl(VD);
4933 else if (VD->getType()->isFunctionPointerType()) {
4934 CheckFunctionPointerDecl(VD->getType(), VD);
4935 if (VD->getInit()) {
4936 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4937 RewriteCastExpr(CE);
4938 }
4939 }
4940 } else if (VD->getType()->isRecordType()) {
4941 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4942 if (RD->isCompleteDefinition())
4943 RewriteRecordBody(RD);
4944 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004945 if (VD->getInit()) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004946 GlobalVarDecl = VD;
4947 CurrentBody = VD->getInit();
4948 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4949 CurrentBody = 0;
4950 if (PropParentMap) {
4951 delete PropParentMap;
4952 PropParentMap = 0;
4953 }
4954 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4955 GlobalVarDecl = 0;
4956
4957 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004958 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004959 RewriteCastExpr(CE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004960 }
4961 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004962 break;
4963 }
4964 case Decl::TypeAlias:
4965 case Decl::Typedef: {
4966 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4967 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4968 RewriteBlockPointerDecl(TD);
4969 else if (TD->getUnderlyingType()->isFunctionPointerType())
4970 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4971 }
4972 break;
4973 }
4974 case Decl::CXXRecord:
4975 case Decl::Record: {
4976 RecordDecl *RD = cast<RecordDecl>(D);
4977 if (RD->isCompleteDefinition())
Steve Naroffe70a52a2009-12-05 15:55:59 +00004978 RewriteRecordBody(RD);
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004979 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004980 }
Fariborz Jahanian7b186692011-12-05 22:59:54 +00004981 default:
4982 break;
Steve Narofff4b992a2008-10-28 20:29:00 +00004983 }
4984 // Nothing yet.
4985}
4986
Chris Lattnercf169832009-03-28 04:11:33 +00004987void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004988 if (Diags.hasErrorOccurred())
4989 return;
Mike Stump11289f42009-09-09 15:08:12 +00004990
Steve Narofff4b992a2008-10-28 20:29:00 +00004991 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004992
Steve Naroffd9803712009-04-29 16:37:50 +00004993 // Here's a great place to add any extra declarations that may be needed.
4994 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004995 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004996 E = ProtocolExprDecls.end(); I != E; ++I)
4997 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4998
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00004999 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005000 if (ClassImplementation.size() || CategoryImplementation.size())
5001 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00005002
Steve Narofff4b992a2008-10-28 20:29:00 +00005003 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5004 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00005005 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00005006 Rewrite.getRewriteBufferFor(MainFileID)) {
5007 //printf("Changed:\n");
5008 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5009 } else {
Benjamin Kramer88ab94e2010-02-14 14:14:16 +00005010 llvm::errs() << "No changes\n";
Steve Narofff4b992a2008-10-28 20:29:00 +00005011 }
Steve Narofff8cfd162008-11-13 20:07:04 +00005012
Steve Naroffd9803712009-04-29 16:37:50 +00005013 if (ClassImplementation.size() || CategoryImplementation.size() ||
5014 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005015 // Rewrite Objective-c meta data*
5016 std::string ResultStr;
Fariborz Jahanian68e628e2011-12-05 18:43:13 +00005017 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00005018 // Emit metadata.
5019 *OutFile << ResultStr;
5020 }
Steve Narofff4b992a2008-10-28 20:29:00 +00005021 OutFile->flush();
5022}
Fariborz Jahanian83077422011-12-08 18:25:15 +00005023
5024void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5025 InitializeCommon(context);
5026
5027 // declaring objc_selector outside the parameter list removes a silly
5028 // scope related warning...
5029 if (IsHeader)
5030 Preamble = "#pragma once\n";
5031 Preamble += "struct objc_selector; struct objc_class;\n";
5032 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5033 Preamble += "struct objc_object *superClass; ";
5034 if (LangOpts.MicrosoftExt) {
5035 // Add a constructor for creating temporary objects.
5036 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5037 ": ";
5038 Preamble += "object(o), superClass(s) {} ";
5039 }
5040 Preamble += "};\n";
5041 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5042 Preamble += "typedef struct objc_object Protocol;\n";
5043 Preamble += "#define _REWRITER_typedef_Protocol\n";
5044 Preamble += "#endif\n";
5045 if (LangOpts.MicrosoftExt) {
5046 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5047 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5048 } else
5049 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5050 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5051 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5052 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5053 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5054 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5055 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5056 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5057 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5058 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5059 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5060 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5061 Preamble += "(const char *);\n";
5062 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5063 Preamble += "(struct objc_class *);\n";
5064 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5065 Preamble += "(const char *);\n";
5066 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5067 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5069 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5071 Preamble += "(struct objc_class *, struct objc_object *);\n";
5072 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00005073 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahanian83077422011-12-08 18:25:15 +00005075 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5076 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5077 Preamble += "struct __objcFastEnumerationState {\n\t";
5078 Preamble += "unsigned long state;\n\t";
5079 Preamble += "void **itemsPtr;\n\t";
5080 Preamble += "unsigned long *mutationsPtr;\n\t";
5081 Preamble += "unsigned long extra[5];\n};\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5083 Preamble += "#define __FASTENUMERATIONSTATE\n";
5084 Preamble += "#endif\n";
5085 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5086 Preamble += "struct __NSConstantStringImpl {\n";
5087 Preamble += " int *isa;\n";
5088 Preamble += " int flags;\n";
5089 Preamble += " char *str;\n";
5090 Preamble += " long length;\n";
5091 Preamble += "};\n";
5092 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5093 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5094 Preamble += "#else\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5096 Preamble += "#endif\n";
5097 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5098 Preamble += "#endif\n";
5099 // Blocks preamble.
5100 Preamble += "#ifndef BLOCK_IMPL\n";
5101 Preamble += "#define BLOCK_IMPL\n";
5102 Preamble += "struct __block_impl {\n";
5103 Preamble += " void *isa;\n";
5104 Preamble += " int Flags;\n";
5105 Preamble += " int Reserved;\n";
5106 Preamble += " void *FuncPtr;\n";
5107 Preamble += "};\n";
5108 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5109 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5110 Preamble += "extern \"C\" __declspec(dllexport) "
5111 "void _Block_object_assign(void *, const void *, const int);\n";
5112 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5113 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5114 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5115 Preamble += "#else\n";
5116 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5117 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5118 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5119 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5120 Preamble += "#endif\n";
5121 Preamble += "#endif\n";
5122 if (LangOpts.MicrosoftExt) {
5123 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5124 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5125 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5126 Preamble += "#define __attribute__(X)\n";
5127 Preamble += "#endif\n";
5128 Preamble += "#define __weak\n";
5129 }
5130 else {
5131 Preamble += "#define __block\n";
5132 Preamble += "#define __weak\n";
5133 }
5134 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5135 // as this avoids warning in any 64bit/32bit compilation model.
5136 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5137}
5138
5139/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5140/// ivar offset.
5141void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5142 std::string &Result) {
5143 if (ivar->isBitField()) {
5144 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5145 // place all bitfields at offset 0.
5146 Result += "0";
5147 } else {
5148 Result += "__OFFSETOFIVAR__(struct ";
5149 Result += ivar->getContainingInterface()->getNameAsString();
5150 if (LangOpts.MicrosoftExt)
5151 Result += "_IMPL";
5152 Result += ", ";
5153 Result += ivar->getNameAsString();
5154 Result += ")";
5155 }
5156}
5157
5158/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5159void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5160 ObjCProtocolDecl *PDecl, StringRef prefix,
5161 StringRef ClassName, std::string &Result) {
5162 static bool objc_protocol_methods = false;
5163
5164 // Output struct protocol_methods holder of method selector and type.
Douglas Gregore6e48b12012-01-01 19:29:29 +00005165 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005166 /* struct protocol_methods {
5167 SEL _cmd;
5168 char *method_types;
5169 }
5170 */
5171 Result += "\nstruct _protocol_methods {\n";
5172 Result += "\tstruct objc_selector *_cmd;\n";
5173 Result += "\tchar *method_types;\n";
5174 Result += "};\n";
5175
5176 objc_protocol_methods = true;
5177 }
5178 // Do not synthesize the protocol more than once.
Douglas Gregor33b24292012-01-01 18:09:12 +00005179 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005180 return;
5181
Douglas Gregorcf9f3ea2012-01-02 02:00:30 +00005182 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5183 PDecl = Def;
5184
Fariborz Jahanian83077422011-12-08 18:25:15 +00005185 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5186 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5187 PDecl->instmeth_end());
5188 /* struct _objc_protocol_method_list {
5189 int protocol_method_count;
5190 struct protocol_methods protocols[];
5191 }
5192 */
5193 Result += "\nstatic struct {\n";
5194 Result += "\tint protocol_method_count;\n";
5195 Result += "\tstruct _protocol_methods protocol_methods[";
5196 Result += utostr(NumMethods);
5197 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5198 Result += PDecl->getNameAsString();
5199 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5200 "{\n\t" + utostr(NumMethods) + "\n";
5201
5202 // Output instance methods declared in this protocol.
5203 for (ObjCProtocolDecl::instmeth_iterator
5204 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5205 I != E; ++I) {
5206 if (I == PDecl->instmeth_begin())
5207 Result += "\t ,{{(struct objc_selector *)\"";
5208 else
5209 Result += "\t ,{(struct objc_selector *)\"";
5210 Result += (*I)->getSelector().getAsString();
5211 std::string MethodTypeString;
5212 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5213 Result += "\", \"";
5214 Result += MethodTypeString;
5215 Result += "\"}\n";
5216 }
5217 Result += "\t }\n};\n";
5218 }
5219
5220 // Output class methods declared in this protocol.
5221 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5222 PDecl->classmeth_end());
5223 if (NumMethods > 0) {
5224 /* struct _objc_protocol_method_list {
5225 int protocol_method_count;
5226 struct protocol_methods protocols[];
5227 }
5228 */
5229 Result += "\nstatic struct {\n";
5230 Result += "\tint protocol_method_count;\n";
5231 Result += "\tstruct _protocol_methods protocol_methods[";
5232 Result += utostr(NumMethods);
5233 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5234 Result += PDecl->getNameAsString();
5235 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5236 "{\n\t";
5237 Result += utostr(NumMethods);
5238 Result += "\n";
5239
5240 // Output instance methods declared in this protocol.
5241 for (ObjCProtocolDecl::classmeth_iterator
5242 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5243 I != E; ++I) {
5244 if (I == PDecl->classmeth_begin())
5245 Result += "\t ,{{(struct objc_selector *)\"";
5246 else
5247 Result += "\t ,{(struct objc_selector *)\"";
5248 Result += (*I)->getSelector().getAsString();
5249 std::string MethodTypeString;
5250 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5251 Result += "\", \"";
5252 Result += MethodTypeString;
5253 Result += "\"}\n";
5254 }
5255 Result += "\t }\n};\n";
5256 }
5257
5258 // Output:
5259 /* struct _objc_protocol {
5260 // Objective-C 1.0 extensions
5261 struct _objc_protocol_extension *isa;
5262 char *protocol_name;
5263 struct _objc_protocol **protocol_list;
5264 struct _objc_protocol_method_list *instance_methods;
5265 struct _objc_protocol_method_list *class_methods;
5266 };
5267 */
5268 static bool objc_protocol = false;
5269 if (!objc_protocol) {
5270 Result += "\nstruct _objc_protocol {\n";
5271 Result += "\tstruct _objc_protocol_extension *isa;\n";
5272 Result += "\tchar *protocol_name;\n";
5273 Result += "\tstruct _objc_protocol **protocol_list;\n";
5274 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5275 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5276 Result += "};\n";
5277
5278 objc_protocol = true;
5279 }
5280
5281 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5282 Result += PDecl->getNameAsString();
5283 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5284 "{\n\t0, \"";
5285 Result += PDecl->getNameAsString();
5286 Result += "\", 0, ";
5287 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5288 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5289 Result += PDecl->getNameAsString();
5290 Result += ", ";
5291 }
5292 else
5293 Result += "0, ";
5294 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5295 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5296 Result += PDecl->getNameAsString();
5297 Result += "\n";
5298 }
5299 else
5300 Result += "0\n";
5301 Result += "};\n";
5302
5303 // Mark this protocol as having been generated.
Douglas Gregor33b24292012-01-01 18:09:12 +00005304 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahanian83077422011-12-08 18:25:15 +00005305 llvm_unreachable("protocol already synthesized");
5306
5307}
5308
5309void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5310 const ObjCList<ObjCProtocolDecl> &Protocols,
5311 StringRef prefix, StringRef ClassName,
5312 std::string &Result) {
5313 if (Protocols.empty()) return;
5314
5315 for (unsigned i = 0; i != Protocols.size(); i++)
5316 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5317
5318 // Output the top lovel protocol meta-data for the class.
5319 /* struct _objc_protocol_list {
5320 struct _objc_protocol_list *next;
5321 int protocol_count;
5322 struct _objc_protocol *class_protocols[];
5323 }
5324 */
5325 Result += "\nstatic struct {\n";
5326 Result += "\tstruct _objc_protocol_list *next;\n";
5327 Result += "\tint protocol_count;\n";
5328 Result += "\tstruct _objc_protocol *class_protocols[";
5329 Result += utostr(Protocols.size());
5330 Result += "];\n} _OBJC_";
5331 Result += prefix;
5332 Result += "_PROTOCOLS_";
5333 Result += ClassName;
5334 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5335 "{\n\t0, ";
5336 Result += utostr(Protocols.size());
5337 Result += "\n";
5338
5339 Result += "\t,{&_OBJC_PROTOCOL_";
5340 Result += Protocols[0]->getNameAsString();
5341 Result += " \n";
5342
5343 for (unsigned i = 1; i != Protocols.size(); i++) {
5344 Result += "\t ,&_OBJC_PROTOCOL_";
5345 Result += Protocols[i]->getNameAsString();
5346 Result += "\n";
5347 }
5348 Result += "\t }\n};\n";
5349}
5350
5351void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5352 std::string &Result) {
5353 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5354
5355 // Explicitly declared @interface's are already synthesized.
5356 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregordc9166c2011-12-15 20:29:51 +00005357 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahanian83077422011-12-08 18:25:15 +00005358 // produce correct synthesis as yet.
5359 RewriteObjCInternalStruct(CDecl, Result);
5360 }
5361
5362 // Build _objc_ivar_list metadata for classes ivars if needed
5363 unsigned NumIvars = !IDecl->ivar_empty()
5364 ? IDecl->ivar_size()
5365 : (CDecl ? CDecl->ivar_size() : 0);
5366 if (NumIvars > 0) {
5367 static bool objc_ivar = false;
5368 if (!objc_ivar) {
5369 /* struct _objc_ivar {
5370 char *ivar_name;
5371 char *ivar_type;
5372 int ivar_offset;
5373 };
5374 */
5375 Result += "\nstruct _objc_ivar {\n";
5376 Result += "\tchar *ivar_name;\n";
5377 Result += "\tchar *ivar_type;\n";
5378 Result += "\tint ivar_offset;\n";
5379 Result += "};\n";
5380
5381 objc_ivar = true;
5382 }
5383
5384 /* struct {
5385 int ivar_count;
5386 struct _objc_ivar ivar_list[nIvars];
5387 };
5388 */
5389 Result += "\nstatic struct {\n";
5390 Result += "\tint ivar_count;\n";
5391 Result += "\tstruct _objc_ivar ivar_list[";
5392 Result += utostr(NumIvars);
5393 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5394 Result += IDecl->getNameAsString();
5395 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5396 "{\n\t";
5397 Result += utostr(NumIvars);
5398 Result += "\n";
5399
5400 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5401 SmallVector<ObjCIvarDecl *, 8> IVars;
5402 if (!IDecl->ivar_empty()) {
5403 for (ObjCInterfaceDecl::ivar_iterator
5404 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5405 IV != IVEnd; ++IV)
David Blaikie40ed2972012-06-06 20:45:41 +00005406 IVars.push_back(*IV);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005407 IVI = IDecl->ivar_begin();
5408 IVE = IDecl->ivar_end();
5409 } else {
5410 IVI = CDecl->ivar_begin();
5411 IVE = CDecl->ivar_end();
5412 }
5413 Result += "\t,{{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005414 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005415 Result += "\", \"";
5416 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005417 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005418 QuoteDoublequotes(TmpString, StrEncoding);
5419 Result += StrEncoding;
5420 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005421 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005422 Result += "}\n";
5423 for (++IVI; IVI != IVE; ++IVI) {
5424 Result += "\t ,{\"";
David Blaikie2d7c57e2012-04-30 02:36:29 +00005425 Result += IVI->getNameAsString();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005426 Result += "\", \"";
5427 std::string TmpString, StrEncoding;
David Blaikie40ed2972012-06-06 20:45:41 +00005428 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005429 QuoteDoublequotes(TmpString, StrEncoding);
5430 Result += StrEncoding;
5431 Result += "\", ";
David Blaikie40ed2972012-06-06 20:45:41 +00005432 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian83077422011-12-08 18:25:15 +00005433 Result += "}\n";
5434 }
5435
5436 Result += "\t }\n};\n";
5437 }
5438
5439 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005440 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005441
5442 // If any of our property implementations have associated getters or
5443 // setters, produce metadata for them as well.
5444 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5445 PropEnd = IDecl->propimpl_end();
5446 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005447 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005448 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005449 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005450 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005451 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005452 if (!PD)
5453 continue;
5454 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5455 if (!Getter->isDefined())
5456 InstanceMethods.push_back(Getter);
5457 if (PD->isReadOnly())
5458 continue;
5459 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5460 if (!Setter->isDefined())
5461 InstanceMethods.push_back(Setter);
5462 }
5463 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5464 true, "", IDecl->getName(), Result);
5465
5466 // Build _objc_method_list for class's class methods if needed
5467 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5468 false, "", IDecl->getName(), Result);
5469
5470 // Protocols referenced in class declaration?
5471 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5472 "CLASS", CDecl->getName(), Result);
5473
5474 // Declaration of class/meta-class metadata
5475 /* struct _objc_class {
5476 struct _objc_class *isa; // or const char *root_class_name when metadata
5477 const char *super_class_name;
5478 char *name;
5479 long version;
5480 long info;
5481 long instance_size;
5482 struct _objc_ivar_list *ivars;
5483 struct _objc_method_list *methods;
5484 struct objc_cache *cache;
5485 struct objc_protocol_list *protocols;
5486 const char *ivar_layout;
5487 struct _objc_class_ext *ext;
5488 };
5489 */
5490 static bool objc_class = false;
5491 if (!objc_class) {
5492 Result += "\nstruct _objc_class {\n";
5493 Result += "\tstruct _objc_class *isa;\n";
5494 Result += "\tconst char *super_class_name;\n";
5495 Result += "\tchar *name;\n";
5496 Result += "\tlong version;\n";
5497 Result += "\tlong info;\n";
5498 Result += "\tlong instance_size;\n";
5499 Result += "\tstruct _objc_ivar_list *ivars;\n";
5500 Result += "\tstruct _objc_method_list *methods;\n";
5501 Result += "\tstruct objc_cache *cache;\n";
5502 Result += "\tstruct _objc_protocol_list *protocols;\n";
5503 Result += "\tconst char *ivar_layout;\n";
5504 Result += "\tstruct _objc_class_ext *ext;\n";
5505 Result += "};\n";
5506 objc_class = true;
5507 }
5508
5509 // Meta-class metadata generation.
5510 ObjCInterfaceDecl *RootClass = 0;
5511 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5512 while (SuperClass) {
5513 RootClass = SuperClass;
5514 SuperClass = SuperClass->getSuperClass();
5515 }
5516 SuperClass = CDecl->getSuperClass();
5517
5518 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5519 Result += CDecl->getNameAsString();
5520 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5521 "{\n\t(struct _objc_class *)\"";
5522 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5523 Result += "\"";
5524
5525 if (SuperClass) {
5526 Result += ", \"";
5527 Result += SuperClass->getNameAsString();
5528 Result += "\", \"";
5529 Result += CDecl->getNameAsString();
5530 Result += "\"";
5531 }
5532 else {
5533 Result += ", 0, \"";
5534 Result += CDecl->getNameAsString();
5535 Result += "\"";
5536 }
5537 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5538 // 'info' field is initialized to CLS_META(2) for metaclass
5539 Result += ", 0,2, sizeof(struct _objc_class), 0";
5540 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5541 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5542 Result += IDecl->getNameAsString();
5543 Result += "\n";
5544 }
5545 else
5546 Result += ", 0\n";
5547 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5548 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5549 Result += CDecl->getNameAsString();
5550 Result += ",0,0\n";
5551 }
5552 else
5553 Result += "\t,0,0,0,0\n";
5554 Result += "};\n";
5555
5556 // class metadata generation.
5557 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5558 Result += CDecl->getNameAsString();
5559 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5560 "{\n\t&_OBJC_METACLASS_";
5561 Result += CDecl->getNameAsString();
5562 if (SuperClass) {
5563 Result += ", \"";
5564 Result += SuperClass->getNameAsString();
5565 Result += "\", \"";
5566 Result += CDecl->getNameAsString();
5567 Result += "\"";
5568 }
5569 else {
5570 Result += ", 0, \"";
5571 Result += CDecl->getNameAsString();
5572 Result += "\"";
5573 }
5574 // 'info' field is initialized to CLS_CLASS(1) for class
5575 Result += ", 0,1";
5576 if (!ObjCSynthesizedStructs.count(CDecl))
5577 Result += ",0";
5578 else {
5579 // class has size. Must synthesize its size.
5580 Result += ",sizeof(struct ";
5581 Result += CDecl->getNameAsString();
5582 if (LangOpts.MicrosoftExt)
5583 Result += "_IMPL";
5584 Result += ")";
5585 }
5586 if (NumIvars > 0) {
5587 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5588 Result += CDecl->getNameAsString();
5589 Result += "\n\t";
5590 }
5591 else
5592 Result += ",0";
5593 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5594 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5595 Result += CDecl->getNameAsString();
5596 Result += ", 0\n\t";
5597 }
5598 else
5599 Result += ",0,0";
5600 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5601 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5602 Result += CDecl->getNameAsString();
5603 Result += ", 0,0\n";
5604 }
5605 else
5606 Result += ",0,0,0\n";
5607 Result += "};\n";
5608}
5609
5610void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5611 int ClsDefCount = ClassImplementation.size();
5612 int CatDefCount = CategoryImplementation.size();
5613
5614 // For each implemented class, write out all its meta data.
5615 for (int i = 0; i < ClsDefCount; i++)
5616 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5617
5618 // For each implemented category, write out all its meta data.
5619 for (int i = 0; i < CatDefCount; i++)
5620 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5621
5622 // Write objc_symtab metadata
5623 /*
5624 struct _objc_symtab
5625 {
5626 long sel_ref_cnt;
5627 SEL *refs;
5628 short cls_def_cnt;
5629 short cat_def_cnt;
5630 void *defs[cls_def_cnt + cat_def_cnt];
5631 };
5632 */
5633
5634 Result += "\nstruct _objc_symtab {\n";
5635 Result += "\tlong sel_ref_cnt;\n";
5636 Result += "\tSEL *refs;\n";
5637 Result += "\tshort cls_def_cnt;\n";
5638 Result += "\tshort cat_def_cnt;\n";
5639 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5640 Result += "};\n\n";
5641
5642 Result += "static struct _objc_symtab "
5643 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5644 Result += "\t0, 0, " + utostr(ClsDefCount)
5645 + ", " + utostr(CatDefCount) + "\n";
5646 for (int i = 0; i < ClsDefCount; i++) {
5647 Result += "\t,&_OBJC_CLASS_";
5648 Result += ClassImplementation[i]->getNameAsString();
5649 Result += "\n";
5650 }
5651
5652 for (int i = 0; i < CatDefCount; i++) {
5653 Result += "\t,&_OBJC_CATEGORY_";
5654 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5655 Result += "_";
5656 Result += CategoryImplementation[i]->getNameAsString();
5657 Result += "\n";
5658 }
5659
5660 Result += "};\n\n";
5661
5662 // Write objc_module metadata
5663
5664 /*
5665 struct _objc_module {
5666 long version;
5667 long size;
5668 const char *name;
5669 struct _objc_symtab *symtab;
5670 }
5671 */
5672
5673 Result += "\nstruct _objc_module {\n";
5674 Result += "\tlong version;\n";
5675 Result += "\tlong size;\n";
5676 Result += "\tconst char *name;\n";
5677 Result += "\tstruct _objc_symtab *symtab;\n";
5678 Result += "};\n\n";
5679 Result += "static struct _objc_module "
5680 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5681 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5682 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5683 Result += "};\n\n";
5684
5685 if (LangOpts.MicrosoftExt) {
5686 if (ProtocolExprDecls.size()) {
5687 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5688 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5689 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5690 E = ProtocolExprDecls.end(); I != E; ++I) {
5691 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5692 Result += (*I)->getNameAsString();
5693 Result += " = &_OBJC_PROTOCOL_";
5694 Result += (*I)->getNameAsString();
5695 Result += ";\n";
5696 }
5697 Result += "#pragma data_seg(pop)\n\n";
5698 }
5699 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5700 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5701 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5702 Result += "&_OBJC_MODULES;\n";
5703 Result += "#pragma data_seg(pop)\n\n";
5704 }
5705}
5706
5707/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5708/// implementation.
5709void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5710 std::string &Result) {
5711 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5712 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00005713 ObjCCategoryDecl *CDecl
5714 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005715
5716 std::string FullCategoryName = ClassDecl->getNameAsString();
5717 FullCategoryName += '_';
5718 FullCategoryName += IDecl->getNameAsString();
5719
5720 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005721 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian83077422011-12-08 18:25:15 +00005722
5723 // If any of our property implementations have associated getters or
5724 // setters, produce metadata for them as well.
5725 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5726 PropEnd = IDecl->propimpl_end();
5727 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005728 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian83077422011-12-08 18:25:15 +00005729 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005730 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian83077422011-12-08 18:25:15 +00005731 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00005732 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian83077422011-12-08 18:25:15 +00005733 if (!PD)
5734 continue;
5735 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5736 InstanceMethods.push_back(Getter);
5737 if (PD->isReadOnly())
5738 continue;
5739 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5740 InstanceMethods.push_back(Setter);
5741 }
5742 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5743 true, "CATEGORY_", FullCategoryName.c_str(),
5744 Result);
5745
5746 // Build _objc_method_list for class's class methods if needed
5747 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5748 false, "CATEGORY_", FullCategoryName.c_str(),
5749 Result);
5750
5751 // Protocols referenced in class declaration?
5752 // Null CDecl is case of a category implementation with no category interface
5753 if (CDecl)
5754 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5755 FullCategoryName, Result);
5756 /* struct _objc_category {
5757 char *category_name;
5758 char *class_name;
5759 struct _objc_method_list *instance_methods;
5760 struct _objc_method_list *class_methods;
5761 struct _objc_protocol_list *protocols;
5762 // Objective-C 1.0 extensions
5763 uint32_t size; // sizeof (struct _objc_category)
5764 struct _objc_property_list *instance_properties; // category's own
5765 // @property decl.
5766 };
5767 */
5768
5769 static bool objc_category = false;
5770 if (!objc_category) {
5771 Result += "\nstruct _objc_category {\n";
5772 Result += "\tchar *category_name;\n";
5773 Result += "\tchar *class_name;\n";
5774 Result += "\tstruct _objc_method_list *instance_methods;\n";
5775 Result += "\tstruct _objc_method_list *class_methods;\n";
5776 Result += "\tstruct _objc_protocol_list *protocols;\n";
5777 Result += "\tunsigned int size;\n";
5778 Result += "\tstruct _objc_property_list *instance_properties;\n";
5779 Result += "};\n";
5780 objc_category = true;
5781 }
5782 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5783 Result += FullCategoryName;
5784 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5785 Result += IDecl->getNameAsString();
5786 Result += "\"\n\t, \"";
5787 Result += ClassDecl->getNameAsString();
5788 Result += "\"\n";
5789
5790 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5791 Result += "\t, (struct _objc_method_list *)"
5792 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5793 Result += FullCategoryName;
5794 Result += "\n";
5795 }
5796 else
5797 Result += "\t, 0\n";
5798 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5799 Result += "\t, (struct _objc_method_list *)"
5800 "&_OBJC_CATEGORY_CLASS_METHODS_";
5801 Result += FullCategoryName;
5802 Result += "\n";
5803 }
5804 else
5805 Result += "\t, 0\n";
5806
5807 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5808 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5809 Result += FullCategoryName;
5810 Result += "\n";
5811 }
5812 else
5813 Result += "\t, 0\n";
5814 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5815}
5816
5817// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5818/// class methods.
5819template<typename MethodIterator>
5820void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5821 MethodIterator MethodEnd,
5822 bool IsInstanceMethod,
5823 StringRef prefix,
5824 StringRef ClassName,
5825 std::string &Result) {
5826 if (MethodBegin == MethodEnd) return;
5827
5828 if (!objc_impl_method) {
5829 /* struct _objc_method {
5830 SEL _cmd;
5831 char *method_types;
5832 void *_imp;
5833 }
5834 */
5835 Result += "\nstruct _objc_method {\n";
5836 Result += "\tSEL _cmd;\n";
5837 Result += "\tchar *method_types;\n";
5838 Result += "\tvoid *_imp;\n";
5839 Result += "};\n";
5840
5841 objc_impl_method = true;
5842 }
5843
5844 // Build _objc_method_list for class's methods if needed
5845
5846 /* struct {
5847 struct _objc_method_list *next_method;
5848 int method_count;
5849 struct _objc_method method_list[];
5850 }
5851 */
5852 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5853 Result += "\nstatic struct {\n";
5854 Result += "\tstruct _objc_method_list *next_method;\n";
5855 Result += "\tint method_count;\n";
5856 Result += "\tstruct _objc_method method_list[";
5857 Result += utostr(NumMethods);
5858 Result += "];\n} _OBJC_";
5859 Result += prefix;
5860 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5861 Result += "_METHODS_";
5862 Result += ClassName;
5863 Result += " __attribute__ ((used, section (\"__OBJC, __";
5864 Result += IsInstanceMethod ? "inst" : "cls";
5865 Result += "_meth\")))= ";
5866 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5867
5868 Result += "\t,{{(SEL)\"";
5869 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5870 std::string MethodTypeString;
5871 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5872 Result += "\", \"";
5873 Result += MethodTypeString;
5874 Result += "\", (void *)";
5875 Result += MethodInternalNames[*MethodBegin];
5876 Result += "}\n";
5877 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5878 Result += "\t ,{(SEL)\"";
5879 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5880 std::string MethodTypeString;
5881 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5882 Result += "\", \"";
5883 Result += MethodTypeString;
5884 Result += "\", (void *)";
5885 Result += MethodInternalNames[*MethodBegin];
5886 Result += "}\n";
5887 }
5888 Result += "\t }\n};\n";
5889}
5890
5891Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5892 SourceRange OldRange = IV->getSourceRange();
5893 Expr *BaseExpr = IV->getBase();
5894
5895 // Rewrite the base, but without actually doing replaces.
5896 {
5897 DisableReplaceStmtScope S(*this);
5898 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5899 IV->setBase(BaseExpr);
5900 }
5901
5902 ObjCIvarDecl *D = IV->getDecl();
5903
5904 Expr *Replacement = IV;
5905 if (CurMethodDef) {
5906 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5907 const ObjCInterfaceType *iFaceDecl =
5908 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5909 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5910 // lookup which class implements the instance variable.
5911 ObjCInterfaceDecl *clsDeclared = 0;
5912 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5913 clsDeclared);
5914 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5915
5916 // Synthesize an explicit cast to gain access to the ivar.
5917 std::string RecName = clsDeclared->getIdentifier()->getName();
5918 RecName += "_IMPL";
5919 IdentifierInfo *II = &Context->Idents.get(RecName);
5920 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5921 SourceLocation(), SourceLocation(),
5922 II);
5923 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5924 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5925 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5926 CK_BitCast,
5927 IV->getBase());
5928 // Don't forget the parens to enforce the proper binding.
5929 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5930 OldRange.getEnd(),
5931 castExpr);
5932 if (IV->isFreeIvar() &&
Douglas Gregor0b144e12011-12-15 00:29:59 +00005933 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahanian83077422011-12-08 18:25:15 +00005934 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5935 IV->getLocation(),
5936 D->getType(),
5937 VK_LValue, OK_Ordinary);
5938 Replacement = ME;
5939 } else {
5940 IV->setBase(PE);
5941 }
5942 }
5943 } else { // we are outside a method.
5944 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5945
5946 // Explicit ivar refs need to have a cast inserted.
5947 // FIXME: consider sharing some of this code with the code above.
5948 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5949 const ObjCInterfaceType *iFaceDecl =
5950 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5951 // lookup which class implements the instance variable.
5952 ObjCInterfaceDecl *clsDeclared = 0;
5953 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5954 clsDeclared);
5955 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5956
5957 // Synthesize an explicit cast to gain access to the ivar.
5958 std::string RecName = clsDeclared->getIdentifier()->getName();
5959 RecName += "_IMPL";
5960 IdentifierInfo *II = &Context->Idents.get(RecName);
5961 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5962 SourceLocation(), SourceLocation(),
5963 II);
5964 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5965 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5966 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5967 CK_BitCast,
5968 IV->getBase());
5969 // Don't forget the parens to enforce the proper binding.
5970 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5971 IV->getBase()->getLocEnd(), castExpr);
5972 // Cannot delete IV->getBase(), since PE points to it.
5973 // Replace the old base with the cast. This is important when doing
5974 // embedded rewrites. For example, [newInv->_container addObject:0].
5975 IV->setBase(PE);
5976 }
5977 }
5978
5979 ReplaceStmtWithRange(IV, Replacement, OldRange);
5980 return Replacement;
5981}