blob: 519681085f568d8f29ab5d77f320f9834978d256 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Chris Lattner07506182007-11-30 22:53:43 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner26de4652007-12-02 01:13:47 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000026#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/StringExtras.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000028#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/raw_ostream.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070030#include <memory>
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000031
Stephen Hines176edba2014-12-01 14:53:08 -080032#ifdef CLANG_ENABLE_OBJC_REWRITER
33
Chris Lattner77cd2a02007-10-11 00:43:27 +000034using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000035using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000036
Chris Lattner77cd2a02007-10-11 00:43:27 +000037namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000038 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000039 protected:
40
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000041 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000042 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000043 block, ... */
44 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
45 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
46 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000047 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000048 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000049 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000050 support routines */
51 BLOCK_BYREF_CURRENT_MAX = 256
52 };
53
54 enum {
55 BLOCK_NEEDS_FREE = (1 << 24),
56 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
57 BLOCK_HAS_CXX_OBJ = (1 << 26),
58 BLOCK_IS_GC = (1 << 27),
59 BLOCK_IS_GLOBAL = (1 << 28),
60 BLOCK_HAS_DESCRIPTOR = (1 << 29)
61 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000062 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000063
Chris Lattner2c64b7b2007-10-16 21:07:07 +000064 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000065 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000066 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000067 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000068 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000069 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000070 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000071 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000072 Stmt *CurrentBody;
73 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000074 std::string InFileName;
75 raw_ostream* OutFile;
76 std::string Preamble;
77
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000085
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000089 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000090 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramere5753592013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000106 FunctionDecl *CurFunctionDef;
107 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000109 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000110 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
111 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000113 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000114 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
115 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 SmallVector<Stmt *, 32> Stmts;
117 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000118 // Remember all the @protocol(<expr>) expressions.
119 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000120
121 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
John McCallf4b88a42012-03-10 09:33:50 +0000128 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4c3580e2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000145
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000146 // Needed for header files being rewritten
147 bool IsHeader;
148 bool SilenceRewriteMacroWarning;
149 bool objc_impl_method;
150
Steve Naroffb619d952008-12-09 12:56:34 +0000151 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000152 class DisableReplaceStmtScope {
153 RewriteObjC &R;
154 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000155
John McCall4b9c2d22011-11-06 09:01:30 +0000156 public:
157 DisableReplaceStmtScope(RewriteObjC &R)
158 : R(R), SavedValue(R.DisableReplaceStmt) {
159 R.DisableReplaceStmt = true;
160 }
161 ~DisableReplaceStmtScope() {
162 R.DisableReplaceStmt = SavedValue;
163 }
164 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000165 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000166
Chris Lattner77cd2a02007-10-11 00:43:27 +0000167 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000168
Chris Lattnerf04da132007-10-24 17:06:59 +0000169 // Top Level Driver code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700170 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000172 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173 if (!Class->isThisDeclarationADefinition()) {
174 RewriteForwardClassDecl(D);
175 break;
176 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000177 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000178
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000179 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
182 break;
183 }
184 }
185
Chris Lattner682bf922009-03-29 16:50:03 +0000186 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000187 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000188 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000189 }
190 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000191 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000192 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000193 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000194 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000195
196 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Stephen Hines651f13c2014-04-23 16:59:28 -0700198 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000200 void ReplaceStmt(Stmt *Old, Stmt *New) {
Stephen Hines176edba2014-12-01 14:53:08 -0800201 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000202 }
Steve Naroffb619d952008-12-09 12:56:34 +0000203
204 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700205 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
Stephen Hines176edba2014-12-01 14:53:08 -0800206
207 Stmt *ReplacingStmt = ReplacedNodes[Old];
208 if (ReplacingStmt)
209 return; // We can't rewrite the same node twice.
210
John McCall4b9c2d22011-11-06 09:01:30 +0000211 if (DisableReplaceStmt)
212 return;
213
Nick Lewycky7e749242010-10-31 21:07:24 +0000214 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000215 int Size = Rewrite.getRangeSize(SrcRange);
216 if (Size == -1) {
217 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
218 << Old->getSourceRange();
219 return;
220 }
221 // Get the new text.
222 std::string SStr;
223 llvm::raw_string_ostream S(SStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700224 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000225 const std::string &Str = S.str();
226
227 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000228 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000229 ReplacedNodes[Old] = New;
230 return;
231 }
232 if (SilenceRewriteMacroWarning)
233 return;
234 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
235 << Old->getSourceRange();
236 }
237
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000239 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000245 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattneraadaf782008-01-31 19:51:04 +0000248 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000249 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000250 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000251 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000252 SilenceRewriteMacroWarning)
253 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000254
Chris Lattneraadaf782008-01-31 19:51:04 +0000255 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
256 }
Mike Stump1eb44332009-09-09 15:08:12 +0000257
Chris Lattnerf04da132007-10-24 17:06:59 +0000258 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000259 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000260 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000261 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000262 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000263 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000264 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000265 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000266 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
267 ObjCImplementationDecl *IMD,
268 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000269 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000270 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000271 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
272 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000273 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
274 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000275 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000276 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000277 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
278 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000279 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000280 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000281 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000282 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000283 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000284 void RewriteBlockPointerType(std::string& Str, QualType Type);
285 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000286 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000288 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000289 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000290
Chris Lattnerf04da132007-10-24 17:06:59 +0000291 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000292 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000293 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000294 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
295 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000296 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000297 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000298 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000299 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000300 void RewriteTryReturnStmts(Stmt *S);
301 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000302 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000303 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000304 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000305 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
306 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000307 Stmt *RewriteBreakStmt(BreakStmt *S);
308 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000309 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000310
Steve Naroff54055232008-10-27 17:20:55 +0000311 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000312 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000313
Mike Stump1eb44332009-09-09 15:08:12 +0000314 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000315 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000316 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000317 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000318 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000319 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000320
321 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
322 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700323
Stephen Hines176edba2014-12-01 14:53:08 -0800324 void Initialize(ASTContext &context) override = 0;
Stephen Hines651f13c2014-04-23 16:59:28 -0700325
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000326 // Metadata Rewriting.
327 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
328 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
329 StringRef prefix,
330 StringRef ClassName,
331 std::string &Result) = 0;
332 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
333 std::string &Result) = 0;
334 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
339 std::string &Result) = 0;
340
341 // Rewriting ivar access
342 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
343 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
344 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000345
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000346 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000347 // rewriting routines on the new ASTs.
348 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
349 Expr **args, unsigned nargs,
350 SourceLocation StartLoc=SourceLocation(),
351 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000352 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
353 QualType msgSendType,
354 QualType returnType,
355 SmallVectorImpl<QualType> &ArgTypes,
356 SmallVectorImpl<Expr*> &MsgExprs,
357 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000358 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
361
362 void SynthCountByEnumWithState(std::string &buf);
363 void SynthMsgSendFunctionDecl();
364 void SynthMsgSendSuperFunctionDecl();
365 void SynthMsgSendStretFunctionDecl();
366 void SynthMsgSendFpretFunctionDecl();
367 void SynthMsgSendSuperStretFunctionDecl();
368 void SynthGetClassFunctionDecl();
369 void SynthGetMetaClassFunctionDecl();
370 void SynthGetSuperClassFunctionDecl();
371 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000372 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000373
374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000376 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000377 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000378 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000379 std::string SynthesizeBlockImpl(BlockExpr *CE,
380 std::string Tag, std::string Desc);
381 std::string SynthesizeBlockDescriptor(std::string DescTag,
382 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000384 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000385 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000386 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000387 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000388 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
389 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000390 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Fariborz Jahanian58457172011-12-05 18:43:13 +0000392 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000393 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000394 void WarnAboutReturnGotoStmts(Stmt *S);
395 void HasReturnStmts(Stmt *S, bool &hasReturns);
396 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
397 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
398 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
399
400 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000401 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000402 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000403 void GetInnerBlockDeclRefExprs(Stmt *S,
404 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Stephen Hines176edba2014-12-01 14:53:08 -0800405 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Steve Naroff54055232008-10-27 17:20:55 +0000407 // We avoid calling Type::isBlockPointerType(), since it operates on the
408 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000409 bool isTopLevelBlockPointerType(QualType T) {
410 return isa<BlockPointerType>(T);
411 }
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000413 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
414 /// to a function pointer type and upon success, returns true; false
415 /// otherwise.
416 bool convertBlockPointerToFunctionPointer(QualType &T) {
417 if (isTopLevelBlockPointerType(T)) {
418 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
419 T = Context->getPointerType(BPT->getPointeeType());
420 return true;
421 }
422 return false;
423 }
424
Fariborz Jahanian58457172011-12-05 18:43:13 +0000425 bool needToScanForQualifiers(QualType T);
426 QualType getSuperStructType();
427 QualType getConstantStringStructType();
428 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
429 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
430
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000431 void convertToUnqualifiedObjCType(QualType &T) {
432 if (T->isObjCQualifiedIdType())
433 T = Context->getObjCIdType();
434 else if (T->isObjCQualifiedClassType())
435 T = Context->getObjCClassType();
436 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000437 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
438 if (const ObjCObjectPointerType * OBJPT =
439 T->getAsObjCInterfacePointerType()) {
440 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
441 T = QualType(IFaceT, 0);
442 T = Context->getPointerType(T);
443 }
444 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000445 }
446
Steve Naroff54055232008-10-27 17:20:55 +0000447 // FIXME: This predicate seems like it would be useful to add to ASTContext.
448 bool isObjCType(QualType T) {
449 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
450 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000451
Steve Naroff54055232008-10-27 17:20:55 +0000452 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Steve Naroff54055232008-10-27 17:20:55 +0000454 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
455 OCT == Context->getCanonicalType(Context->getObjCClassType()))
456 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Ted Kremenek6217b802009-07-29 21:53:49 +0000458 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000459 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000460 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000461 return true;
462 }
463 return false;
464 }
465 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000466 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000467 void GetExtentOfArgList(const char *Name, const char *&LParen,
468 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000469
Steve Naroff621edce2009-04-29 16:37:50 +0000470 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000471 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000472 if (From[i] == '"')
473 To += "\\\"";
474 else
475 To += From[i];
476 }
477 }
John McCalle23cf432010-12-14 08:05:40 +0000478
479 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000480 ArrayRef<QualType> args,
John McCalle23cf432010-12-14 08:05:40 +0000481 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000482 if (result == Context->getObjCInstanceType())
483 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000484 FunctionProtoType::ExtProtoInfo fpi;
485 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000486 return Context->getFunctionType(result, args, fpi);
John McCalle23cf432010-12-14 08:05:40 +0000487 }
John McCall9d125032010-01-15 18:39:57 +0000488
Fariborz Jahanian58457172011-12-05 18:43:13 +0000489 // Helper function: create a CStyleCastExpr with trivial type source info.
490 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
491 CastKind Kind, Expr *E) {
492 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700493 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
494 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian58457172011-12-05 18:43:13 +0000495 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700496
497 StringLiteral *getStringLiteral(StringRef Str) {
498 QualType StrType = Context->getConstantArrayType(
499 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
500 0);
501 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
502 /*Pascal=*/false, StrType, SourceLocation());
503 }
Fariborz Jahanian58457172011-12-05 18:43:13 +0000504 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000505
506 class RewriteObjCFragileABI : public RewriteObjC {
507 public:
508
509 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
510 DiagnosticsEngine &D, const LangOptions &LOpts,
511 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
512 D, LOpts,
513 silenceMacroWarn) {}
514
515 ~RewriteObjCFragileABI() {}
Stephen Hines176edba2014-12-01 14:53:08 -0800516 void Initialize(ASTContext &context) override;
Stephen Hines651f13c2014-04-23 16:59:28 -0700517
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000518 // Rewriting metadata
519 template<typename MethodIterator>
520 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
521 MethodIterator MethodEnd,
522 bool IsInstanceMethod,
523 StringRef prefix,
524 StringRef ClassName,
525 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700526 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
527 StringRef prefix, StringRef ClassName,
528 std::string &Result) override;
529 void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result) override;
532 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result) override;
534 void RewriteMetaDataIntoBuffer(std::string &Result) override;
535 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result) override;
537
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000538 // Rewriting ivar
Stephen Hines651f13c2014-04-23 16:59:28 -0700539 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result) override;
541 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000542 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000543}
544
Mike Stump1eb44332009-09-09 15:08:12 +0000545void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000547 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700549 for (const auto &I : fproto->param_types())
550 if (isTopLevelBlockPointerType(I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000551 // All the args are checked/rewritten. Don't call twice!
552 RewriteBlockPointerDecl(D);
553 break;
554 }
555 }
556}
557
558void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000559 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000560 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000561 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000562}
563
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000564static bool IsHeaderFile(const std::string &Filename) {
565 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000567 if (DotPos == std::string::npos) {
568 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000569 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000570 }
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000572 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
573 // C header: .h
574 // C++ header: .hh or .H;
575 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000576}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000577
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000579 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000580 bool silenceMacroWarn)
581 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
582 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000583 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000584 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000585 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000586 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
587 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000588 "rewriter doesn't support user-specified control flow semantics "
589 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000590}
591
Stephen Hines176edba2014-12-01 14:53:08 -0800592std::unique_ptr<ASTConsumer>
593clang::CreateObjCRewriter(const std::string &InFile, raw_ostream *OS,
594 DiagnosticsEngine &Diags, const LangOptions &LOpts,
595 bool SilenceRewriteMacroWarning) {
596 return llvm::make_unique<RewriteObjCFragileABI>(InFile, OS, Diags, LOpts,
597 SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000598}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000599
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000600void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000601 Context = &context;
602 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000603 TUDecl = Context->getTranslationUnitDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700604 MsgSendFunctionDecl = nullptr;
605 MsgSendSuperFunctionDecl = nullptr;
606 MsgSendStretFunctionDecl = nullptr;
607 MsgSendSuperStretFunctionDecl = nullptr;
608 MsgSendFpretFunctionDecl = nullptr;
609 GetClassFunctionDecl = nullptr;
610 GetMetaClassFunctionDecl = nullptr;
611 GetSuperClassFunctionDecl = nullptr;
612 SelGetUidFunctionDecl = nullptr;
613 CFStringFunctionDecl = nullptr;
614 ConstantStringClassReference = nullptr;
615 NSStringRecord = nullptr;
616 CurMethodDef = nullptr;
617 CurFunctionDef = nullptr;
618 CurFunctionDeclToDeclareForBlock = nullptr;
619 GlobalVarDecl = nullptr;
620 SuperStructDecl = nullptr;
621 ProtocolTypeDecl = nullptr;
622 ConstantStringDecl = nullptr;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000623 BcLabelCount = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700624 SuperConstructorFunctionDecl = nullptr;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000625 NumObjCStringLiterals = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700626 PropParentMap = nullptr;
627 CurrentBody = nullptr;
Steve Naroffb619d952008-12-09 12:56:34 +0000628 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000629 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000631 // Get the ID and start/end of the main file.
632 MainFileID = SM->getMainFileID();
633 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634 MainFileStart = MainBuf->getBufferStart();
635 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000636
David Blaikie4e4d0842012-03-11 07:00:24 +0000637 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000638}
639
Chris Lattnerf04da132007-10-24 17:06:59 +0000640//===----------------------------------------------------------------------===//
641// Top Level Driver Code
642//===----------------------------------------------------------------------===//
643
Chris Lattner682bf922009-03-29 16:50:03 +0000644void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000645 if (Diags.hasErrorOccurred())
646 return;
647
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000648 // Two cases: either the decl could be in the main file, or it could be in a
649 // #included file. If the former, rewrite it now. If the later, check to see
650 // if we rewrote the #include/#import.
651 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000652 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000653
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000654 // If this is for a builtin, ignore it.
655 if (Loc.isInvalid()) return;
656
Steve Naroffebf2b562007-10-23 23:50:29 +0000657 // Look for built-in declarations that we need to refer during the rewrite.
658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000659 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000660 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000661 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000662 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000663 ConstantStringClassReference = FVD;
664 return;
665 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000666 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667 if (ID->isThisDeclarationADefinition())
668 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000669 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000670 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000671 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000674 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000676 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000678 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000679 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
682 SourceLocation StartLoc = IFace->getLocStart();
683 do {
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
687 DG.push_back(*DI);
688 else
689 break;
690
Douglas Gregor7723fec2011-12-15 20:29:51 +0000691 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000692 } while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
694 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000695 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000696 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000697
698 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
701 SourceLocation StartLoc = Proto->getLocStart();
702 do {
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
706 DG.push_back(*DI);
707 else
708 break;
709
710 ++DI;
711 } while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
713 continue;
714 }
715 }
716
Chris Lattner682bf922009-03-29 16:50:03 +0000717 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000718 ++DI;
719 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000720 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000721 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000722 if (SM->isWrittenInMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000723 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000724}
725
Chris Lattnerf04da132007-10-24 17:06:59 +0000726//===----------------------------------------------------------------------===//
727// Syntactic (non-AST) Rewriting Code
728//===----------------------------------------------------------------------===//
729
Steve Naroffb29b4272008-04-14 22:03:09 +0000730void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000732 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000735 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000737 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000738 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr == '#') {
740 if (++BufPtr == MainBufEnd)
741 return;
742 while (*BufPtr == ' ' || *BufPtr == '\t')
743 if (++BufPtr == MainBufEnd)
744 return;
745 if (!strncmp(BufPtr, "import", ImportLen)) {
746 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000747 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000748 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000749 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000750 BufPtr += ImportLen;
751 }
752 }
753 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000754}
755
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000756static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000762 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 return S;
764}
765
Steve Naroffa0876e82008-12-02 17:36:43 +0000766void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000771 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000772 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000777 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000778 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffeb0646c2008-12-02 15:48:25 +0000783 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000787 if (!OID)
788 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000789 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000790 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000793 ObjCPropertyDecl::OBJC_PR_copy));
794 std::string Getr;
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000800 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
803 Getr += "{ ";
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808 Getr += "typedef ";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700809 const FunctionType *FPRetType = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000811 FPRetType);
812 Getr += " _TYPE";
813 if (FPRetType) {
814 Getr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818 Getr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -0700819 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000820 if (i) Getr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -0700821 std::string ParamStr =
822 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000823 Getr += ParamStr;
824 }
825 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700826 if (FT->getNumParams())
827 Getr += ", ";
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000837 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000847 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Steve Naroffeb0646c2008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000867 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000870 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000872 Setr += "0, ";
873 else
874 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000883 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000886}
Chris Lattner8a12c272007-10-11 18:38:32 +0000887
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000888static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
899}
900
Douglas Gregor375bb142011-12-27 22:43:10 +0000901void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000902 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000903 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000910void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000911 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000914 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000920 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000921 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000923 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000924 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000926}
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Craig Topper6b9240e2013-07-05 19:34:19 +0000928void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000929 std::string typedefString;
930 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000931 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000932 if (i == 0) {
933 typedefString += "// @class ";
934 typedefString += ForwardDecl->getNameAsString();
935 typedefString += ";\n";
936 }
937 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
938 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000939 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000940}
941
Steve Naroffb29b4272008-04-14 22:03:09 +0000942void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000943 // When method is a synthesized one, such as a getter/setter there is
944 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000945 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000946 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000947 SourceLocation LocStart = Method->getLocStart();
948 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Chandler Carruth64211622011-07-25 21:09:52 +0000950 if (SM->getExpansionLineNumber(LocEnd) >
951 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000952 InsertText(LocStart, "#if 0\n");
953 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000954 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000955 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000956 }
957}
958
Mike Stump1eb44332009-09-09 15:08:12 +0000959void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000960 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000961
Benjamin Kramerd999b372010-02-14 14:14:16 +0000962 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000963 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000964}
965
Steve Naroffb29b4272008-04-14 22:03:09 +0000966void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000967 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Steve Naroff423cb562007-10-30 13:30:57 +0000969 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000970 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Stephen Hines651f13c2014-04-23 16:59:28 -0700972 for (auto *I : CatDecl->properties())
973 RewriteProperty(I);
974 for (auto *I : CatDecl->instance_methods())
975 RewriteMethodDeclaration(I);
976 for (auto *I : CatDecl->class_methods())
977 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000978
Steve Naroff423cb562007-10-30 13:30:57 +0000979 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000980 ReplaceText(CatDecl->getAtEndRange().getBegin(),
981 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000982}
983
Steve Naroffb29b4272008-04-14 22:03:09 +0000984void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000985 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000986 assert(PDecl->isThisDeclarationADefinition());
987
Steve Naroff752d6ef2007-10-30 16:42:30 +0000988 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000989 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Stephen Hines651f13c2014-04-23 16:59:28 -0700991 for (auto *I : PDecl->instance_methods())
992 RewriteMethodDeclaration(I);
993 for (auto *I : PDecl->class_methods())
994 RewriteMethodDeclaration(I);
995 for (auto *I : PDecl->properties())
996 RewriteProperty(I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000997
Steve Naroff752d6ef2007-10-30 16:42:30 +0000998 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000999 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001000 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001001
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001002 // Must comment out @optional/@required
1003 const char *startBuf = SM->getCharacterData(LocStart);
1004 const char *endBuf = SM->getCharacterData(LocEnd);
1005 for (const char *p = startBuf; p < endBuf; p++) {
1006 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001007 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001008 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 }
1011 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001012 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001013 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001015 }
1016 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001017}
1018
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001019void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1020 SourceLocation LocStart = (*D.begin())->getLocStart();
1021 if (LocStart.isInvalid())
1022 llvm_unreachable("Invalid SourceLocation");
1023 // FIXME: handle forward protocol that are declared across multiple lines.
1024 ReplaceText(LocStart, 0, "// ");
1025}
1026
1027void
Craig Topper6b9240e2013-07-05 19:34:19 +00001028RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001029 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001030 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001031 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001032 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001033 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001034}
1035
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001036void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1037 const FunctionType *&FPRetType) {
1038 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001039 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001040 else if (T->isFunctionPointerType() ||
1041 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001042 // needs special handling, since pointer-to-functions have special
1043 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001044 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001045 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001046 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001047 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001048 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001049 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001050 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001051 ResultStr +=
1052 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001053 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001054 }
1055 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001056 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001057}
1058
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001059void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1060 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001061 std::string &ResultStr) {
1062 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001063 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001064 ResultStr += "\nstatic ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001065 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001066 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001068 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001069 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001071 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001072 NameStr += "_I_";
1073 else
1074 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001076 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001077 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001078
1079 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001080 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001081 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001082 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001085 {
1086 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001087 int len = selString.size();
1088 for (int i = 0; i < len; i++)
1089 if (selString[i] == ':')
1090 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001091 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001092 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001093 // Remember this name for metadata emission
1094 MethodInternalNames[OMD] = NameStr;
1095 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 // Rewrite arguments
1098 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001101 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001102 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001103 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001104 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001105 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001106 ResultStr += "struct ";
1107 }
1108 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001109 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001110 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 }
1112 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001113 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001114 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001116 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001117 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001118 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001120 // Method arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07001121 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001123 if (PDecl->getType()->isObjCQualifiedIdType()) {
1124 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001125 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001126 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001127 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001128 QualType QT = PDecl->getType();
1129 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001130 (void)convertBlockPointerToFunctionPointer(QT);
1131 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001132 ResultStr += Name;
1133 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001134 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001135 if (OMD->isVariadic())
1136 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001137 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Steve Naroff76e429d2008-07-16 14:40:40 +00001139 if (FPRetType) {
1140 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Steve Naroff76e429d2008-07-16 14:40:40 +00001142 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001143 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001144 ResultStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07001145 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001146 if (i) ResultStr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001147 std::string ParamStr =
1148 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001149 ResultStr += ParamStr;
1150 }
1151 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001152 if (FT->getNumParams())
1153 ResultStr += ", ";
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 ResultStr += "...";
1155 }
1156 ResultStr += ")";
1157 } else {
1158 ResultStr += "()";
1159 }
1160 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001162void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1164 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001166 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Stephen Hines651f13c2014-04-23 16:59:28 -07001168 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 std::string ResultStr;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001170 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001171 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001172 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001173
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001174 const char *startBuf = SM->getCharacterData(LocStart);
1175 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001176 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Stephen Hines651f13c2014-04-23 16:59:28 -07001179 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001180 std::string ResultStr;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001181 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001182 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001183 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185 const char *startBuf = SM->getCharacterData(LocStart);
1186 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001187 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001188 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001189 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1190 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001191
Benjamin Kramerd999b372010-02-14 14:14:16 +00001192 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001193}
1194
Steve Naroffb29b4272008-04-14 22:03:09 +00001195void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001196 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001197 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001198 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001199 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001201 ResultStr += "\n";
1202 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001205 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001206 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001207 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001208 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001209 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001210 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001211 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Stephen Hines651f13c2014-04-23 16:59:28 -07001213 for (auto *I : ClassDecl->properties())
1214 RewriteProperty(I);
1215 for (auto *I : ClassDecl->instance_methods())
1216 RewriteMethodDeclaration(I);
1217 for (auto *I : ClassDecl->class_methods())
1218 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001219
Steve Naroff2feac5e2007-10-30 03:43:13 +00001220 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001221 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1222 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001223}
1224
John McCall4b9c2d22011-11-06 09:01:30 +00001225Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1226 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001227
John McCall4b9c2d22011-11-06 09:01:30 +00001228 // We just magically know some things about the structure of this
1229 // expression.
1230 ObjCMessageExpr *OldMsg =
1231 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1232 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001233
John McCall4b9c2d22011-11-06 09:01:30 +00001234 // Because the rewriter doesn't allow us to rewrite rewritten code,
1235 // we need to suppress rewriting the sub-statements.
1236 Expr *Base, *RHS;
1237 {
1238 DisableReplaceStmtScope S(*this);
1239
1240 // Rebuild the base expression if we have one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001241 Base = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001242 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1243 Base = OldMsg->getInstanceReceiver();
1244 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1245 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1246 }
1247
1248 // Rebuild the RHS.
1249 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1250 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1251 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1252 }
1253
1254 // TODO: avoid this copy.
1255 SmallVector<SourceLocation, 1> SelLocs;
1256 OldMsg->getSelectorLocs(SelLocs);
1257
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001258 ObjCMessageExpr *NewMsg = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001259 switch (OldMsg->getReceiverKind()) {
1260 case ObjCMessageExpr::Class:
1261 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1262 OldMsg->getValueKind(),
1263 OldMsg->getLeftLoc(),
1264 OldMsg->getClassReceiverTypeInfo(),
1265 OldMsg->getSelector(),
1266 SelLocs,
1267 OldMsg->getMethodDecl(),
1268 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001269 OldMsg->getRightLoc(),
1270 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001271 break;
1272
1273 case ObjCMessageExpr::Instance:
1274 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1275 OldMsg->getValueKind(),
1276 OldMsg->getLeftLoc(),
1277 Base,
1278 OldMsg->getSelector(),
1279 SelLocs,
1280 OldMsg->getMethodDecl(),
1281 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001282 OldMsg->getRightLoc(),
1283 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001284 break;
1285
1286 case ObjCMessageExpr::SuperClass:
1287 case ObjCMessageExpr::SuperInstance:
1288 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1289 OldMsg->getValueKind(),
1290 OldMsg->getLeftLoc(),
1291 OldMsg->getSuperLoc(),
1292 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1293 OldMsg->getSuperType(),
1294 OldMsg->getSelector(),
1295 SelLocs,
1296 OldMsg->getMethodDecl(),
1297 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001298 OldMsg->getRightLoc(),
1299 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001300 break;
1301 }
1302
1303 Stmt *Replacement = SynthMessageExpr(NewMsg);
1304 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1305 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001306}
1307
John McCall4b9c2d22011-11-06 09:01:30 +00001308Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1309 SourceRange OldRange = PseudoOp->getSourceRange();
1310
1311 // We just magically know some things about the structure of this
1312 // expression.
1313 ObjCMessageExpr *OldMsg =
1314 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1315
1316 // Because the rewriter doesn't allow us to rewrite rewritten code,
1317 // we need to suppress rewriting the sub-statements.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001318 Expr *Base = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001319 {
1320 DisableReplaceStmtScope S(*this);
1321
1322 // Rebuild the base expression if we have one.
1323 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1324 Base = OldMsg->getInstanceReceiver();
1325 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1326 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001327 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001328 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001329
John McCall4b9c2d22011-11-06 09:01:30 +00001330 // Intentionally empty.
1331 SmallVector<SourceLocation, 1> SelLocs;
1332 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001333
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001334 ObjCMessageExpr *NewMsg = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001335 switch (OldMsg->getReceiverKind()) {
1336 case ObjCMessageExpr::Class:
1337 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1338 OldMsg->getValueKind(),
1339 OldMsg->getLeftLoc(),
1340 OldMsg->getClassReceiverTypeInfo(),
1341 OldMsg->getSelector(),
1342 SelLocs,
1343 OldMsg->getMethodDecl(),
1344 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001345 OldMsg->getRightLoc(),
1346 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001347 break;
1348
1349 case ObjCMessageExpr::Instance:
1350 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1351 OldMsg->getValueKind(),
1352 OldMsg->getLeftLoc(),
1353 Base,
1354 OldMsg->getSelector(),
1355 SelLocs,
1356 OldMsg->getMethodDecl(),
1357 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001358 OldMsg->getRightLoc(),
1359 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001360 break;
1361
1362 case ObjCMessageExpr::SuperClass:
1363 case ObjCMessageExpr::SuperInstance:
1364 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1365 OldMsg->getValueKind(),
1366 OldMsg->getLeftLoc(),
1367 OldMsg->getSuperLoc(),
1368 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1369 OldMsg->getSuperType(),
1370 OldMsg->getSelector(),
1371 SelLocs,
1372 OldMsg->getMethodDecl(),
1373 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001374 OldMsg->getRightLoc(),
1375 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001376 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001377 }
John McCall4b9c2d22011-11-06 09:01:30 +00001378
1379 Stmt *Replacement = SynthMessageExpr(NewMsg);
1380 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1381 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001382}
1383
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384/// SynthCountByEnumWithState - To print:
1385/// ((unsigned int (*)
1386/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001387/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001388/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001389/// "countByEnumeratingWithState:objects:count:"),
1390/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001391/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392///
Steve Naroffb29b4272008-04-14 22:03:09 +00001393void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001394 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1395 "id *, unsigned int))(void *)objc_msgSend)";
1396 buf += "\n\t\t";
1397 buf += "((id)l_collection,\n\t\t";
1398 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1399 buf += "\n\t\t";
1400 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001401 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001402}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001403
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001404/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1405/// statement to exit to its outer synthesized loop.
1406///
Steve Naroffb29b4272008-04-14 22:03:09 +00001407Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001408 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1409 return S;
1410 // replace break with goto __break_label
1411 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001413 SourceLocation startLoc = S->getLocStart();
1414 buf = "goto __break_label_";
1415 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001416 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001417
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001418 return nullptr;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419}
1420
1421/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1422/// statement to continue with its inner synthesized loop.
1423///
Steve Naroffb29b4272008-04-14 22:03:09 +00001424Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001425 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1426 return S;
1427 // replace continue with goto __continue_label
1428 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001430 SourceLocation startLoc = S->getLocStart();
1431 buf = "goto __continue_label_";
1432 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001433 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001435 return nullptr;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436}
1437
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001438/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001439/// It rewrites:
1440/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001442/// Into:
1443/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001444/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001445/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001446/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001448/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001449/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001450/// if (limit) {
1451/// unsigned long startMutations = *enumState.mutationsPtr;
1452/// do {
1453/// unsigned long counter = 0;
1454/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001455/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001456/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001457/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001458/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001459/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001460/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001461/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001462/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001464/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001465/// }
1466/// else
1467/// elem = nil;
1468/// }
1469///
Steve Naroffb29b4272008-04-14 22:03:09 +00001470Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001471 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001472 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001473 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001474 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001475 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001476 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001478 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001480 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001481 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001482 std::string buf;
1483 buf = "\n{\n\t";
1484 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1485 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001486 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001487 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001488 if (ElementType->isObjCQualifiedIdType() ||
1489 ElementType->isObjCQualifiedInterfaceType())
1490 // Simply use 'id' for all qualified types.
1491 elementTypeAsString = "id";
1492 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001493 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001494 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001495 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001496 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001497 buf += elementName;
1498 buf += ";\n\t";
1499 }
Chris Lattner06767512008-04-08 05:52:18 +00001500 else {
1501 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001502 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001503 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1504 if (VD->getType()->isObjCQualifiedIdType() ||
1505 VD->getType()->isObjCQualifiedInterfaceType())
1506 // Simply use 'id' for all qualified types.
1507 elementTypeAsString = "id";
1508 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001509 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001510 }
Mike Stump1eb44332009-09-09 15:08:12 +00001511
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001512 // struct __objcFastEnumerationState enumState = { 0 };
1513 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001514 // id __rw_items[16];
1515 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 // id l_collection = (id)
1517 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001518 // Find start location of 'collection' the hard way!
1519 const char *startCollectionBuf = startBuf;
1520 startCollectionBuf += 3; // skip 'for'
1521 startCollectionBuf = strchr(startCollectionBuf, '(');
1522 startCollectionBuf++; // skip '('
1523 // find 'in' and skip it.
1524 while (*startCollectionBuf != ' ' ||
1525 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1526 (*(startCollectionBuf+3) != ' ' &&
1527 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1528 startCollectionBuf++;
1529 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
1531 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001532 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001533 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001534 SourceLocation rightParenLoc = S->getRParenLoc();
1535 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001536 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001537 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001539 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001540 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001541 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001542 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 // ((unsigned int (*)
1544 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001545 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001546 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001547 // "countByEnumeratingWithState:objects:count:"),
1548 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001549 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001550 buf += "unsigned long limit =\n\t\t";
1551 SynthCountByEnumWithState(buf);
1552 buf += ";\n\t";
1553 /// if (limit) {
1554 /// unsigned long startMutations = *enumState.mutationsPtr;
1555 /// do {
1556 /// unsigned long counter = 0;
1557 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001558 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001559 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001560 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001561 buf += "if (limit) {\n\t";
1562 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1563 buf += "do {\n\t\t";
1564 buf += "unsigned long counter = 0;\n\t\t";
1565 buf += "do {\n\t\t\t";
1566 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1567 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1568 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001569 buf += " = (";
1570 buf += elementTypeAsString;
1571 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001573 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001575 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001577 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001578 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001579 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 /// }
1582 /// else
1583 /// elem = nil;
1584 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001585 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001586 buf = ";\n\t";
1587 buf += "__continue_label_";
1588 buf += utostr(ObjCBcLabelNo.back());
1589 buf += ": ;";
1590 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001591 buf += "} while (counter < limit);\n\t";
1592 buf += "} while (limit = ";
1593 SynthCountByEnumWithState(buf);
1594 buf += ");\n\t";
1595 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001596 buf += " = ((";
1597 buf += elementTypeAsString;
1598 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001599 buf += "__break_label_";
1600 buf += utostr(ObjCBcLabelNo.back());
1601 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 buf += "}\n\t";
1603 buf += "else\n\t\t";
1604 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001605 buf += " = ((";
1606 buf += elementTypeAsString;
1607 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001611 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001612 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001613 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001614 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001615 } else {
1616 /* Need to treat single statements specially. For example:
1617 *
1618 * for (A *a in b) if (stuff()) break;
1619 * for (A *a in b) xxxyy;
1620 *
1621 * The following code simply scans ahead to the semi to find the actual end.
1622 */
1623 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1624 const char *semiBuf = strchr(stmtBuf, ';');
1625 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001626 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001627 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001628 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001629 Stmts.pop_back();
1630 ObjCBcLabelNo.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001631 return nullptr;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001632}
1633
Mike Stump1eb44332009-09-09 15:08:12 +00001634/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001635/// This routine rewrites @synchronized(expr) stmt;
1636/// into:
1637/// objc_sync_enter(expr);
1638/// @try stmt @finally { objc_sync_exit(expr); }
1639///
Steve Naroffb29b4272008-04-14 22:03:09 +00001640Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001641 // Get the start location and compute the semi location.
1642 SourceLocation startLoc = S->getLocStart();
1643 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001645 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001646
1647 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001648 buf = "objc_sync_enter((id)";
1649 const char *lparenBuf = startBuf;
1650 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001651 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001652 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1653 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001654 // been rewritten! (which implies the SourceLocation's are invalid).
1655 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001656 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001657 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001658 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001659 buf = ");\n";
1660 // declare a new scope with two variables, _stack and _rethrow.
1661 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1662 buf += "int buf[18/*32-bit i386*/];\n";
1663 buf += "char *pointers[4];} _stack;\n";
1664 buf += "id volatile _rethrow = 0;\n";
1665 buf += "objc_exception_try_enter(&_stack);\n";
1666 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001667 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001668 startLoc = S->getSynchBody()->getLocEnd();
1669 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Steve Naroffc7089f12008-08-19 13:04:19 +00001671 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001672 SourceLocation lastCurlyLoc = startLoc;
1673 buf = "}\nelse {\n";
1674 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001675 buf += "}\n";
1676 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001677 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001678
1679 std::string syncBuf;
1680 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001681
1682 Expr *syncExpr = S->getSynchExpr();
1683 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1684 ? CK_BitCast :
1685 syncExpr->getType()->isBlockPointerType()
1686 ? CK_BlockPointerToObjCPointerCast
1687 : CK_CPointerToObjCPointerCast;
1688 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1689 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001690 std::string syncExprBufS;
1691 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001692 assert(syncExpr != nullptr && "Expected non-null Expr");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001693 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001694 syncBuf += syncExprBuf.str();
1695 syncBuf += ");";
1696
1697 buf += syncBuf;
1698 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001699 buf += "}\n";
1700 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Benjamin Kramerd999b372010-02-14 14:14:16 +00001702 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703
1704 bool hasReturns = false;
1705 HasReturnStmts(S->getSynchBody(), hasReturns);
1706 if (hasReturns)
1707 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1708
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001709 return nullptr;
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001710}
1711
Steve Naroffb85e77a2009-12-05 21:43:12 +00001712void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1713{
Steve Naroff8c565152008-12-05 17:03:39 +00001714 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001715 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001716 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001717 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001718
Steve Naroffb85e77a2009-12-05 21:43:12 +00001719 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001720 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001721 TryFinallyContainsReturnDiag);
1722 }
1723 return;
1724}
1725
Steve Naroffb85e77a2009-12-05 21:43:12 +00001726void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1727{
1728 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001729 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001730 if (*CI)
1731 HasReturnStmts(*CI, hasReturns);
1732
1733 if (isa<ReturnStmt>(S))
1734 hasReturns = true;
1735 return;
1736}
1737
1738void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1739 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001740 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001741 if (*CI) {
1742 RewriteTryReturnStmts(*CI);
1743 }
1744 if (isa<ReturnStmt>(S)) {
1745 SourceLocation startLoc = S->getLocStart();
1746 const char *startBuf = SM->getCharacterData(startLoc);
1747
1748 const char *semiBuf = strchr(startBuf, ';');
1749 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001750 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001751
1752 std::string buf;
1753 buf = "{ objc_exception_try_exit(&_stack); return";
1754
Benjamin Kramerd999b372010-02-14 14:14:16 +00001755 ReplaceText(startLoc, 6, buf);
1756 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001757 }
1758 return;
1759}
1760
1761void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1762 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001763 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001764 if (*CI) {
1765 RewriteSyncReturnStmts(*CI, syncExitBuf);
1766 }
1767 if (isa<ReturnStmt>(S)) {
1768 SourceLocation startLoc = S->getLocStart();
1769 const char *startBuf = SM->getCharacterData(startLoc);
1770
1771 const char *semiBuf = strchr(startBuf, ';');
1772 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001773 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001774
1775 std::string buf;
1776 buf = "{ objc_exception_try_exit(&_stack);";
1777 buf += syncExitBuf;
1778 buf += " return";
1779
Benjamin Kramerd999b372010-02-14 14:14:16 +00001780 ReplaceText(startLoc, 6, buf);
1781 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001782 }
1783 return;
1784}
1785
Steve Naroffb29b4272008-04-14 22:03:09 +00001786Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001787 // Get the start location and compute the semi location.
1788 SourceLocation startLoc = S->getLocStart();
1789 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Steve Naroff75730982007-11-07 04:08:17 +00001791 assert((*startBuf == '@') && "bogus @try location");
1792
1793 std::string buf;
1794 // declare a new scope with two variables, _stack and _rethrow.
1795 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1796 buf += "int buf[18/*32-bit i386*/];\n";
1797 buf += "char *pointers[4];} _stack;\n";
1798 buf += "id volatile _rethrow = 0;\n";
1799 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001800 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001801
Benjamin Kramerd999b372010-02-14 14:14:16 +00001802 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001803
Steve Naroff75730982007-11-07 04:08:17 +00001804 startLoc = S->getTryBody()->getLocEnd();
1805 startBuf = SM->getCharacterData(startLoc);
1806
1807 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Steve Naroff75730982007-11-07 04:08:17 +00001809 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001810 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001811 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001812 buf = " /* @catch begin */ else {\n";
1813 buf += " id _caught = objc_exception_extract(&_stack);\n";
1814 buf += " objc_exception_try_enter (&_stack);\n";
1815 buf += " if (_setjmp(_stack.buf))\n";
1816 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1817 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Benjamin Kramerd999b372010-02-14 14:14:16 +00001819 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001820 } else { /* no catch list */
1821 buf = "}\nelse {\n";
1822 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1823 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001824 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001825 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001826 Stmt *lastCatchBody = nullptr;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001827 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1828 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001829 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001830
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001831 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001832 buf = "if ("; // we are generating code for the first catch clause
1833 else
1834 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001835 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001836 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Steve Naroff75730982007-11-07 04:08:17 +00001838 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Steve Naroff75730982007-11-07 04:08:17 +00001840 const char *lParenLoc = strchr(startBuf, '(');
1841
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001842 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001843 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001844 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001845 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1846 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001847 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001848 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001849 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Steve Naroffe12e6922008-02-01 20:02:07 +00001851 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001852 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001853 } else if (catchDecl) {
1854 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001855 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001856 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001857 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001858 } else if (const ObjCObjectPointerType *Ptr =
1859 t->getAs<ObjCObjectPointerType>()) {
1860 // Should be a pointer to a class.
1861 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1862 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001863 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001864 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001865 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001867 }
1868 }
1869 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001870 lastCatchBody = Catch->getCatchBody();
1871 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001872 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1873 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1874 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1875 assert((*rParenBuf == ')') && "bogus @catch paren location");
1876 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Mike Stump1eb44332009-09-09 15:08:12 +00001878 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001879 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001880 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001881 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001882 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001883 }
Steve Naroff75730982007-11-07 04:08:17 +00001884 }
1885 // Complete the catch list...
1886 if (lastCatchBody) {
1887 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001888 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1889 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Steve Naroff378f47a2008-09-11 15:29:03 +00001891 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001892 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001893 buf = "} /* last catch end */\n";
1894 buf += "else {\n";
1895 buf += " _rethrow = _caught;\n";
1896 buf += " objc_exception_try_exit(&_stack);\n";
1897 buf += "} } /* @catch end */\n";
1898 if (!S->getFinallyStmt())
1899 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001900 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001901
Steve Naroff75730982007-11-07 04:08:17 +00001902 // Set lastCurlyLoc
1903 lastCurlyLoc = lastCatchBody->getLocEnd();
1904 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001905 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001906 startLoc = finalStmt->getLocStart();
1907 startBuf = SM->getCharacterData(startLoc);
1908 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Benjamin Kramerd999b372010-02-14 14:14:16 +00001910 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Steve Naroff75730982007-11-07 04:08:17 +00001912 Stmt *body = finalStmt->getFinallyBody();
1913 SourceLocation startLoc = body->getLocStart();
1914 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001915 assert(*SM->getCharacterData(startLoc) == '{' &&
1916 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001917 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001918 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001920 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001921 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001922 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001923 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Steve Naroff75730982007-11-07 04:08:17 +00001925 // Set lastCurlyLoc
1926 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Steve Naroff8c565152008-12-05 17:03:39 +00001928 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001929 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001930 } else { /* no finally clause - make sure we synthesize an implicit one */
1931 buf = "{ /* implicit finally clause */\n";
1932 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1933 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1934 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001935 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001936
1937 // Now check for any return/continue/go statements within the @try.
1938 // The implicit finally clause won't called if the @try contains any
1939 // jump statements.
1940 bool hasReturns = false;
1941 HasReturnStmts(S->getTryBody(), hasReturns);
1942 if (hasReturns)
1943 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001944 }
1945 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001946 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001947 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001948 return nullptr;
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001949}
1950
Mike Stump1eb44332009-09-09 15:08:12 +00001951// This can't be done with ReplaceStmt(S, ThrowExpr), since
1952// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001953// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001954Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001955 // Get the start location and compute the semi location.
1956 SourceLocation startLoc = S->getLocStart();
1957 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroff2bd03922007-11-07 15:32:26 +00001959 assert((*startBuf == '@') && "bogus @throw location");
1960
1961 std::string buf;
1962 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001963 if (S->getThrowExpr())
1964 buf = "objc_exception_throw(";
1965 else // add an implicit argument
1966 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001968 // handle "@ throw" correctly.
1969 const char *wBuf = strchr(startBuf, 'w');
1970 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001971 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Steve Naroff2bd03922007-11-07 15:32:26 +00001973 const char *semiBuf = strchr(startBuf, ';');
1974 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001975 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001976 ReplaceText(semiLoc, 1, ");");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001977 return nullptr;
Steve Naroff2bd03922007-11-07 15:32:26 +00001978}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001979
Steve Naroffb29b4272008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001981 // Create a new string expression.
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001982 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001983 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Stephen Hines651f13c2014-04-23 16:59:28 -07001984 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001985 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Chris Lattner07506182007-11-30 22:53:43 +00001987 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001988 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001989 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001990}
1991
Steve Naroffb29b4272008-04-14 22:03:09 +00001992Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001993 if (!SelGetUidFunctionDecl)
1994 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001995 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1996 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00001997 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07001998 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2000 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002001 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002002 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002003 return SelExp;
2004}
2005
Steve Naroffb29b4272008-04-14 22:03:09 +00002006CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002007 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2008 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002009 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002010 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002011
Steve Naroffebf2b562007-10-23 23:50:29 +00002012 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002013 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2014 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Steve Naroffebf2b562007-10-23 23:50:29 +00002016 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002017 QualType pToFunc = Context->getPointerType(msgSendType);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002018 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002019 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002020 DRE, nullptr, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002021
John McCall183700f2009-09-21 23:43:11 +00002022 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002024 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002025 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCallf89e55a2010-11-18 06:31:45 +00002026 FT->getCallResultType(*Context),
2027 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002028 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002029}
2030
Steve Naroffd5255f52007-11-01 13:24:47 +00002031static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2032 const char *&startRef, const char *&endRef) {
2033 while (startBuf < endBuf) {
2034 if (*startBuf == '<')
2035 startRef = startBuf; // mark the start.
2036 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002037 if (startRef && *startRef == '<') {
2038 endRef = startBuf; // mark the end.
2039 return true;
2040 }
2041 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002042 }
2043 startBuf++;
2044 }
2045 return false;
2046}
2047
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002048static void scanToNextArgument(const char *&argRef) {
2049 int angle = 0;
2050 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2051 if (*argRef == '<')
2052 angle++;
2053 else if (*argRef == '>')
2054 angle--;
2055 argRef++;
2056 }
2057 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2058}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002059
Steve Naroffb29b4272008-04-14 22:03:09 +00002060bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002061 if (T->isObjCQualifiedIdType())
2062 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002063 if (const PointerType *PT = T->getAs<PointerType>()) {
2064 if (PT->getPointeeType()->isObjCQualifiedIdType())
2065 return true;
2066 }
2067 if (T->isObjCObjectPointerType()) {
2068 T = T->getPointeeType();
2069 return T->isObjCQualifiedInterfaceType();
2070 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002071 if (T->isArrayType()) {
2072 QualType ElemTy = Context->getBaseElementType(T);
2073 return needToScanForQualifiers(ElemTy);
2074 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002075 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002076}
2077
Steve Naroff4f95b752008-07-29 18:15:38 +00002078void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2079 QualType Type = E->getType();
2080 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002081 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Steve Naroffcda658e2008-11-19 21:15:47 +00002083 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2084 Loc = ECE->getLParenLoc();
2085 EndLoc = ECE->getRParenLoc();
2086 } else {
2087 Loc = E->getLocStart();
2088 EndLoc = E->getLocEnd();
2089 }
2090 // This will defend against trying to rewrite synthesized expressions.
2091 if (Loc.isInvalid() || EndLoc.isInvalid())
2092 return;
2093
Steve Naroff4f95b752008-07-29 18:15:38 +00002094 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002095 const char *endBuf = SM->getCharacterData(EndLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002096 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff4f95b752008-07-29 18:15:38 +00002097 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2098 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002099 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2100 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002101 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002102 InsertText(LessLoc, "/*");
2103 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002104 }
2105 }
2106}
2107
Steve Naroffb29b4272008-04-14 22:03:09 +00002108void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002109 SourceLocation Loc;
2110 QualType Type;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002111 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002112 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2113 Loc = VD->getLocation();
2114 Type = VD->getType();
2115 }
2116 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2117 Loc = FD->getLocation();
2118 // Check for ObjC 'id' and class types that have been adorned with protocol
2119 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002120 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002121 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002122 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002123 if (!proto)
2124 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002125 Type = proto->getReturnType();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002126 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002127 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2128 Loc = FD->getLocation();
2129 Type = FD->getType();
2130 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002131 else
2132 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002133
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002134 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002135 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Steve Naroffd5255f52007-11-01 13:24:47 +00002137 const char *endBuf = SM->getCharacterData(Loc);
2138 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002139 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002140 startBuf--; // scan backward (from the decl location) for return type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002141 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroffd5255f52007-11-01 13:24:47 +00002142 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2143 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002144 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2145 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002146 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002147 InsertText(LessLoc, "/*");
2148 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002149 }
2150 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002151 if (!proto)
2152 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002153 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002154 const char *startBuf = SM->getCharacterData(Loc);
2155 const char *startFuncBuf = startBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07002156 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2157 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002158 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002159
Steve Naroffd5255f52007-11-01 13:24:47 +00002160 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161 // scan forward (from the decl location) for argument types.
2162 scanToNextArgument(endBuf);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002163 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroffd5255f52007-11-01 13:24:47 +00002164 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2165 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002166 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002167 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002168 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002169 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002171 InsertText(LessLoc, "/*");
2172 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002174 startBuf = ++endBuf;
2175 }
2176 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002177 // If the function name is derived from a macro expansion, then the
2178 // argument buffer will not follow the name. Need to speak with Chris.
2179 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002180 startBuf++; // scan forward (from the decl location) for argument types.
2181 startBuf++;
2182 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002183 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002184}
2185
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002186void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2187 QualType QT = ND->getType();
2188 const Type* TypePtr = QT->getAs<Type>();
2189 if (!isa<TypeOfExprType>(TypePtr))
2190 return;
2191 while (isa<TypeOfExprType>(TypePtr)) {
2192 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2193 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2194 TypePtr = QT->getAs<Type>();
2195 }
2196 // FIXME. This will not work for multiple declarators; as in:
2197 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002198 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002199 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2200 const char *startBuf = SM->getCharacterData(DeclLoc);
2201 if (ND->getInit()) {
2202 std::string Name(ND->getNameAsString());
2203 TypeAsString += " " + Name + " = ";
2204 Expr *E = ND->getInit();
2205 SourceLocation startLoc;
2206 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2207 startLoc = ECE->getLParenLoc();
2208 else
2209 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002210 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002211 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002212 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002213 }
2214 else {
2215 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002216 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002217 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002218 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002219 }
2220}
2221
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002222// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002223void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002224 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002225 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002226 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002227 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002228 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002229 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002230 SourceLocation(),
2231 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002232 SelGetUidIdent, getFuncType,
2233 nullptr, SC_Extern);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002234}
2235
Steve Naroffb29b4272008-04-14 22:03:09 +00002236void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002237 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002238 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002239 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002240 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002241 return;
2242 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002243 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002244}
2245
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002246void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002247 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002248 const char *argPtr = TypeString.c_str();
2249 if (!strchr(argPtr, '^')) {
2250 Str += TypeString;
2251 return;
2252 }
2253 while (*argPtr) {
2254 Str += (*argPtr == '^' ? '*' : *argPtr);
2255 argPtr++;
2256 }
2257}
2258
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002259// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002260void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2261 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002262 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002263 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002264 const char *argPtr = TypeString.c_str();
2265 int paren = 0;
2266 while (*argPtr) {
2267 switch (*argPtr) {
2268 case '(':
2269 Str += *argPtr;
2270 paren++;
2271 break;
2272 case ')':
2273 Str += *argPtr;
2274 paren--;
2275 break;
2276 case '^':
2277 Str += '*';
2278 if (paren == 1)
2279 Str += VD->getNameAsString();
2280 break;
2281 default:
2282 Str += *argPtr;
2283 break;
2284 }
2285 argPtr++;
2286 }
2287}
2288
2289
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002290void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2291 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2292 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2293 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2294 if (!proto)
2295 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002296 QualType Type = proto->getReturnType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002297 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002298 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002299 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002300 FdStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07002301 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002302 for (unsigned i = 0; i < numArgs; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002303 QualType ArgType = proto->getParamType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002304 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002305 if (i+1 < numArgs)
2306 FdStr += ", ";
2307 }
2308 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002309 InsertText(FunLocStart, FdStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002310 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002311}
2312
Benjamin Kramere5753592013-09-09 14:48:42 +00002313// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2314void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2315 if (SuperConstructorFunctionDecl)
Steve Naroffc0a123c2008-03-11 17:37:02 +00002316 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002317 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002318 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002319 QualType argT = Context->getObjCIdType();
2320 assert(!argT.isNull() && "Can't find 'id' type");
2321 ArgTys.push_back(argT);
2322 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002323 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002324 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002325 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002326 SourceLocation(),
2327 SourceLocation(),
2328 msgSendIdent, msgSendType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002329 nullptr, SC_Extern);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002330}
2331
Steve Naroff09b266e2007-10-30 23:14:51 +00002332// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002333void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002334 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002335 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002337 assert(!argT.isNull() && "Can't find 'id' type");
2338 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002340 assert(!argT.isNull() && "Can't find 'SEL' type");
2341 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002342 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002343 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002344 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002345 SourceLocation(),
2346 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002347 msgSendIdent, msgSendType,
2348 nullptr, SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002349}
2350
Steve Naroff874e2322007-11-15 10:28:18 +00002351// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002352void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002353 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002354 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002355 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002356 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002357 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002358 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2359 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2360 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002361 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002362 assert(!argT.isNull() && "Can't find 'SEL' type");
2363 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002364 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002365 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002366 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002367 SourceLocation(),
2368 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002369 msgSendIdent, msgSendType,
2370 nullptr, SC_Extern);
Steve Naroff874e2322007-11-15 10:28:18 +00002371}
2372
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002373// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002374void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002375 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002376 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002378 assert(!argT.isNull() && "Can't find 'id' type");
2379 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002380 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002381 assert(!argT.isNull() && "Can't find 'SEL' type");
2382 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002383 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002384 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002385 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002386 SourceLocation(),
2387 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002388 msgSendIdent, msgSendType,
2389 nullptr, SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002390}
2391
Mike Stump1eb44332009-09-09 15:08:12 +00002392// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002393// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002394void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002395 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002397 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002398 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002399 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002400 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002401 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2402 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2403 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002404 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002405 assert(!argT.isNull() && "Can't find 'SEL' type");
2406 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002407 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002408 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002409 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002410 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002411 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002412 msgSendIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002413 msgSendType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002414 SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415}
2416
Steve Naroff1284db82008-05-08 22:02:18 +00002417// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002418void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002420 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002427 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002428 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002429 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002430 SourceLocation(),
2431 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002432 msgSendIdent, msgSendType,
2433 nullptr, SC_Extern);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002434}
2435
Steve Naroff09b266e2007-10-30 23:14:51 +00002436// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002437void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002438 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002439 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002440 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002441 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002442 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002443 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002444 SourceLocation(),
2445 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002446 getClassIdent, getClassType,
2447 nullptr, SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002448}
2449
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002450// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2451void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2452 IdentifierInfo *getSuperClassIdent =
2453 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002455 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002456 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002457 ArgTys);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002458 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002459 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002460 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002461 getSuperClassIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002462 getClassType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002463 SC_Extern);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002464}
2465
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002466// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002467void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002468 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002469 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002470 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002471 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002472 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002473 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002474 SourceLocation(),
2475 SourceLocation(),
2476 getClassIdent, getClassType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002477 nullptr, SC_Extern);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002478}
2479
Steve Naroffb29b4272008-04-14 22:03:09 +00002480Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002481 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002482 QualType strType = getConstantStringStructType();
2483
2484 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002485
2486 std::string tmpName = InFileName;
2487 unsigned i;
2488 for (i=0; i < tmpName.length(); i++) {
2489 char c = tmpName.at(i);
Stephen Hines651f13c2014-04-23 16:59:28 -07002490 // replace any non-alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002491 if (!isAlphanumeric(c))
Steve Naroff7691d9b2008-05-31 03:35:42 +00002492 tmpName[i] = '_';
2493 }
2494 S += tmpName;
2495 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002496 S += utostr(NumObjCStringLiterals++);
2497
Steve Naroffba92b2e2008-03-27 22:29:16 +00002498 Preamble += "static __NSConstantStringImpl " + S;
2499 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2500 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002501 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002502 std::string prettyBufS;
2503 llvm::raw_string_ostream prettyBuf(prettyBufS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002504 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002505 Preamble += prettyBuf.str();
2506 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002507 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002508
2509 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002510 SourceLocation(), &Context->Idents.get(S),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002511 strType, nullptr, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002512 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002513 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002514 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002515 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002516 VK_RValue, OK_Ordinary,
2517 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002518 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002519 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002520 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002521 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002522 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002523 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002524}
2525
Steve Naroff874e2322007-11-15 10:28:18 +00002526// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002527QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002528 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002529 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002530 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002531 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002532 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Steve Naroff874e2322007-11-15 10:28:18 +00002534 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002535 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002536 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002537 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002538
Steve Naroff874e2322007-11-15 10:28:18 +00002539 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002540 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002541 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002542 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002543 SourceLocation(), nullptr,
2544 FieldTypes[i], nullptr,
2545 /*BitWidth=*/nullptr,
Richard Smith7a614d82011-06-11 17:19:42 +00002546 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002547 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002548 }
Mike Stump1eb44332009-09-09 15:08:12 +00002549
Douglas Gregor838db382010-02-11 01:19:42 +00002550 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002551 }
2552 return Context->getTagDeclType(SuperStructDecl);
2553}
2554
Steve Naroffb29b4272008-04-14 22:03:09 +00002555QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002556 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002557 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002558 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002559 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002560 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002561
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002562 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002563 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002564 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002565 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002566 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002567 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002568 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002569 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002570
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002571 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002572 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002573 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2574 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002575 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002576 SourceLocation(), nullptr,
2577 FieldTypes[i], nullptr,
2578 /*BitWidth=*/nullptr,
Richard Smith7a614d82011-06-11 17:19:42 +00002579 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002580 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002581 }
2582
Douglas Gregor838db382010-02-11 01:19:42 +00002583 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002584 }
2585 return Context->getTagDeclType(ConstantStringDecl);
2586}
2587
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002588CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2589 QualType msgSendType,
2590 QualType returnType,
2591 SmallVectorImpl<QualType> &ArgTypes,
2592 SmallVectorImpl<Expr*> &MsgExprs,
2593 ObjCMethodDecl *Method) {
2594 // Create a reference to the objc_msgSend_stret() declaration.
2595 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2596 false, msgSendType,
2597 VK_LValue, SourceLocation());
2598 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2599 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2600 Context->getPointerType(Context->VoidTy),
2601 CK_BitCast, STDRE);
2602 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002603 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2604 Method ? Method->isVariadic()
2605 : false);
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002606 castType = Context->getPointerType(castType);
2607 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2608 cast);
2609
2610 // Don't forget the parens to enforce the proper binding.
2611 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2612
2613 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002614 CallExpr *STCE = new (Context) CallExpr(
2615 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002616 return STCE;
2617
2618}
2619
2620
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002621Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2622 SourceLocation StartLoc,
2623 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002624 if (!SelGetUidFunctionDecl)
2625 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002626 if (!MsgSendFunctionDecl)
2627 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002628 if (!MsgSendSuperFunctionDecl)
2629 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002630 if (!MsgSendStretFunctionDecl)
2631 SynthMsgSendStretFunctionDecl();
2632 if (!MsgSendSuperStretFunctionDecl)
2633 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002634 if (!MsgSendFpretFunctionDecl)
2635 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002636 if (!GetClassFunctionDecl)
2637 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002638 if (!GetSuperClassFunctionDecl)
2639 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002640 if (!GetMetaClassFunctionDecl)
2641 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Steve Naroff874e2322007-11-15 10:28:18 +00002643 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002644 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2645 // May need to use objc_msgSend_stret() as well.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002646 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroff621edce2009-04-29 16:37:50 +00002647 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002648 QualType resultType = mDecl->getReturnType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002649 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002650 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002651 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002652 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002653 }
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Steve Naroff934f2762007-10-24 22:48:43 +00002655 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002657 switch (Exp->getReceiverKind()) {
2658 case ObjCMessageExpr::SuperClass: {
2659 MsgSendFlavor = MsgSendSuperFunctionDecl;
2660 if (MsgSendStretFlavor)
2661 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2662 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Douglas Gregor04badcf2010-04-21 00:45:42 +00002664 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Chris Lattner5f9e2722011-07-23 10:55:15 +00002666 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002667
Douglas Gregor04badcf2010-04-21 00:45:42 +00002668 // set the receiver to self, the first argument to all methods.
2669 InitExprs.push_back(
2670 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002671 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002672 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002673 false,
John McCallf89e55a2010-11-18 06:31:45 +00002674 Context->getObjCIdType(),
2675 VK_RValue,
2676 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002677 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Douglas Gregor04badcf2010-04-21 00:45:42 +00002679 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002680 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002681 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683 &ClsExprs[0],
2684 ClsExprs.size(),
2685 StartLoc,
2686 EndLoc);
2687 // (Class)objc_getClass("CurrentClass")
2688 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2689 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002690 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002691 ClsExprs.clear();
2692 ClsExprs.push_back(ArgExpr);
2693 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2694 &ClsExprs[0], ClsExprs.size(),
2695 StartLoc, EndLoc);
2696
2697 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2698 // To turn off a warning, type-cast to 'id'
2699 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2700 NoTypeInfoCStyleCastExpr(Context,
2701 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002702 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002703 // struct objc_super
2704 QualType superType = getSuperStructType();
2705 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002706
Francois Pichet62ec1f22011-09-17 17:15:52 +00002707 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002708 SynthSuperConstructorFunctionDecl();
2709 // Simulate a constructor call...
2710 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002711 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002712 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002713 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002714 superType, VK_LValue,
2715 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002716 // The code for super is a little tricky to prevent collision with
2717 // the structure definition in the header. The rewriter has it's own
2718 // internal definition (__rw_objc_super) that is uses. This is why
2719 // we need the cast below. For example:
2720 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2721 //
John McCall2de56d12010-08-25 11:45:40 +00002722 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002723 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002724 VK_RValue, OK_Ordinary,
2725 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2727 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002728 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002729 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002730 // (struct objc_super) { <exprs from above> }
2731 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002732 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733 SourceLocation());
2734 TypeSourceInfo *superTInfo
2735 = Context->getTrivialTypeSourceInfo(superType);
2736 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002737 superType, VK_LValue,
2738 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002740 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002741 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002742 VK_RValue, OK_Ordinary,
2743 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002744 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002745 MsgExprs.push_back(SuperRep);
2746 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002747 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002748
2749 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002750 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002751 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002752 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002753 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002754 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002755 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2756 &ClsExprs[0],
2757 ClsExprs.size(),
2758 StartLoc, EndLoc);
2759 MsgExprs.push_back(Cls);
2760 break;
2761 }
2762
2763 case ObjCMessageExpr::SuperInstance:{
2764 MsgSendFlavor = MsgSendSuperFunctionDecl;
2765 if (MsgSendStretFlavor)
2766 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2767 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2768 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002769 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002770
2771 InitExprs.push_back(
2772 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002773 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002774 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002775 false,
John McCallf89e55a2010-11-18 06:31:45 +00002776 Context->getObjCIdType(),
2777 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002778 ); // set the 'receiver'.
2779
2780 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002781 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002782 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002783 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2784 &ClsExprs[0],
2785 ClsExprs.size(),
2786 StartLoc, EndLoc);
2787 // (Class)objc_getClass("CurrentClass")
2788 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2789 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002790 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002791 ClsExprs.clear();
2792 ClsExprs.push_back(ArgExpr);
2793 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2794 &ClsExprs[0], ClsExprs.size(),
2795 StartLoc, EndLoc);
2796
2797 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2798 // To turn off a warning, type-cast to 'id'
2799 InitExprs.push_back(
2800 // set 'super class', using class_getSuperclass().
2801 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002802 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002803 // struct objc_super
2804 QualType superType = getSuperStructType();
2805 Expr *SuperRep;
2806
Francois Pichet62ec1f22011-09-17 17:15:52 +00002807 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002808 SynthSuperConstructorFunctionDecl();
2809 // Simulate a constructor call...
2810 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002811 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002812 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002813 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002814 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002815 // The code for super is a little tricky to prevent collision with
2816 // the structure definition in the header. The rewriter has it's own
2817 // internal definition (__rw_objc_super) that is uses. This is why
2818 // we need the cast below. For example:
2819 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2820 //
John McCall2de56d12010-08-25 11:45:40 +00002821 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002823 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 SourceLocation());
2825 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2826 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002827 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002828 } else {
2829 // (struct objc_super) { <exprs from above> }
2830 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002831 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 SourceLocation());
2833 TypeSourceInfo *superTInfo
2834 = Context->getTrivialTypeSourceInfo(superType);
2835 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002836 superType, VK_RValue, ILE,
2837 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 }
2839 MsgExprs.push_back(SuperRep);
2840 break;
2841 }
2842
2843 case ObjCMessageExpr::Instance: {
2844 // Remove all type-casts because it may contain objc-style types; e.g.
2845 // Foo<Proto> *.
2846 Expr *recExpr = Exp->getInstanceReceiver();
2847 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2848 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002849 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2850 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2851 ? CK_BlockPointerToObjCPointerCast
2852 : CK_CPointerToObjCPointerCast;
2853
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002855 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 MsgExprs.push_back(recExpr);
2857 break;
2858 }
2859 }
2860
Steve Naroffbeaf2992007-11-03 11:27:19 +00002861 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002862 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002863 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff934f2762007-10-24 22:48:43 +00002864 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002865 &SelExprs[0], SelExprs.size(),
2866 StartLoc,
2867 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002868 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Steve Naroff934f2762007-10-24 22:48:43 +00002870 // Now push any user supplied arguments.
2871 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002872 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002873 // Make all implicit casts explicit...ICE comes in handy:-)
2874 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2875 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002876 QualType type = ICE->getType();
2877 if (needToScanForQualifiers(type))
2878 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002879 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002880 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002881 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002882 CastKind CK;
2883 if (SubExpr->getType()->isIntegralType(*Context) &&
2884 type->isBooleanType()) {
2885 CK = CK_IntegralToBoolean;
2886 } else if (type->isObjCObjectPointerType()) {
2887 if (SubExpr->getType()->isBlockPointerType()) {
2888 CK = CK_BlockPointerToObjCPointerCast;
2889 } else if (SubExpr->getType()->isPointerType()) {
2890 CK = CK_CPointerToObjCPointerCast;
2891 } else {
2892 CK = CK_BitCast;
2893 }
2894 } else {
2895 CK = CK_BitCast;
2896 }
2897
2898 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002899 }
2900 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002901 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002902 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002903 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002904 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002905 CastKind CK;
2906 if (userExpr->getType()->isIntegralType(*Context)) {
2907 CK = CK_IntegralToPointer;
2908 } else if (userExpr->getType()->isBlockPointerType()) {
2909 CK = CK_BlockPointerToObjCPointerCast;
2910 } else if (userExpr->getType()->isPointerType()) {
2911 CK = CK_CPointerToObjCPointerCast;
2912 } else {
2913 CK = CK_BitCast;
2914 }
John McCall9d125032010-01-15 18:39:57 +00002915 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002916 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002917 }
Mike Stump1eb44332009-09-09 15:08:12 +00002918 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002919 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002920 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2921 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002922 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002923 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002924 }
Steve Naroffab972d32007-11-04 22:37:50 +00002925 // Generate the funky cast.
2926 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002927 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002928 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Steve Naroffab972d32007-11-04 22:37:50 +00002930 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002931 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2932 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2933 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002934 ArgTypes.push_back(Context->getObjCIdType());
2935 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002936 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002937 // Push any user argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -07002938 for (const auto *PI : OMD->params()) {
2939 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002940 ? Context->getObjCIdType()
Stephen Hines651f13c2014-04-23 16:59:28 -07002941 : PI->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002942 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002943 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002944 ArgTypes.push_back(t);
2945 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002946 returnType = Exp->getType();
2947 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002948 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002949 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002950 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002951 }
2952 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002953 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002954
Steve Naroffab972d32007-11-04 22:37:50 +00002955 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002956 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002957 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002958
Mike Stump1eb44332009-09-09 15:08:12 +00002959 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002960 // If we don't do this cast, we get the following bizarre warning/note:
2961 // xx.m:13: warning: function called through a non-compatible type
2962 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002963 cast = NoTypeInfoCStyleCastExpr(Context,
2964 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002965 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Steve Naroffab972d32007-11-04 22:37:50 +00002967 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002968 // If we don't have a method decl, force a variadic cast.
2969 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalle23cf432010-12-14 08:05:40 +00002970 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002971 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002972 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002973 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002974 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002975
2976 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002977 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002978
John McCall183700f2009-09-21 23:43:11 +00002979 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002980 CallExpr *CE = new (Context)
2981 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002982 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002983 if (MsgSendStretFlavor) {
2984 // We have the method which returns a struct/union. Must also generate
2985 // call to objc_msgSend_stret and hang both varieties on a conditional
2986 // expression which dictate which one to envoke depending on size of
2987 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002988
2989 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2990 msgSendType, returnType,
2991 ArgTypes, MsgExprs,
2992 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002994 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002995 UnaryExprOrTypeTraitExpr *sizeofExpr =
2996 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2997 Context->getTrivialTypeSourceInfo(returnType),
2998 Context->getSizeType(), SourceLocation(),
2999 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003000 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3001 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3002 // For X86 it is more complicated and some kind of target specific routine
3003 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003004 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003005 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003006 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3007 llvm::APInt(IntSize, 8),
3008 Context->IntTy,
3009 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003010 BinaryOperator *lessThanExpr =
3011 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003012 VK_RValue, OK_Ordinary, SourceLocation(),
3013 false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003014 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003015 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003016 new (Context) ConditionalOperator(lessThanExpr,
3017 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003018 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003019 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003020 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3021 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003022 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003023 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003024 return ReplacingStmt;
3025}
3026
Steve Naroffb29b4272008-04-14 22:03:09 +00003027Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003028 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3029 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003030
Steve Naroff934f2762007-10-24 22:48:43 +00003031 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003032 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003034 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003035 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003036}
3037
Steve Naroff621edce2009-04-29 16:37:50 +00003038// typedef struct objc_object Protocol;
3039QualType RewriteObjC::getProtocolType() {
3040 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003041 TypeSourceInfo *TInfo
3042 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003043 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003044 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003045 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003046 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003047 }
3048 return Context->getTypeDeclType(ProtocolTypeDecl);
3049}
3050
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003051/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003052/// a synthesized/forward data reference (to the protocol's metadata).
3053/// The forward references (and metadata) are generated in
3054/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003055Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003056 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3057 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003058 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003059 SourceLocation(), ID, getProtocolType(),
3060 nullptr, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003061 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3062 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003063 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003064 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003065 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003066 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003067 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003068 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003069 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003070 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003071 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003072 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003074}
3075
Mike Stump1eb44332009-09-09 15:08:12 +00003076bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003077 const char *endBuf) {
3078 while (startBuf < endBuf) {
3079 if (*startBuf == '#') {
3080 // Skip whitespace.
3081 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3082 ;
3083 if (!strncmp(startBuf, "if", strlen("if")) ||
3084 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3085 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3086 !strncmp(startBuf, "define", strlen("define")) ||
3087 !strncmp(startBuf, "undef", strlen("undef")) ||
3088 !strncmp(startBuf, "else", strlen("else")) ||
3089 !strncmp(startBuf, "elif", strlen("elif")) ||
3090 !strncmp(startBuf, "endif", strlen("endif")) ||
3091 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3092 !strncmp(startBuf, "include", strlen("include")) ||
3093 !strncmp(startBuf, "import", strlen("import")) ||
3094 !strncmp(startBuf, "include_next", strlen("include_next")))
3095 return true;
3096 }
3097 startBuf++;
3098 }
3099 return false;
3100}
3101
Fariborz Jahanian58457172011-12-05 18:43:13 +00003102/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003103/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003104void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003105 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003106 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003107 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003108 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003109 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003110 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003111 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003113 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003114 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003115 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003116
Steve Narofffea763e82007-11-14 19:25:57 +00003117 const char *startBuf = SM->getCharacterData(LocStart);
3118 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003120 // If no ivars and no root or if its root, directly or indirectly,
3121 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003122 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003123 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003124 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003125 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003126 return;
3127 }
Mike Stump1eb44332009-09-09 15:08:12 +00003128
3129 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003130 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003131 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003132 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003133 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003134 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003135
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003136 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003137 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003138 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003139 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003140 // If the buffer contains preprocessor directives, we do more fine-grained
3141 // rewrites. This is intended to fix code that looks like (which occurs in
3142 // NSURL.h, for example):
3143 //
3144 // #ifdef XYZ
3145 // @interface Foo : NSObject
3146 // #else
3147 // @interface FooBar : NSObject
3148 // #endif
3149 // {
3150 // int i;
3151 // }
3152 // @end
3153 //
3154 // This clause is segregated to avoid breaking the common case.
3155 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003156 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003157 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003158 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003159 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003160
Chris Lattnercafeb352009-02-20 18:18:36 +00003161 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003162 // advance to the end of the referenced protocols.
3163 while (endHeader < cursor && *endHeader != '>') endHeader++;
3164 endHeader++;
3165 }
3166 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003167 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003168 } else {
3169 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003170 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003171 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003172 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003173 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003174 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003175 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003176 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003177 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003178
Steve Narofffea763e82007-11-14 19:25:57 +00003179 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003180 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003181 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003182 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003183 }
3184 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Steve Narofffea763e82007-11-14 19:25:57 +00003186 // Now comment out any visibility specifiers.
3187 while (cursor < endBuf) {
3188 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003189 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003190 // Skip whitespace.
3191 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3192 /*scan*/;
3193
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003194 // FIXME: presence of @public, etc. inside comment results in
3195 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003196 if (!strncmp(cursor, "public", strlen("public")) ||
3197 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003198 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003199 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003200 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003201 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003202 // FIXME: If there are cases where '<' is used in ivar declaration part
3203 // of user code, then scan the ivar list and use needToScanForQualifiers
3204 // for type checking.
3205 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003206 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003207 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003208 cursor = strchr(cursor, '>');
3209 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003210 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003211 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003212 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003213 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003214 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003215 }
Steve Narofffea763e82007-11-14 19:25:57 +00003216 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003217 }
Steve Narofffea763e82007-11-14 19:25:57 +00003218 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003219 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003220 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003221 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003222 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003223 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003224 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003225 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003226 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003227 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003228 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003229 // Mark this struct as having been generated.
Stephen Hines176edba2014-12-01 14:53:08 -08003230 if (!ObjCSynthesizedStructs.insert(CDecl).second)
David Blaikieb219cfc2011-09-23 05:06:16 +00003231 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003232}
3233
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003234//===----------------------------------------------------------------------===//
3235// Meta Data Emission
3236//===----------------------------------------------------------------------===//
3237
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003238
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003239/// RewriteImplementations - This routine rewrites all method implementations
3240/// and emits meta-data.
3241
Steve Narofface66252008-11-13 20:07:04 +00003242void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003243 int ClsDefCount = ClassImplementation.size();
3244 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003246 // Rewrite implemented methods
3247 for (int i = 0; i < ClsDefCount; i++)
3248 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003249
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003250 for (int i = 0; i < CatDefCount; i++)
3251 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003252}
Mike Stump1eb44332009-09-09 15:08:12 +00003253
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003254void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3255 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003256 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003257 assert(BlockByRefDeclNo.count(VD) &&
3258 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003259 if (def)
3260 ResultStr += "struct ";
3261 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003262 "_" + utostr(BlockByRefDeclNo[VD]) ;
3263}
3264
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003265static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3266 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3267 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3268 return false;
3269}
3270
Steve Naroff54055232008-10-27 17:20:55 +00003271std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003272 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003273 std::string Tag) {
3274 const FunctionType *AFT = CE->getFunctionType();
Stephen Hines651f13c2014-04-23 16:59:28 -07003275 QualType RT = AFT->getReturnType();
Steve Naroff54055232008-10-27 17:20:55 +00003276 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003277 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003278 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003279
Steve Naroff54055232008-10-27 17:20:55 +00003280 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003281
Douglas Gregor72564e72009-02-26 23:50:07 +00003282 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003283 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003284 // block (to reference imported block decl refs).
3285 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003286 } else if (BD->param_empty()) {
3287 S += "(" + StructRef + " *__cself)";
3288 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003289 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003290 assert(FT && "SynthesizeBlockFunc: No function proto");
3291 S += '(';
3292 // first add the implicit argument.
3293 S += StructRef + " *__cself, ";
3294 std::string ParamStr;
3295 for (BlockDecl::param_iterator AI = BD->param_begin(),
3296 E = BD->param_end(); AI != E; ++AI) {
3297 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003299 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003300 (void)convertBlockPointerToFunctionPointer(QT);
3301 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003302 S += ParamStr;
3303 }
3304 if (FT->isVariadic()) {
3305 if (!BD->param_empty()) S += ", ";
3306 S += "...";
3307 }
3308 S += ')';
3309 }
3310 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003311
Steve Naroff54055232008-10-27 17:20:55 +00003312 // Create local declarations to avoid rewriting all closure decl ref exprs.
3313 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00003314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003315 E = BlockByRefDecls.end(); I != E; ++I) {
3316 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003317 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003318 std::string TypeString;
3319 RewriteByRefString(TypeString, Name, (*I));
3320 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003321 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003322 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003323 }
Steve Naroff54055232008-10-27 17:20:55 +00003324 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003325 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003326 E = BlockByCopyDecls.end(); I != E; ++I) {
3327 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003328 // Handle nested closure invocation. For example:
3329 //
3330 // void (^myImportedClosure)(void);
3331 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003332 //
Steve Naroff54055232008-10-27 17:20:55 +00003333 // void (^anotherClosure)(void);
3334 // anotherClosure = ^(void) {
3335 // myImportedClosure(); // import and invoke the closure
3336 // };
3337 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003338 if (isTopLevelBlockPointerType((*I)->getType())) {
3339 RewriteBlockPointerTypeVariable(S, (*I));
3340 S += " = (";
3341 RewriteBlockPointerType(S, (*I)->getType());
3342 S += ")";
3343 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3344 }
3345 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003346 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003347 QualType QT = (*I)->getType();
3348 if (HasLocalVariableExternalStorage(*I))
3349 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003350 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003351 S += Name + " = __cself->" +
3352 (*I)->getNameAsString() + "; // bound by copy\n";
3353 }
Steve Naroff54055232008-10-27 17:20:55 +00003354 }
3355 std::string RewrittenStr = RewrittenBlockExprs[CE];
3356 const char *cstr = RewrittenStr.c_str();
3357 while (*cstr++ != '{') ;
3358 S += cstr;
3359 S += "\n";
3360 return S;
3361}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003362
Steve Naroff54055232008-10-27 17:20:55 +00003363std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003364 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003365 std::string Tag) {
3366 std::string StructRef = "struct " + Tag;
3367 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Steve Naroff54055232008-10-27 17:20:55 +00003369 S += funcName;
3370 S += "_block_copy_" + utostr(i);
3371 S += "(" + StructRef;
3372 S += "*dst, " + StructRef;
3373 S += "*src) {";
Stephen Hines176edba2014-12-01 14:53:08 -08003374 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003375 S += "_Block_object_assign((void*)&dst->";
Stephen Hines176edba2014-12-01 14:53:08 -08003376 S += VD->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003377 S += ", (void*)src->";
Stephen Hines176edba2014-12-01 14:53:08 -08003378 S += VD->getNameAsString();
3379 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003380 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003381 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003382 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003383 else
3384 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003385 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003386 S += "}\n";
3387
Steve Naroff54055232008-10-27 17:20:55 +00003388 S += "\nstatic void __";
3389 S += funcName;
3390 S += "_block_dispose_" + utostr(i);
3391 S += "(" + StructRef;
3392 S += "*src) {";
Stephen Hines176edba2014-12-01 14:53:08 -08003393 for (ValueDecl *VD : ImportedBlockDecls) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003394 S += "_Block_object_dispose((void*)src->";
Stephen Hines176edba2014-12-01 14:53:08 -08003395 S += VD->getNameAsString();
3396 if (BlockByRefDeclsPtrSet.count(VD))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003397 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003398 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003399 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003400 else
3401 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003402 }
Mike Stump1eb44332009-09-09 15:08:12 +00003403 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003404 return S;
3405}
3406
Steve Naroff01aec112009-12-06 21:14:13 +00003407std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3408 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003409 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003410 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Steve Naroff54055232008-10-27 17:20:55 +00003412 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003413 S += " struct " + Desc;
3414 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Steve Naroff01aec112009-12-06 21:14:13 +00003416 Constructor += "(void *fp, "; // Invoke function pointer.
3417 Constructor += "struct " + Desc; // Descriptor pointer.
3418 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003419
Steve Naroff54055232008-10-27 17:20:55 +00003420 if (BlockDeclRefs.size()) {
3421 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003422 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003423 E = BlockByCopyDecls.end(); I != E; ++I) {
3424 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003425 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003426 std::string ArgName = "_" + FieldName;
3427 // Handle nested closure invocation. For example:
3428 //
3429 // void (^myImportedBlock)(void);
3430 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003431 //
Steve Naroff54055232008-10-27 17:20:55 +00003432 // void (^anotherBlock)(void);
3433 // anotherBlock = ^(void) {
3434 // myImportedBlock(); // import and invoke the closure
3435 // };
3436 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003437 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003438 S += "struct __block_impl *";
3439 Constructor += ", void *" + ArgName;
3440 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003441 QualType QT = (*I)->getType();
3442 if (HasLocalVariableExternalStorage(*I))
3443 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003444 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3445 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003446 Constructor += ", " + ArgName;
3447 }
3448 S += FieldName + ";\n";
3449 }
3450 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003451 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003452 E = BlockByRefDecls.end(); I != E; ++I) {
3453 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003454 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003455 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003456 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003457 std::string TypeString;
3458 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003459 TypeString += " *";
3460 FieldName = TypeString + FieldName;
3461 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003462 Constructor += ", " + ArgName;
3463 }
3464 S += FieldName + "; // by ref\n";
3465 }
3466 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003467 Constructor += ", int flags=0)";
3468 // Initialize all "by copy" arguments.
3469 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00003470 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003471 E = BlockByCopyDecls.end(); I != E; ++I) {
3472 std::string Name = (*I)->getNameAsString();
3473 if (firsTime) {
3474 Constructor += " : ";
3475 firsTime = false;
3476 }
3477 else
3478 Constructor += ", ";
3479 if (isTopLevelBlockPointerType((*I)->getType()))
3480 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3481 else
3482 Constructor += Name + "(_" + Name + ")";
3483 }
3484 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00003485 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003486 E = BlockByRefDecls.end(); I != E; ++I) {
3487 std::string Name = (*I)->getNameAsString();
3488 if (firsTime) {
3489 Constructor += " : ";
3490 firsTime = false;
3491 }
3492 else
3493 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003494 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003495 }
3496
3497 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003498 if (GlobalVarDecl)
3499 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3500 else
3501 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003502 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Steve Naroff01aec112009-12-06 21:14:13 +00003504 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003505 } else {
3506 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003507 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003508 if (GlobalVarDecl)
3509 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3510 else
3511 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003512 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3513 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003514 }
3515 Constructor += " ";
3516 Constructor += "}\n";
3517 S += Constructor;
3518 S += "};\n";
3519 return S;
3520}
3521
Steve Naroff01aec112009-12-06 21:14:13 +00003522std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3523 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003524 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003525 unsigned hasCopy) {
3526 std::string S = "\nstatic struct " + DescTag;
3527
3528 S += " {\n unsigned long reserved;\n";
3529 S += " unsigned long Block_size;\n";
3530 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003531 S += " void (*copy)(struct ";
3532 S += ImplTag; S += "*, struct ";
3533 S += ImplTag; S += "*);\n";
3534
3535 S += " void (*dispose)(struct ";
3536 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003537 }
3538 S += "} ";
3539
3540 S += DescTag + "_DATA = { 0, sizeof(struct ";
3541 S += ImplTag + ")";
3542 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003543 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3544 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003545 }
3546 S += "};\n";
3547 return S;
3548}
3549
Steve Naroff54055232008-10-27 17:20:55 +00003550void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003551 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003552 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003553 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003554 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003555 bool RewriteSC = (GlobalVarDecl &&
3556 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003557 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003558 GlobalVarDecl->getType().getCVRQualifiers());
3559 if (RewriteSC) {
3560 std::string SC(" void __");
3561 SC += GlobalVarDecl->getNameAsString();
3562 SC += "() {}";
3563 InsertText(FunLocStart, SC);
3564 }
3565
Steve Naroff54055232008-10-27 17:20:55 +00003566 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003567 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3568 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003569 // Need to copy-in the inner copied-in variables not actually used in this
3570 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003571 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003572 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003573 ValueDecl *VD = Exp->getDecl();
3574 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003575 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003576 BlockByCopyDeclsPtrSet.insert(VD);
3577 BlockByCopyDecls.push_back(VD);
3578 }
John McCallf4b88a42012-03-10 09:33:50 +00003579 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003580 BlockByRefDeclsPtrSet.insert(VD);
3581 BlockByRefDecls.push_back(VD);
3582 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003583 // imported objects in the inner blocks not used in the outer
3584 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003585 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003586 VD->getType()->isObjCObjectPointerType() ||
3587 VD->getType()->isBlockPointerType())
3588 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003589 }
Steve Naroff54055232008-10-27 17:20:55 +00003590
Daniel Dunbar4087f272010-08-17 22:39:59 +00003591 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3592 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Steve Naroff01aec112009-12-06 21:14:13 +00003594 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003595
Benjamin Kramerd999b372010-02-14 14:14:16 +00003596 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003597
Steve Naroff01aec112009-12-06 21:14:13 +00003598 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003599
Benjamin Kramerd999b372010-02-14 14:14:16 +00003600 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003601
3602 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003603 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003604 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003605 }
Steve Naroff01aec112009-12-06 21:14:13 +00003606 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3607 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003608 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003609
Steve Naroff54055232008-10-27 17:20:55 +00003610 BlockDeclRefs.clear();
3611 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003612 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003613 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003614 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003615 ImportedBlockDecls.clear();
3616 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003617 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003618 // Must insert any 'const/volatile/static here. Since it has been
3619 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003620 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003621 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003622 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003623 if (GlobalVarDecl->getType().isConstQualified())
3624 SC += "const ";
3625 if (GlobalVarDecl->getType().isVolatileQualified())
3626 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003627 if (GlobalVarDecl->getType().isRestrictQualified())
3628 SC += "restrict ";
3629 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003630 }
3631
Steve Naroff54055232008-10-27 17:20:55 +00003632 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003633 InnerDeclRefsCount.clear();
3634 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003635 RewrittenBlockExprs.clear();
3636}
3637
3638void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3639 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003640 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003641
Steve Naroff54055232008-10-27 17:20:55 +00003642 SynthesizeBlockLiterals(FunLocStart, FuncName);
3643}
3644
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003645static void BuildUniqueMethodName(std::string &Name,
3646 ObjCMethodDecl *MD) {
3647 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003648 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003649 Name += "__" + MD->getSelector().getAsString();
3650 // Convert colons to underscores.
3651 std::string::size_type loc = 0;
3652 while ((loc = Name.find(":", loc)) != std::string::npos)
3653 Name.replace(loc, 1, "_");
3654}
3655
Steve Naroff54055232008-10-27 17:20:55 +00003656void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003657 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3658 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003659 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003660 std::string FuncName;
3661 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003662 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003663}
3664
3665void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003666 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003667 if (*CI) {
3668 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3669 GetBlockDeclRefExprs(CBE->getBody());
3670 else
3671 GetBlockDeclRefExprs(*CI);
3672 }
3673 // Handle specific things.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003674 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3675 if (DRE->refersToEnclosingVariableOrCapture() ||
3676 HasLocalVariableExternalStorage(DRE->getDecl()))
John McCallf4b88a42012-03-10 09:33:50 +00003677 // FIXME: Handle enums.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003678 BlockDeclRefs.push_back(DRE);
3679
Steve Naroff54055232008-10-27 17:20:55 +00003680 return;
3681}
3682
Craig Topper6b9240e2013-07-05 19:34:19 +00003683void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3684 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Stephen Hines176edba2014-12-01 14:53:08 -08003685 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003686 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003687 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003688 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3689 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003690 GetInnerBlockDeclRefExprs(CBE->getBody(),
3691 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003692 InnerContexts);
3693 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003694 else
3695 GetInnerBlockDeclRefExprs(*CI,
3696 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003697 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003698
3699 }
3700 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003702 if (DRE->refersToEnclosingVariableOrCapture() ||
3703 HasLocalVariableExternalStorage(DRE->getDecl())) {
3704 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
John McCallf4b88a42012-03-10 09:33:50 +00003705 InnerBlockDeclRefs.push_back(DRE);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003706 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
John McCallf4b88a42012-03-10 09:33:50 +00003707 if (Var->isFunctionOrMethodVarDecl())
3708 ImportedLocalExternalDecls.insert(Var);
3709 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003710 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003711
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003712 return;
3713}
3714
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003715/// convertFunctionTypeOfBlocks - This routine converts a function type
3716/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003717/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003718/// all block pointers to function pointers.
3719QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3720 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3721 // FTP will be null for closures that don't take arguments.
3722 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003723 SmallVector<QualType, 8> ArgTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07003724 QualType Res = FT->getReturnType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003725 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003726
3727 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003728 for (auto &I : FTP->param_types()) {
3729 QualType t = I;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003730 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003731 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003732 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003733 ArgTypes.push_back(t);
3734 }
3735 }
3736 QualType FuncType;
3737 // FIXME. Does this work if block takes no argument but has a return type
3738 // which is of block type?
3739 if (HasBlockType)
Jordan Rosebea522f2013-03-08 21:51:21 +00003740 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003741 else FuncType = QualType(FT, 0);
3742 return FuncType;
3743}
3744
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003745Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003746 // Navigate to relevant type information.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003747 const BlockPointerType *CPT = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003749 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003750 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003751 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003752 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003753 }
3754 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3755 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3756 }
3757 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3758 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3759 else if (const ConditionalOperator *CEXPR =
3760 dyn_cast<ConditionalOperator>(BlockExp)) {
3761 Expr *LHSExp = CEXPR->getLHS();
3762 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3763 Expr *RHSExp = CEXPR->getRHS();
3764 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3765 Expr *CONDExp = CEXPR->getCond();
3766 ConditionalOperator *CondExpr =
3767 new (Context) ConditionalOperator(CONDExp,
3768 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003769 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003770 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003771 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003772 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3773 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003774 } else if (const PseudoObjectExpr *POE
3775 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3776 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003777 } else {
3778 assert(1 && "RewriteBlockClass: Bad type");
3779 }
3780 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003781 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003782 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003783 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003784 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003786 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003787 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003788 &Context->Idents.get("__block_impl"));
3789 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003790
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003791 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003792 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003794 // Push the block argument type.
3795 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003796 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003797 for (auto &I : FTP->param_types()) {
3798 QualType t = I;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003800 if (!convertBlockPointerToFunctionPointer(t))
3801 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003802 ArgTypes.push_back(t);
3803 }
Steve Naroff54055232008-10-27 17:20:55 +00003804 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003805 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003806 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003808 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003809
John McCall9d125032010-01-15 18:39:57 +00003810 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003811 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003812 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003813 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003814 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3815 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003816 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003818 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003819 SourceLocation(),
3820 &Context->Idents.get("FuncPtr"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003821 Context->VoidPtrTy, nullptr,
3822 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003823 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003824 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003825 FD->getType(), VK_LValue,
3826 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003827
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003828
John McCall9d125032010-01-15 18:39:57 +00003829 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003830 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003831 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Chris Lattner5f9e2722011-07-23 10:55:15 +00003833 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003834 // Add the implicit argument.
3835 BlkExprs.push_back(BlkCast);
3836 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003837 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003838 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003839 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003840 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003841 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003842 Exp->getType(), VK_RValue,
3843 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003844 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003845}
3846
Steve Naroff621edce2009-04-29 16:37:50 +00003847// We need to return the rewritten expression to handle cases where the
3848// BlockDeclRefExpr is embedded in another expression being rewritten.
3849// For example:
3850//
3851// int main() {
3852// __block Foo *f;
3853// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003854//
Steve Naroff621edce2009-04-29 16:37:50 +00003855// void (^myblock)() = ^() {
3856// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3857// i = 77;
3858// };
3859//}
John McCallf4b88a42012-03-10 09:33:50 +00003860Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003861 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003862 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003863 ValueDecl *VD = DeclRefExp->getDecl();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003864 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3865 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003866
3867 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003868 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003869 &Context->Idents.get("__forwarding"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003870 Context->VoidPtrTy, nullptr,
3871 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003872 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003873 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3874 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003875 FD->getType(), VK_LValue,
3876 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003877
Chris Lattner5f9e2722011-07-23 10:55:15 +00003878 StringRef Name = VD->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003879 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003880 &Context->Idents.get(Name),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003881 Context->VoidPtrTy, nullptr,
3882 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003883 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003884 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003885 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003886
3887
3888
Steve Naroffdf8570d2009-02-02 17:19:26 +00003889 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003890 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3891 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003892 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003893 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003894 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003895}
3896
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003897// Rewrites the imported local variable V with external storage
3898// (static, extern, etc.) as *V
3899//
3900Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3901 ValueDecl *VD = DRE->getDecl();
3902 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3903 if (!ImportedLocalExternalDecls.count(Var))
3904 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003905 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3906 VK_LValue, OK_Ordinary,
3907 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003908 // Need parens to enforce precedence.
3909 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3910 Exp);
3911 ReplaceStmt(DRE, PE);
3912 return PE;
3913}
3914
Steve Naroffb2f9e512008-11-03 23:29:32 +00003915void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3916 SourceLocation LocStart = CE->getLParenLoc();
3917 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003918
3919 // Need to avoid trying to rewrite synthesized casts.
3920 if (LocStart.isInvalid())
3921 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003922 // Need to avoid trying to rewrite casts contained in macros.
3923 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3924 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Steve Naroff54055232008-10-27 17:20:55 +00003926 const char *startBuf = SM->getCharacterData(LocStart);
3927 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003928 QualType QT = CE->getType();
3929 const Type* TypePtr = QT->getAs<Type>();
3930 if (isa<TypeOfExprType>(TypePtr)) {
3931 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3932 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3933 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003934 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003935 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003936 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003937 return;
3938 }
Steve Naroff54055232008-10-27 17:20:55 +00003939 // advance the location to startArgList.
3940 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Steve Naroff54055232008-10-27 17:20:55 +00003942 while (*argPtr++ && (argPtr < endBuf)) {
3943 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003944 case '^':
3945 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003946 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003947 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003948 break;
Steve Naroff54055232008-10-27 17:20:55 +00003949 }
3950 }
3951 return;
3952}
3953
3954void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3955 SourceLocation DeclLoc = FD->getLocation();
3956 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Steve Naroff54055232008-10-27 17:20:55 +00003958 // We have 1 or more arguments that have closure pointers.
3959 const char *startBuf = SM->getCharacterData(DeclLoc);
3960 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Steve Naroff54055232008-10-27 17:20:55 +00003962 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00003963
Steve Naroff54055232008-10-27 17:20:55 +00003964 parenCount++;
3965 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003966 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00003967 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00003968
Steve Naroff54055232008-10-27 17:20:55 +00003969 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00003970
Steve Naroff54055232008-10-27 17:20:55 +00003971 while (*argPtr++ && parenCount) {
3972 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003973 case '^':
3974 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003975 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003976 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003977 break;
3978 case '(':
3979 parenCount++;
3980 break;
3981 case ')':
3982 parenCount--;
3983 break;
Steve Naroff54055232008-10-27 17:20:55 +00003984 }
3985 }
3986 return;
3987}
3988
3989bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00003990 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00003991 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003992 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00003993 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00003994 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00003995 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003996 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00003997 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00003998 }
3999 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004000 for (const auto &I : FTP->param_types())
4001 if (isTopLevelBlockPointerType(I))
Steve Naroff54055232008-10-27 17:20:55 +00004002 return true;
4003 }
4004 return false;
4005}
4006
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004007bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4008 const FunctionProtoType *FTP;
4009 const PointerType *PT = QT->getAs<PointerType>();
4010 if (PT) {
4011 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4012 } else {
4013 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4014 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4015 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4016 }
4017 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004018 for (const auto &I : FTP->param_types()) {
4019 if (I->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004020 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004021 if (I->isObjCObjectPointerType() &&
4022 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004023 return true;
4024 }
4025
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004026 }
4027 return false;
4028}
4029
Ted Kremenek8189cde2009-02-07 01:47:29 +00004030void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4031 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004032 const char *argPtr = strchr(Name, '(');
4033 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Steve Naroff54055232008-10-27 17:20:55 +00004035 LParen = argPtr; // output the start.
4036 argPtr++; // skip past the left paren.
4037 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Steve Naroff54055232008-10-27 17:20:55 +00004039 while (*argPtr && parenCount) {
4040 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004041 case '(': parenCount++; break;
4042 case ')': parenCount--; break;
4043 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004044 }
4045 if (parenCount) argPtr++;
4046 }
4047 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4048 RParen = argPtr; // output the end
4049}
4050
4051void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4052 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4053 RewriteBlockPointerFunctionArgs(FD);
4054 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004055 }
Steve Naroff54055232008-10-27 17:20:55 +00004056 // Handle Variables and Typedefs.
4057 SourceLocation DeclLoc = ND->getLocation();
4058 QualType DeclT;
4059 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4060 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004061 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004062 DeclT = TDD->getUnderlyingType();
4063 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4064 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004065 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004066 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Steve Naroff54055232008-10-27 17:20:55 +00004068 const char *startBuf = SM->getCharacterData(DeclLoc);
4069 const char *endBuf = startBuf;
4070 // scan backward (from the decl location) for the end of the previous decl.
4071 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4072 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004073 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004074 std::string buf;
4075 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004076 // *startBuf != '^' if we are dealing with a pointer to function that
4077 // may take block argument types (which will be handled below).
4078 if (*startBuf == '^') {
4079 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004080 buf = '*';
4081 startBuf++;
4082 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004083 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004084 while (*startBuf != ')') {
4085 buf += *startBuf;
4086 startBuf++;
4087 OrigLength++;
4088 }
4089 buf += ')';
4090 OrigLength++;
4091
4092 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4093 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004094 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004095 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004096 DeclLoc = ND->getLocation();
4097 startBuf = SM->getCharacterData(DeclLoc);
4098 const char *argListBegin, *argListEnd;
4099 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4100 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004101 if (*argListBegin == '^')
4102 buf += '*';
4103 else if (*argListBegin == '<') {
4104 buf += "/*";
4105 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004106 OrigLength++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004107 while (*argListBegin != '>') {
4108 buf += *argListBegin++;
4109 OrigLength++;
4110 }
4111 buf += *argListBegin;
4112 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004113 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004114 else
4115 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004116 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004117 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004118 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004119 buf += ')';
4120 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004121 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004122 ReplaceText(Start, OrigLength, buf);
4123
Steve Naroff54055232008-10-27 17:20:55 +00004124 return;
4125}
4126
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004127
4128/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4129/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4130/// struct Block_byref_id_object *src) {
4131/// _Block_object_assign (&_dest->object, _src->object,
4132/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4133/// [|BLOCK_FIELD_IS_WEAK]) // object
4134/// _Block_object_assign(&_dest->object, _src->object,
4135/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4136/// [|BLOCK_FIELD_IS_WEAK]) // block
4137/// }
4138/// And:
4139/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4140/// _Block_object_dispose(_src->object,
4141/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4142/// [|BLOCK_FIELD_IS_WEAK]) // object
4143/// _Block_object_dispose(_src->object,
4144/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4145/// [|BLOCK_FIELD_IS_WEAK]) // block
4146/// }
4147
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004148std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4149 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004150 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004151 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004152 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004153 CopyDestroyCache.insert(flag);
4154 S = "static void __Block_byref_id_object_copy_";
4155 S += utostr(flag);
4156 S += "(void *dst, void *src) {\n";
4157
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004158 // offset into the object pointer is computed as:
4159 // void * + void* + int + int + void* + void *
4160 unsigned IntSize =
4161 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4162 unsigned VoidPtrSize =
4163 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4164
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004165 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004166 S += " _Block_object_assign((char*)dst + ";
4167 S += utostr(offset);
4168 S += ", *(void * *) ((char*)src + ";
4169 S += utostr(offset);
4170 S += "), ";
4171 S += utostr(flag);
4172 S += ");\n}\n";
4173
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004174 S += "static void __Block_byref_id_object_dispose_";
4175 S += utostr(flag);
4176 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004177 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4178 S += utostr(offset);
4179 S += "), ";
4180 S += utostr(flag);
4181 S += ");\n}\n";
4182 return S;
4183}
4184
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004185/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4186/// the declaration into:
4187/// struct __Block_byref_ND {
4188/// void *__isa; // NULL for everything except __weak pointers
4189/// struct __Block_byref_ND *__forwarding;
4190/// int32_t __flags;
4191/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004192/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4193/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004194/// typex ND;
4195/// };
4196///
4197/// It then replaces declaration of ND variable with:
4198/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4199/// __size=sizeof(struct __Block_byref_ND),
4200/// ND=initializer-if-any};
4201///
4202///
4203void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004204 // Insert declaration for the function in which block literal is
4205 // used.
4206 if (CurFunctionDeclToDeclareForBlock)
4207 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004208 int flag = 0;
4209 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004210 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004211 if (DeclLoc.isInvalid())
4212 // If type location is missing, it is because of missing type (a warning).
4213 // Use variable's location which is good for this case.
4214 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004215 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004216 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004217 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004218 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004219 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004220 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004221 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004222 ByrefType += " {\n";
4223 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004224 RewriteByRefString(ByrefType, Name, ND);
4225 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004226 ByrefType += " int __flags;\n";
4227 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004228 // Add void *__Block_byref_id_object_copy;
4229 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004230 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004231 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004232 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004233 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4234 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004235 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004236
4237 QualType T = Ty;
4238 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004239 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004240
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004241 ByrefType += " " + Name + ";\n";
4242 ByrefType += "};\n";
4243 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004244 SourceLocation FunLocStart;
4245 if (CurFunctionDef)
4246 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4247 else {
4248 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4249 FunLocStart = CurMethodDef->getLocStart();
4250 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004251 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004252 if (Ty.isObjCGCWeak()) {
4253 flag |= BLOCK_FIELD_IS_WEAK;
4254 isa = 1;
4255 }
4256
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004257 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004258 flag = BLOCK_BYREF_CALLER;
4259 QualType Ty = ND->getType();
4260 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4261 if (Ty->isBlockPointerType())
4262 flag |= BLOCK_FIELD_IS_BLOCK;
4263 else
4264 flag |= BLOCK_FIELD_IS_OBJECT;
4265 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004266 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004267 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004268 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004269
4270 // struct __Block_byref_ND ND =
4271 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4272 // initializer-if-any};
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004273 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004274 unsigned flags = 0;
4275 if (HasCopyAndDispose)
4276 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004277 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004278 ByrefType.clear();
4279 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004280 std::string ForwardingCastType("(");
4281 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004282 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004283 ByrefType += " " + Name + " = {(void*)";
4284 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004285 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004286 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004287 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004288 ByrefType += "sizeof(";
4289 RewriteByRefString(ByrefType, Name, ND);
4290 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004291 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004292 ByrefType += ", __Block_byref_id_object_copy_";
4293 ByrefType += utostr(flag);
4294 ByrefType += ", __Block_byref_id_object_dispose_";
4295 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004296 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004297 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004298 unsigned nameSize = Name.size();
4299 // for block or function pointer declaration. Name is aleady
4300 // part of the declaration.
4301 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4302 nameSize = 1;
4303 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004304 }
4305 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004306 SourceLocation startLoc;
4307 Expr *E = ND->getInit();
4308 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4309 startLoc = ECE->getLParenLoc();
4310 else
4311 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004312 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004313 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004314 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004315 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004316 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004317 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004318 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004319 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004320 ByrefType += "sizeof(";
4321 RewriteByRefString(ByrefType, Name, ND);
4322 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004323 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004324 ByrefType += "__Block_byref_id_object_copy_";
4325 ByrefType += utostr(flag);
4326 ByrefType += ", __Block_byref_id_object_dispose_";
4327 ByrefType += utostr(flag);
4328 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004329 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004330 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004331
4332 // Complete the newly synthesized compound expression by inserting a right
4333 // curly brace before the end of the declaration.
4334 // FIXME: This approach avoids rewriting the initializer expression. It
4335 // also assumes there is only one declarator. For example, the following
4336 // isn't currently supported by this routine (in general):
4337 //
4338 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4339 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004340 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4341 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004342 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4343 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004344 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004345
Benjamin Kramerd999b372010-02-14 14:14:16 +00004346 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004347 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004348 return;
4349}
4350
Mike Stump1eb44332009-09-09 15:08:12 +00004351void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004352 // Add initializers for any closure decl refs.
4353 GetBlockDeclRefExprs(Exp->getBody());
4354 if (BlockDeclRefs.size()) {
4355 // Unique all "by copy" declarations.
4356 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004357 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004358 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4359 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4360 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4361 }
4362 }
Steve Naroff54055232008-10-27 17:20:55 +00004363 // Unique all "by ref" declarations.
4364 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004365 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004366 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4367 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4368 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4369 }
Steve Naroff54055232008-10-27 17:20:55 +00004370 }
4371 // Find any imported blocks...they will need special attention.
4372 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004373 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004374 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004375 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004376 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004377 }
4378}
4379
Chris Lattner5f9e2722011-07-23 10:55:15 +00004380FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004381 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004382 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004383 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004384 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004385 false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004386}
4387
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004388Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00004389 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004390 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004391 Blocks.push_back(Exp);
4392
4393 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004394
4395 // Add inner imported variables now used in current block.
4396 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004397 if (!InnerBlockDeclRefs.empty()) {
4398 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004399 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004400 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004401 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004402 // We need to save the copied-in variables in nested
4403 // blocks because it is needed at the end for some of the API generations.
4404 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004405 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4406 BlockDeclRefs.push_back(Exp);
4407 BlockByCopyDeclsPtrSet.insert(VD);
4408 BlockByCopyDecls.push_back(VD);
4409 }
John McCallf4b88a42012-03-10 09:33:50 +00004410 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004411 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4412 BlockDeclRefs.push_back(Exp);
4413 BlockByRefDeclsPtrSet.insert(VD);
4414 BlockByRefDecls.push_back(VD);
4415 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004416 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004417 // Find any imported blocks...they will need special attention.
4418 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004419 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004420 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4421 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4422 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004423 }
4424 InnerDeclRefsCount.push_back(countOfInnerDecls);
4425
Steve Narofffa15fd92008-10-28 20:29:00 +00004426 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Steve Narofffa15fd92008-10-28 20:29:00 +00004428 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004429 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004430 else if (CurMethodDef)
4431 BuildUniqueMethodName(FuncName, CurMethodDef);
4432 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004433 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004434
Steve Narofffa15fd92008-10-28 20:29:00 +00004435 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004436
Steve Narofffa15fd92008-10-28 20:29:00 +00004437 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4438 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004439
Steve Narofffa15fd92008-10-28 20:29:00 +00004440 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004441 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4442 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004443
4444 FunctionDecl *FD;
4445 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004446
Benjamin Kramere5753592013-09-09 14:48:42 +00004447 // Simulate a constructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004448 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004449 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004450 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004451
Chris Lattner5f9e2722011-07-23 10:55:15 +00004452 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004453
Steve Narofffdc03722008-10-29 21:23:59 +00004454 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004455 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004456 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4457 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004458 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004459 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004460 InitExprs.push_back(castExpr);
4461
Steve Naroff01aec112009-12-06 21:14:13 +00004462 // Initialize the block descriptor.
4463 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004464
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004465 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4466 SourceLocation(), SourceLocation(),
4467 &Context->Idents.get(DescData.c_str()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004468 Context->VoidPtrTy, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004469 SC_Static);
John McCallf89e55a2010-11-18 06:31:45 +00004470 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004471 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004472 Context->VoidPtrTy,
4473 VK_LValue,
4474 SourceLocation()),
4475 UO_AddrOf,
4476 Context->getPointerType(Context->VoidPtrTy),
4477 VK_RValue, OK_Ordinary,
4478 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004479 InitExprs.push_back(DescRefExpr);
4480
Steve Narofffa15fd92008-10-28 20:29:00 +00004481 // Add initializers for any closure decl refs.
4482 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004483 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004484 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004485 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004486 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004487 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004488 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004489 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004490 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004491 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004492 if (HasLocalVariableExternalStorage(*I)) {
4493 QualType QT = (*I)->getType();
4494 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004495 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4496 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004497 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004498 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004499 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004500 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004501 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004502 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004503 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004504 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004505 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004506 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004507 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004508 if (HasLocalVariableExternalStorage(*I)) {
4509 QualType QT = (*I)->getType();
4510 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004511 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4512 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004513 }
4514
Steve Narofffa15fd92008-10-28 20:29:00 +00004515 }
Mike Stump1eb44332009-09-09 15:08:12 +00004516 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004517 }
4518 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004519 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004521 ValueDecl *ND = (*I);
4522 std::string Name(ND->getNameAsString());
4523 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004524 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004525 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4526 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004527 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004528 SourceLocation(), SourceLocation(),
4529 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004530 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4531 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4532
Daniel Dunbar4087f272010-08-17 22:39:59 +00004533 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004534 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004535 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004536 bool isNestedCapturedVar = false;
4537 if (block)
Stephen Hines651f13c2014-04-23 16:59:28 -07004538 for (const auto &CI : block->captures()) {
4539 const VarDecl *variable = CI.getVariable();
4540 if (variable == ND && CI.isNested()) {
4541 assert (CI.isByRef() &&
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004542 "SynthBlockInitExpr - captured block variable is not byref");
4543 isNestedCapturedVar = true;
4544 break;
4545 }
4546 }
4547 // captured nested byref variable has its address passed. Do not take
4548 // its address again.
4549 if (!isNestedCapturedVar)
4550 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004551 Context->getPointerType(Exp->getType()),
4552 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004553 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004554 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004555 }
4556 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004557 if (ImportedBlockDecls.size()) {
4558 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4559 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004560 unsigned IntSize =
4561 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004562 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4563 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004564 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004565 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004566 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00004567 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004568 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004569 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004570 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004571 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004572 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004573 BlockDeclRefs.clear();
4574 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004575 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004576 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004577 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004578 ImportedBlockDecls.clear();
4579 return NewRep;
4580}
4581
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004582bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4583 if (const ObjCForCollectionStmt * CS =
4584 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4585 return CS->getElement() == DS;
4586 return false;
4587}
4588
Steve Narofffa15fd92008-10-28 20:29:00 +00004589//===----------------------------------------------------------------------===//
4590// Function Body / Expression rewriting
4591//===----------------------------------------------------------------------===//
4592
4593Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004594 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004595 isa<DoStmt>(S) || isa<ForStmt>(S))
4596 Stmts.push_back(S);
4597 else if (isa<ObjCForCollectionStmt>(S)) {
4598 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004599 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004600 }
Mike Stump1eb44332009-09-09 15:08:12 +00004601
John McCall4b9c2d22011-11-06 09:01:30 +00004602 // Pseudo-object operations and ivar references need special
4603 // treatment because we're going to recursively rewrite them.
4604 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4605 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4606 return RewritePropertyOrImplicitSetter(PseudoOp);
4607 } else {
4608 return RewritePropertyOrImplicitGetter(PseudoOp);
4609 }
4610 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4611 return RewriteObjCIvarRefExpr(IvarRefExpr);
4612 }
4613
Steve Narofffa15fd92008-10-28 20:29:00 +00004614 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Steve Narofffa15fd92008-10-28 20:29:00 +00004616 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004617 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004618 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004619 Stmt *childStmt = (*CI);
4620 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004621 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004622 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004623 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004624 }
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Steve Narofffa15fd92008-10-28 20:29:00 +00004626 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004627 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004628 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4629 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004630 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004631 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004632 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004633 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004634 Stmt *SaveCurrentBody = CurrentBody;
4635 CurrentBody = BE->getBody();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004636 PropParentMap = nullptr;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004637 // block literal on rhs of a property-dot-sytax assignment
4638 // must be replaced by its synthesize ast so getRewrittenText
4639 // works as expected. In this case, what actually ends up on RHS
4640 // is the blockTranscribed which is the helper function for the
4641 // block literal; as in: self.c = ^() {[ace ARR];};
4642 bool saveDisableReplaceStmt = DisableReplaceStmt;
4643 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004644 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004645 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004646 CurrentBody = SaveCurrentBody;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004647 PropParentMap = nullptr;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004648 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004649 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004650 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004651 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004652
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004653 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4654
Steve Narofffa15fd92008-10-28 20:29:00 +00004655 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004656 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004657 return blockTranscribed;
4658 }
4659 // Handle specific things.
4660 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4661 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Steve Narofffa15fd92008-10-28 20:29:00 +00004663 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4664 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Steve Narofffa15fd92008-10-28 20:29:00 +00004666 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4667 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Steve Narofffa15fd92008-10-28 20:29:00 +00004669 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004670#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004671 // Before we rewrite it, put the original message expression in a comment.
4672 SourceLocation startLoc = MessExpr->getLocStart();
4673 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004674
Steve Narofffa15fd92008-10-28 20:29:00 +00004675 const char *startBuf = SM->getCharacterData(startLoc);
4676 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004677
Steve Narofffa15fd92008-10-28 20:29:00 +00004678 std::string messString;
4679 messString += "// ";
4680 messString.append(startBuf, endBuf-startBuf+1);
4681 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004682
4683 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 // InsertText(clang::SourceLocation, char const*, unsigned int).
4685 // InsertText(startLoc, messString.c_str(), messString.size());
4686 // Tried this, but it didn't work either...
4687 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004688#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 return RewriteMessageExpr(MessExpr);
4690 }
Mike Stump1eb44332009-09-09 15:08:12 +00004691
Steve Narofffa15fd92008-10-28 20:29:00 +00004692 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4693 return RewriteObjCTryStmt(StmtTry);
4694
4695 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4696 return RewriteObjCSynchronizedStmt(StmtTry);
4697
4698 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4699 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004700
Steve Narofffa15fd92008-10-28 20:29:00 +00004701 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4702 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004703
4704 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004705 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004706 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004707 OrigStmtRange.getEnd());
4708 if (BreakStmt *StmtBreakStmt =
4709 dyn_cast<BreakStmt>(S))
4710 return RewriteBreakStmt(StmtBreakStmt);
4711 if (ContinueStmt *StmtContinueStmt =
4712 dyn_cast<ContinueStmt>(S))
4713 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004714
4715 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 // and cast exprs.
4717 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4718 // FIXME: What we're doing here is modifying the type-specifier that
4719 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004720 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004721 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4722 // the context of an ObjCForCollectionStmt. For example:
4723 // NSArray *someArray;
4724 // for (id <FooProtocol> index in someArray) ;
4725 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4726 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004727 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004728 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004729
Steve Narofffa15fd92008-10-28 20:29:00 +00004730 // Blocks rewrite rules.
Stephen Hines651f13c2014-04-23 16:59:28 -07004731 for (auto *SD : DS->decls()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004732 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004733 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004734 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004735 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004736 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004737 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004738 if (VD->hasAttr<BlocksAttr>()) {
4739 static unsigned uniqueByrefDeclCount = 0;
4740 assert(!BlockByRefDeclNo.count(ND) &&
4741 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4742 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004743 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004744 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004745 else
4746 RewriteTypeOfDecl(VD);
4747 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 }
Richard Smith162e1c12011-04-15 14:24:37 +00004749 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004750 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004752 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004753 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4754 }
4755 }
4756 }
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Steve Narofffa15fd92008-10-28 20:29:00 +00004758 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4759 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004760
4761 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004762 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4763 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004764 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4765 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 && "Statement stack mismatch");
4767 Stmts.pop_back();
4768 }
4769 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004770 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4771 ValueDecl *VD = DRE->getDecl();
4772 if (VD->hasAttr<BlocksAttr>())
4773 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004774 if (HasLocalVariableExternalStorage(VD))
4775 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004776 }
4777
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004779 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004780 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004781 ReplaceStmt(S, BlockCall);
4782 return BlockCall;
4783 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004784 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004785 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 RewriteCastExpr(CE);
4787 }
4788#if 0
4789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004790 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4791 ICE->getSubExpr(),
4792 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004793 // Get the new text.
4794 std::string SStr;
4795 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004796 Replacement->printPretty(Buf);
Steve Narofffa15fd92008-10-28 20:29:00 +00004797 const std::string &Str = Buf.str();
4798
4799 printf("CAST = %s\n", &Str[0]);
4800 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4801 delete S;
4802 return Replacement;
4803 }
4804#endif
4805 // Return this stmt unmodified.
4806 return S;
4807}
4808
Steve Naroff3d7e7862009-12-05 15:55:59 +00004809void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004810 for (auto *FD : RD->fields()) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00004811 if (isTopLevelBlockPointerType(FD->getType()))
4812 RewriteBlockPointerDecl(FD);
4813 if (FD->getType()->isObjCQualifiedIdType() ||
4814 FD->getType()->isObjCQualifiedInterfaceType())
4815 RewriteObjCQualifiedInterfaceTypes(FD);
4816 }
4817}
4818
Steve Narofffa15fd92008-10-28 20:29:00 +00004819/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4820/// main file of the input.
4821void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004822 switch (D->getKind()) {
4823 case Decl::Function: {
4824 FunctionDecl *FD = cast<FunctionDecl>(D);
4825 if (FD->isOverloadedOperator())
4826 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004827
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004828 // Since function prototypes don't have ParmDecl's, we check the function
4829 // prototype. This enables us to rewrite function declarations and
4830 // definitions using the same code.
4831 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004832
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004833 if (!FD->isThisDeclarationADefinition())
4834 break;
4835
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004836 // FIXME: If this should support Obj-C++, support CXXTryStmt
4837 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4838 CurFunctionDef = FD;
4839 CurFunctionDeclToDeclareForBlock = FD;
4840 CurrentBody = Body;
4841 Body =
4842 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4843 FD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004844 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004845 if (PropParentMap) {
4846 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004847 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004848 }
4849 // This synthesizes and inserts the block "impl" struct, invoke function,
4850 // and any copy/dispose helper functions.
4851 InsertBlockLiteralsWithinFunction(FD);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004852 CurFunctionDef = nullptr;
4853 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004854 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004855 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004856 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004857 case Decl::ObjCMethod: {
4858 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4859 if (CompoundStmt *Body = MD->getCompoundBody()) {
4860 CurMethodDef = MD;
4861 CurrentBody = Body;
4862 Body =
4863 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4864 MD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004865 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004866 if (PropParentMap) {
4867 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004868 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004869 }
4870 InsertBlockLiteralsWithinMethod(MD);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004871 CurMethodDef = nullptr;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004872 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004873 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004874 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004875 case Decl::ObjCImplementation: {
4876 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4877 ClassImplementation.push_back(CI);
4878 break;
4879 }
4880 case Decl::ObjCCategoryImpl: {
4881 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4882 CategoryImplementation.push_back(CI);
4883 break;
4884 }
4885 case Decl::Var: {
4886 VarDecl *VD = cast<VarDecl>(D);
4887 RewriteObjCQualifiedInterfaceTypes(VD);
4888 if (isTopLevelBlockPointerType(VD->getType()))
4889 RewriteBlockPointerDecl(VD);
4890 else if (VD->getType()->isFunctionPointerType()) {
4891 CheckFunctionPointerDecl(VD->getType(), VD);
4892 if (VD->getInit()) {
4893 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4894 RewriteCastExpr(CE);
4895 }
4896 }
4897 } else if (VD->getType()->isRecordType()) {
4898 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4899 if (RD->isCompleteDefinition())
4900 RewriteRecordBody(RD);
4901 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004902 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004903 GlobalVarDecl = VD;
4904 CurrentBody = VD->getInit();
4905 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004906 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004907 if (PropParentMap) {
4908 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004909 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004910 }
4911 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004912 GlobalVarDecl = nullptr;
4913
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004914 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004915 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004916 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004917 }
4918 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004919 break;
4920 }
4921 case Decl::TypeAlias:
4922 case Decl::Typedef: {
4923 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4924 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4925 RewriteBlockPointerDecl(TD);
4926 else if (TD->getUnderlyingType()->isFunctionPointerType())
4927 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4928 }
4929 break;
4930 }
4931 case Decl::CXXRecord:
4932 case Decl::Record: {
4933 RecordDecl *RD = cast<RecordDecl>(D);
4934 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004935 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004936 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004937 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004938 default:
4939 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004940 }
4941 // Nothing yet.
4942}
4943
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004944void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004945 if (Diags.hasErrorOccurred())
4946 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004949
Steve Naroff621edce2009-04-29 16:37:50 +00004950 // Here's a great place to add any extra declarations that may be needed.
4951 // Write out meta data for each @protocol(<expr>).
Stephen Hines176edba2014-12-01 14:53:08 -08004952 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4953 RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
Steve Naroff621edce2009-04-29 16:37:50 +00004954
Benjamin Kramerd999b372010-02-14 14:14:16 +00004955 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004956 if (ClassImplementation.size() || CategoryImplementation.size())
4957 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004958
Steve Narofffa15fd92008-10-28 20:29:00 +00004959 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4960 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00004961 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00004962 Rewrite.getRewriteBufferFor(MainFileID)) {
4963 //printf("Changed:\n");
4964 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4965 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00004966 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00004967 }
Steve Narofface66252008-11-13 20:07:04 +00004968
Steve Naroff621edce2009-04-29 16:37:50 +00004969 if (ClassImplementation.size() || CategoryImplementation.size() ||
4970 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004971 // Rewrite Objective-c meta data*
4972 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00004973 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00004974 // Emit metadata.
4975 *OutFile << ResultStr;
4976 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004977 OutFile->flush();
4978}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00004979
4980void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4981 InitializeCommon(context);
4982
4983 // declaring objc_selector outside the parameter list removes a silly
4984 // scope related warning...
4985 if (IsHeader)
4986 Preamble = "#pragma once\n";
4987 Preamble += "struct objc_selector; struct objc_class;\n";
4988 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4989 Preamble += "struct objc_object *superClass; ";
4990 if (LangOpts.MicrosoftExt) {
4991 // Add a constructor for creating temporary objects.
4992 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4993 ": ";
4994 Preamble += "object(o), superClass(s) {} ";
4995 }
4996 Preamble += "};\n";
4997 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4998 Preamble += "typedef struct objc_object Protocol;\n";
4999 Preamble += "#define _REWRITER_typedef_Protocol\n";
5000 Preamble += "#endif\n";
5001 if (LangOpts.MicrosoftExt) {
5002 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5003 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5004 } else
5005 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5006 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5007 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5008 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5009 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5010 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5011 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5012 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5013 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5014 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5015 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5016 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5017 Preamble += "(const char *);\n";
5018 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5019 Preamble += "(struct objc_class *);\n";
5020 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5021 Preamble += "(const char *);\n";
5022 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5023 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5024 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5025 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5026 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5027 Preamble += "(struct objc_class *, struct objc_object *);\n";
5028 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005029 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5030 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005031 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5032 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5033 Preamble += "struct __objcFastEnumerationState {\n\t";
5034 Preamble += "unsigned long state;\n\t";
5035 Preamble += "void **itemsPtr;\n\t";
5036 Preamble += "unsigned long *mutationsPtr;\n\t";
5037 Preamble += "unsigned long extra[5];\n};\n";
5038 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5039 Preamble += "#define __FASTENUMERATIONSTATE\n";
5040 Preamble += "#endif\n";
5041 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5042 Preamble += "struct __NSConstantStringImpl {\n";
5043 Preamble += " int *isa;\n";
5044 Preamble += " int flags;\n";
5045 Preamble += " char *str;\n";
5046 Preamble += " long length;\n";
5047 Preamble += "};\n";
5048 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5049 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5050 Preamble += "#else\n";
5051 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5052 Preamble += "#endif\n";
5053 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5054 Preamble += "#endif\n";
5055 // Blocks preamble.
5056 Preamble += "#ifndef BLOCK_IMPL\n";
5057 Preamble += "#define BLOCK_IMPL\n";
5058 Preamble += "struct __block_impl {\n";
5059 Preamble += " void *isa;\n";
5060 Preamble += " int Flags;\n";
5061 Preamble += " int Reserved;\n";
5062 Preamble += " void *FuncPtr;\n";
5063 Preamble += "};\n";
5064 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5065 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5066 Preamble += "extern \"C\" __declspec(dllexport) "
5067 "void _Block_object_assign(void *, const void *, const int);\n";
5068 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5069 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5070 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5071 Preamble += "#else\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5076 Preamble += "#endif\n";
5077 Preamble += "#endif\n";
5078 if (LangOpts.MicrosoftExt) {
5079 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5080 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5081 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5082 Preamble += "#define __attribute__(X)\n";
5083 Preamble += "#endif\n";
5084 Preamble += "#define __weak\n";
5085 }
5086 else {
5087 Preamble += "#define __block\n";
5088 Preamble += "#define __weak\n";
5089 }
5090 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5091 // as this avoids warning in any 64bit/32bit compilation model.
5092 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5093}
5094
5095/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5096/// ivar offset.
5097void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5098 std::string &Result) {
5099 if (ivar->isBitField()) {
5100 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5101 // place all bitfields at offset 0.
5102 Result += "0";
5103 } else {
5104 Result += "__OFFSETOFIVAR__(struct ";
5105 Result += ivar->getContainingInterface()->getNameAsString();
5106 if (LangOpts.MicrosoftExt)
5107 Result += "_IMPL";
5108 Result += ", ";
5109 Result += ivar->getNameAsString();
5110 Result += ")";
5111 }
5112}
5113
5114/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5115void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5116 ObjCProtocolDecl *PDecl, StringRef prefix,
5117 StringRef ClassName, std::string &Result) {
5118 static bool objc_protocol_methods = false;
5119
5120 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005121 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005122 /* struct protocol_methods {
5123 SEL _cmd;
5124 char *method_types;
5125 }
5126 */
5127 Result += "\nstruct _protocol_methods {\n";
5128 Result += "\tstruct objc_selector *_cmd;\n";
5129 Result += "\tchar *method_types;\n";
5130 Result += "};\n";
5131
5132 objc_protocol_methods = true;
5133 }
5134 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005135 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005136 return;
5137
Douglas Gregor61cc2962012-01-02 02:00:30 +00005138 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5139 PDecl = Def;
5140
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005141 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5142 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5143 PDecl->instmeth_end());
5144 /* struct _objc_protocol_method_list {
5145 int protocol_method_count;
5146 struct protocol_methods protocols[];
5147 }
5148 */
5149 Result += "\nstatic struct {\n";
5150 Result += "\tint protocol_method_count;\n";
5151 Result += "\tstruct _protocol_methods protocol_methods[";
5152 Result += utostr(NumMethods);
5153 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5154 Result += PDecl->getNameAsString();
5155 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5156 "{\n\t" + utostr(NumMethods) + "\n";
5157
5158 // Output instance methods declared in this protocol.
5159 for (ObjCProtocolDecl::instmeth_iterator
5160 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5161 I != E; ++I) {
5162 if (I == PDecl->instmeth_begin())
5163 Result += "\t ,{{(struct objc_selector *)\"";
5164 else
5165 Result += "\t ,{(struct objc_selector *)\"";
5166 Result += (*I)->getSelector().getAsString();
5167 std::string MethodTypeString;
5168 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5169 Result += "\", \"";
5170 Result += MethodTypeString;
5171 Result += "\"}\n";
5172 }
5173 Result += "\t }\n};\n";
5174 }
5175
5176 // Output class methods declared in this protocol.
5177 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5178 PDecl->classmeth_end());
5179 if (NumMethods > 0) {
5180 /* struct _objc_protocol_method_list {
5181 int protocol_method_count;
5182 struct protocol_methods protocols[];
5183 }
5184 */
5185 Result += "\nstatic struct {\n";
5186 Result += "\tint protocol_method_count;\n";
5187 Result += "\tstruct _protocol_methods protocol_methods[";
5188 Result += utostr(NumMethods);
5189 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5190 Result += PDecl->getNameAsString();
5191 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5192 "{\n\t";
5193 Result += utostr(NumMethods);
5194 Result += "\n";
5195
5196 // Output instance methods declared in this protocol.
5197 for (ObjCProtocolDecl::classmeth_iterator
5198 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5199 I != E; ++I) {
5200 if (I == PDecl->classmeth_begin())
5201 Result += "\t ,{{(struct objc_selector *)\"";
5202 else
5203 Result += "\t ,{(struct objc_selector *)\"";
5204 Result += (*I)->getSelector().getAsString();
5205 std::string MethodTypeString;
5206 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5207 Result += "\", \"";
5208 Result += MethodTypeString;
5209 Result += "\"}\n";
5210 }
5211 Result += "\t }\n};\n";
5212 }
5213
5214 // Output:
5215 /* struct _objc_protocol {
5216 // Objective-C 1.0 extensions
5217 struct _objc_protocol_extension *isa;
5218 char *protocol_name;
5219 struct _objc_protocol **protocol_list;
5220 struct _objc_protocol_method_list *instance_methods;
5221 struct _objc_protocol_method_list *class_methods;
5222 };
5223 */
5224 static bool objc_protocol = false;
5225 if (!objc_protocol) {
5226 Result += "\nstruct _objc_protocol {\n";
5227 Result += "\tstruct _objc_protocol_extension *isa;\n";
5228 Result += "\tchar *protocol_name;\n";
5229 Result += "\tstruct _objc_protocol **protocol_list;\n";
5230 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5231 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5232 Result += "};\n";
5233
5234 objc_protocol = true;
5235 }
5236
5237 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5238 Result += PDecl->getNameAsString();
5239 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5240 "{\n\t0, \"";
5241 Result += PDecl->getNameAsString();
5242 Result += "\", 0, ";
5243 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5244 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5245 Result += PDecl->getNameAsString();
5246 Result += ", ";
5247 }
5248 else
5249 Result += "0, ";
5250 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5251 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5252 Result += PDecl->getNameAsString();
5253 Result += "\n";
5254 }
5255 else
5256 Result += "0\n";
5257 Result += "};\n";
5258
5259 // Mark this protocol as having been generated.
Stephen Hines176edba2014-12-01 14:53:08 -08005260 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005261 llvm_unreachable("protocol already synthesized");
5262
5263}
5264
5265void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5266 const ObjCList<ObjCProtocolDecl> &Protocols,
5267 StringRef prefix, StringRef ClassName,
5268 std::string &Result) {
5269 if (Protocols.empty()) return;
5270
5271 for (unsigned i = 0; i != Protocols.size(); i++)
5272 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5273
5274 // Output the top lovel protocol meta-data for the class.
5275 /* struct _objc_protocol_list {
5276 struct _objc_protocol_list *next;
5277 int protocol_count;
5278 struct _objc_protocol *class_protocols[];
5279 }
5280 */
5281 Result += "\nstatic struct {\n";
5282 Result += "\tstruct _objc_protocol_list *next;\n";
5283 Result += "\tint protocol_count;\n";
5284 Result += "\tstruct _objc_protocol *class_protocols[";
5285 Result += utostr(Protocols.size());
5286 Result += "];\n} _OBJC_";
5287 Result += prefix;
5288 Result += "_PROTOCOLS_";
5289 Result += ClassName;
5290 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5291 "{\n\t0, ";
5292 Result += utostr(Protocols.size());
5293 Result += "\n";
5294
5295 Result += "\t,{&_OBJC_PROTOCOL_";
5296 Result += Protocols[0]->getNameAsString();
5297 Result += " \n";
5298
5299 for (unsigned i = 1; i != Protocols.size(); i++) {
5300 Result += "\t ,&_OBJC_PROTOCOL_";
5301 Result += Protocols[i]->getNameAsString();
5302 Result += "\n";
5303 }
5304 Result += "\t }\n};\n";
5305}
5306
5307void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5308 std::string &Result) {
5309 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5310
5311 // Explicitly declared @interface's are already synthesized.
5312 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005313 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005314 // produce correct synthesis as yet.
5315 RewriteObjCInternalStruct(CDecl, Result);
5316 }
5317
5318 // Build _objc_ivar_list metadata for classes ivars if needed
5319 unsigned NumIvars = !IDecl->ivar_empty()
5320 ? IDecl->ivar_size()
5321 : (CDecl ? CDecl->ivar_size() : 0);
5322 if (NumIvars > 0) {
5323 static bool objc_ivar = false;
5324 if (!objc_ivar) {
5325 /* struct _objc_ivar {
5326 char *ivar_name;
5327 char *ivar_type;
5328 int ivar_offset;
5329 };
5330 */
5331 Result += "\nstruct _objc_ivar {\n";
5332 Result += "\tchar *ivar_name;\n";
5333 Result += "\tchar *ivar_type;\n";
5334 Result += "\tint ivar_offset;\n";
5335 Result += "};\n";
5336
5337 objc_ivar = true;
5338 }
5339
5340 /* struct {
5341 int ivar_count;
5342 struct _objc_ivar ivar_list[nIvars];
5343 };
5344 */
5345 Result += "\nstatic struct {\n";
5346 Result += "\tint ivar_count;\n";
5347 Result += "\tstruct _objc_ivar ivar_list[";
5348 Result += utostr(NumIvars);
5349 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5350 Result += IDecl->getNameAsString();
5351 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5352 "{\n\t";
5353 Result += utostr(NumIvars);
5354 Result += "\n";
5355
5356 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5357 SmallVector<ObjCIvarDecl *, 8> IVars;
5358 if (!IDecl->ivar_empty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005359 for (auto *IV : IDecl->ivars())
5360 IVars.push_back(IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005361 IVI = IDecl->ivar_begin();
5362 IVE = IDecl->ivar_end();
5363 } else {
5364 IVI = CDecl->ivar_begin();
5365 IVE = CDecl->ivar_end();
5366 }
5367 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005368 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005369 Result += "\", \"";
5370 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005371 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005372 QuoteDoublequotes(TmpString, StrEncoding);
5373 Result += StrEncoding;
5374 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005375 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005376 Result += "}\n";
5377 for (++IVI; IVI != IVE; ++IVI) {
5378 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005379 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005380 Result += "\", \"";
5381 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005382 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005383 QuoteDoublequotes(TmpString, StrEncoding);
5384 Result += StrEncoding;
5385 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005386 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005387 Result += "}\n";
5388 }
5389
5390 Result += "\t }\n};\n";
5391 }
5392
5393 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005394 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005395
5396 // If any of our property implementations have associated getters or
5397 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005398 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005399 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005400 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005401 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005402 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005403 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005404 if (!PD)
5405 continue;
5406 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5407 if (!Getter->isDefined())
5408 InstanceMethods.push_back(Getter);
5409 if (PD->isReadOnly())
5410 continue;
5411 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5412 if (!Setter->isDefined())
5413 InstanceMethods.push_back(Setter);
5414 }
5415 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5416 true, "", IDecl->getName(), Result);
5417
5418 // Build _objc_method_list for class's class methods if needed
5419 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5420 false, "", IDecl->getName(), Result);
5421
5422 // Protocols referenced in class declaration?
5423 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5424 "CLASS", CDecl->getName(), Result);
5425
5426 // Declaration of class/meta-class metadata
5427 /* struct _objc_class {
5428 struct _objc_class *isa; // or const char *root_class_name when metadata
5429 const char *super_class_name;
5430 char *name;
5431 long version;
5432 long info;
5433 long instance_size;
5434 struct _objc_ivar_list *ivars;
5435 struct _objc_method_list *methods;
5436 struct objc_cache *cache;
5437 struct objc_protocol_list *protocols;
5438 const char *ivar_layout;
5439 struct _objc_class_ext *ext;
5440 };
5441 */
5442 static bool objc_class = false;
5443 if (!objc_class) {
5444 Result += "\nstruct _objc_class {\n";
5445 Result += "\tstruct _objc_class *isa;\n";
5446 Result += "\tconst char *super_class_name;\n";
5447 Result += "\tchar *name;\n";
5448 Result += "\tlong version;\n";
5449 Result += "\tlong info;\n";
5450 Result += "\tlong instance_size;\n";
5451 Result += "\tstruct _objc_ivar_list *ivars;\n";
5452 Result += "\tstruct _objc_method_list *methods;\n";
5453 Result += "\tstruct objc_cache *cache;\n";
5454 Result += "\tstruct _objc_protocol_list *protocols;\n";
5455 Result += "\tconst char *ivar_layout;\n";
5456 Result += "\tstruct _objc_class_ext *ext;\n";
5457 Result += "};\n";
5458 objc_class = true;
5459 }
5460
5461 // Meta-class metadata generation.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005462 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005463 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5464 while (SuperClass) {
5465 RootClass = SuperClass;
5466 SuperClass = SuperClass->getSuperClass();
5467 }
5468 SuperClass = CDecl->getSuperClass();
5469
5470 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5471 Result += CDecl->getNameAsString();
5472 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5473 "{\n\t(struct _objc_class *)\"";
5474 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5475 Result += "\"";
5476
5477 if (SuperClass) {
5478 Result += ", \"";
5479 Result += SuperClass->getNameAsString();
5480 Result += "\", \"";
5481 Result += CDecl->getNameAsString();
5482 Result += "\"";
5483 }
5484 else {
5485 Result += ", 0, \"";
5486 Result += CDecl->getNameAsString();
5487 Result += "\"";
5488 }
5489 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5490 // 'info' field is initialized to CLS_META(2) for metaclass
5491 Result += ", 0,2, sizeof(struct _objc_class), 0";
5492 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5493 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5494 Result += IDecl->getNameAsString();
5495 Result += "\n";
5496 }
5497 else
5498 Result += ", 0\n";
5499 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5500 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5501 Result += CDecl->getNameAsString();
5502 Result += ",0,0\n";
5503 }
5504 else
5505 Result += "\t,0,0,0,0\n";
5506 Result += "};\n";
5507
5508 // class metadata generation.
5509 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5510 Result += CDecl->getNameAsString();
5511 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5512 "{\n\t&_OBJC_METACLASS_";
5513 Result += CDecl->getNameAsString();
5514 if (SuperClass) {
5515 Result += ", \"";
5516 Result += SuperClass->getNameAsString();
5517 Result += "\", \"";
5518 Result += CDecl->getNameAsString();
5519 Result += "\"";
5520 }
5521 else {
5522 Result += ", 0, \"";
5523 Result += CDecl->getNameAsString();
5524 Result += "\"";
5525 }
5526 // 'info' field is initialized to CLS_CLASS(1) for class
5527 Result += ", 0,1";
5528 if (!ObjCSynthesizedStructs.count(CDecl))
5529 Result += ",0";
5530 else {
5531 // class has size. Must synthesize its size.
5532 Result += ",sizeof(struct ";
5533 Result += CDecl->getNameAsString();
5534 if (LangOpts.MicrosoftExt)
5535 Result += "_IMPL";
5536 Result += ")";
5537 }
5538 if (NumIvars > 0) {
5539 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5540 Result += CDecl->getNameAsString();
5541 Result += "\n\t";
5542 }
5543 else
5544 Result += ",0";
5545 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5546 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5547 Result += CDecl->getNameAsString();
5548 Result += ", 0\n\t";
5549 }
5550 else
5551 Result += ",0,0";
5552 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5553 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5554 Result += CDecl->getNameAsString();
5555 Result += ", 0,0\n";
5556 }
5557 else
5558 Result += ",0,0,0\n";
5559 Result += "};\n";
5560}
5561
5562void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5563 int ClsDefCount = ClassImplementation.size();
5564 int CatDefCount = CategoryImplementation.size();
5565
5566 // For each implemented class, write out all its meta data.
5567 for (int i = 0; i < ClsDefCount; i++)
5568 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5569
5570 // For each implemented category, write out all its meta data.
5571 for (int i = 0; i < CatDefCount; i++)
5572 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5573
5574 // Write objc_symtab metadata
5575 /*
5576 struct _objc_symtab
5577 {
5578 long sel_ref_cnt;
5579 SEL *refs;
5580 short cls_def_cnt;
5581 short cat_def_cnt;
5582 void *defs[cls_def_cnt + cat_def_cnt];
5583 };
5584 */
5585
5586 Result += "\nstruct _objc_symtab {\n";
5587 Result += "\tlong sel_ref_cnt;\n";
5588 Result += "\tSEL *refs;\n";
5589 Result += "\tshort cls_def_cnt;\n";
5590 Result += "\tshort cat_def_cnt;\n";
5591 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5592 Result += "};\n\n";
5593
5594 Result += "static struct _objc_symtab "
5595 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5596 Result += "\t0, 0, " + utostr(ClsDefCount)
5597 + ", " + utostr(CatDefCount) + "\n";
5598 for (int i = 0; i < ClsDefCount; i++) {
5599 Result += "\t,&_OBJC_CLASS_";
5600 Result += ClassImplementation[i]->getNameAsString();
5601 Result += "\n";
5602 }
5603
5604 for (int i = 0; i < CatDefCount; i++) {
5605 Result += "\t,&_OBJC_CATEGORY_";
5606 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5607 Result += "_";
5608 Result += CategoryImplementation[i]->getNameAsString();
5609 Result += "\n";
5610 }
5611
5612 Result += "};\n\n";
5613
5614 // Write objc_module metadata
5615
5616 /*
5617 struct _objc_module {
5618 long version;
5619 long size;
5620 const char *name;
5621 struct _objc_symtab *symtab;
5622 }
5623 */
5624
5625 Result += "\nstruct _objc_module {\n";
5626 Result += "\tlong version;\n";
5627 Result += "\tlong size;\n";
5628 Result += "\tconst char *name;\n";
5629 Result += "\tstruct _objc_symtab *symtab;\n";
5630 Result += "};\n\n";
5631 Result += "static struct _objc_module "
5632 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5633 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5634 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5635 Result += "};\n\n";
5636
5637 if (LangOpts.MicrosoftExt) {
5638 if (ProtocolExprDecls.size()) {
5639 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5640 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Stephen Hines176edba2014-12-01 14:53:08 -08005641 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005642 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
Stephen Hines176edba2014-12-01 14:53:08 -08005643 Result += ProtDecl->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005644 Result += " = &_OBJC_PROTOCOL_";
Stephen Hines176edba2014-12-01 14:53:08 -08005645 Result += ProtDecl->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005646 Result += ";\n";
5647 }
5648 Result += "#pragma data_seg(pop)\n\n";
5649 }
5650 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5651 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5652 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5653 Result += "&_OBJC_MODULES;\n";
5654 Result += "#pragma data_seg(pop)\n\n";
5655 }
5656}
5657
5658/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5659/// implementation.
5660void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5661 std::string &Result) {
5662 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5663 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00005664 ObjCCategoryDecl *CDecl
5665 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005666
5667 std::string FullCategoryName = ClassDecl->getNameAsString();
5668 FullCategoryName += '_';
5669 FullCategoryName += IDecl->getNameAsString();
5670
5671 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005672 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005673
5674 // If any of our property implementations have associated getters or
5675 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005676 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005677 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005678 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005679 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005680 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005681 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005682 if (!PD)
5683 continue;
5684 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5685 InstanceMethods.push_back(Getter);
5686 if (PD->isReadOnly())
5687 continue;
5688 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5689 InstanceMethods.push_back(Setter);
5690 }
5691 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5692 true, "CATEGORY_", FullCategoryName.c_str(),
5693 Result);
5694
5695 // Build _objc_method_list for class's class methods if needed
5696 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5697 false, "CATEGORY_", FullCategoryName.c_str(),
5698 Result);
5699
5700 // Protocols referenced in class declaration?
5701 // Null CDecl is case of a category implementation with no category interface
5702 if (CDecl)
5703 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5704 FullCategoryName, Result);
5705 /* struct _objc_category {
5706 char *category_name;
5707 char *class_name;
5708 struct _objc_method_list *instance_methods;
5709 struct _objc_method_list *class_methods;
5710 struct _objc_protocol_list *protocols;
5711 // Objective-C 1.0 extensions
5712 uint32_t size; // sizeof (struct _objc_category)
5713 struct _objc_property_list *instance_properties; // category's own
5714 // @property decl.
5715 };
5716 */
5717
5718 static bool objc_category = false;
5719 if (!objc_category) {
5720 Result += "\nstruct _objc_category {\n";
5721 Result += "\tchar *category_name;\n";
5722 Result += "\tchar *class_name;\n";
5723 Result += "\tstruct _objc_method_list *instance_methods;\n";
5724 Result += "\tstruct _objc_method_list *class_methods;\n";
5725 Result += "\tstruct _objc_protocol_list *protocols;\n";
5726 Result += "\tunsigned int size;\n";
5727 Result += "\tstruct _objc_property_list *instance_properties;\n";
5728 Result += "};\n";
5729 objc_category = true;
5730 }
5731 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5732 Result += FullCategoryName;
5733 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5734 Result += IDecl->getNameAsString();
5735 Result += "\"\n\t, \"";
5736 Result += ClassDecl->getNameAsString();
5737 Result += "\"\n";
5738
5739 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5740 Result += "\t, (struct _objc_method_list *)"
5741 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5742 Result += FullCategoryName;
5743 Result += "\n";
5744 }
5745 else
5746 Result += "\t, 0\n";
5747 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5748 Result += "\t, (struct _objc_method_list *)"
5749 "&_OBJC_CATEGORY_CLASS_METHODS_";
5750 Result += FullCategoryName;
5751 Result += "\n";
5752 }
5753 else
5754 Result += "\t, 0\n";
5755
5756 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5757 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5758 Result += FullCategoryName;
5759 Result += "\n";
5760 }
5761 else
5762 Result += "\t, 0\n";
5763 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5764}
5765
5766// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5767/// class methods.
5768template<typename MethodIterator>
5769void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5770 MethodIterator MethodEnd,
5771 bool IsInstanceMethod,
5772 StringRef prefix,
5773 StringRef ClassName,
5774 std::string &Result) {
5775 if (MethodBegin == MethodEnd) return;
5776
5777 if (!objc_impl_method) {
5778 /* struct _objc_method {
5779 SEL _cmd;
5780 char *method_types;
5781 void *_imp;
5782 }
5783 */
5784 Result += "\nstruct _objc_method {\n";
5785 Result += "\tSEL _cmd;\n";
5786 Result += "\tchar *method_types;\n";
5787 Result += "\tvoid *_imp;\n";
5788 Result += "};\n";
5789
5790 objc_impl_method = true;
5791 }
5792
5793 // Build _objc_method_list for class's methods if needed
5794
5795 /* struct {
5796 struct _objc_method_list *next_method;
5797 int method_count;
5798 struct _objc_method method_list[];
5799 }
5800 */
5801 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5802 Result += "\nstatic struct {\n";
5803 Result += "\tstruct _objc_method_list *next_method;\n";
5804 Result += "\tint method_count;\n";
5805 Result += "\tstruct _objc_method method_list[";
5806 Result += utostr(NumMethods);
5807 Result += "];\n} _OBJC_";
5808 Result += prefix;
5809 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5810 Result += "_METHODS_";
5811 Result += ClassName;
5812 Result += " __attribute__ ((used, section (\"__OBJC, __";
5813 Result += IsInstanceMethod ? "inst" : "cls";
5814 Result += "_meth\")))= ";
5815 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5816
5817 Result += "\t,{{(SEL)\"";
5818 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5819 std::string MethodTypeString;
5820 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5821 Result += "\", \"";
5822 Result += MethodTypeString;
5823 Result += "\", (void *)";
5824 Result += MethodInternalNames[*MethodBegin];
5825 Result += "}\n";
5826 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5827 Result += "\t ,{(SEL)\"";
5828 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5829 std::string MethodTypeString;
5830 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5831 Result += "\", \"";
5832 Result += MethodTypeString;
5833 Result += "\", (void *)";
5834 Result += MethodInternalNames[*MethodBegin];
5835 Result += "}\n";
5836 }
5837 Result += "\t }\n};\n";
5838}
5839
5840Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5841 SourceRange OldRange = IV->getSourceRange();
5842 Expr *BaseExpr = IV->getBase();
5843
5844 // Rewrite the base, but without actually doing replaces.
5845 {
5846 DisableReplaceStmtScope S(*this);
5847 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5848 IV->setBase(BaseExpr);
5849 }
5850
5851 ObjCIvarDecl *D = IV->getDecl();
5852
5853 Expr *Replacement = IV;
5854 if (CurMethodDef) {
5855 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5856 const ObjCInterfaceType *iFaceDecl =
5857 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5858 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5859 // lookup which class implements the instance variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005860 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005861 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5862 clsDeclared);
5863 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5864
5865 // Synthesize an explicit cast to gain access to the ivar.
5866 std::string RecName = clsDeclared->getIdentifier()->getName();
5867 RecName += "_IMPL";
5868 IdentifierInfo *II = &Context->Idents.get(RecName);
5869 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5870 SourceLocation(), SourceLocation(),
5871 II);
5872 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5873 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5874 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5875 CK_BitCast,
5876 IV->getBase());
5877 // Don't forget the parens to enforce the proper binding.
5878 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5879 OldRange.getEnd(),
5880 castExpr);
5881 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005882 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005883 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5884 IV->getLocation(),
5885 D->getType(),
5886 VK_LValue, OK_Ordinary);
5887 Replacement = ME;
5888 } else {
5889 IV->setBase(PE);
5890 }
5891 }
5892 } else { // we are outside a method.
5893 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5894
5895 // Explicit ivar refs need to have a cast inserted.
5896 // FIXME: consider sharing some of this code with the code above.
5897 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5898 const ObjCInterfaceType *iFaceDecl =
5899 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5900 // lookup which class implements the instance variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005901 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005902 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5903 clsDeclared);
5904 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5905
5906 // Synthesize an explicit cast to gain access to the ivar.
5907 std::string RecName = clsDeclared->getIdentifier()->getName();
5908 RecName += "_IMPL";
5909 IdentifierInfo *II = &Context->Idents.get(RecName);
5910 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5911 SourceLocation(), SourceLocation(),
5912 II);
5913 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5914 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5915 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5916 CK_BitCast,
5917 IV->getBase());
5918 // Don't forget the parens to enforce the proper binding.
5919 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5920 IV->getBase()->getLocEnd(), castExpr);
5921 // Cannot delete IV->getBase(), since PE points to it.
5922 // Replace the old base with the cast. This is important when doing
5923 // embedded rewrites. For example, [newInv->_container addObject:0].
5924 IV->setBase(PE);
5925 }
5926 }
5927
5928 ReplaceStmtWithRange(IV, Replacement, OldRange);
5929 return Replacement;
5930}
Stephen Hines176edba2014-12-01 14:53:08 -08005931
5932#endif