blob: dfeb11a9aa71cf843ebb574b88a0db8b90a0e459 [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
Chris Lattner77cd2a02007-10-11 00:43:27 +000032using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000033using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000034
Chris Lattner77cd2a02007-10-11 00:43:27 +000035namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000036 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000037 protected:
38
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000040 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000041 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000047 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000048 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000060 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000061
Chris Lattner2c64b7b2007-10-16 21:07:07 +000062 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000063 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000064 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000065 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000066 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000067 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000068 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000069 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000070 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000072 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
78 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000083
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000084 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000087 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000088 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramere5753592013-09-09 14:48:42 +0000103 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000104 FunctionDecl *CurFunctionDef;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000107 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
113 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000114 SmallVector<Stmt *, 32> Stmts;
115 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000116 // Remember all the @protocol(<expr>) expressions.
117 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000118
119 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000122 SmallVector<BlockExpr *, 32> Blocks;
123 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125
John McCallf4b88a42012-03-10 09:33:50 +0000126 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000127
Steve Naroff54055232008-10-27 17:20:55 +0000128 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000133 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000135 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
136
Steve Naroff54055232008-10-27 17:20:55 +0000137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroff4c3580e2008-12-04 23:50:32 +0000139 // This maps an original source AST to it's rewritten form. This allows
140 // us to avoid rewriting the same node twice (which is very uncommon).
141 // This is needed to support some of the exotic property rewriting.
142 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000143
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000144 // Needed for header files being rewritten
145 bool IsHeader;
146 bool SilenceRewriteMacroWarning;
147 bool objc_impl_method;
148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000150 class DisableReplaceStmtScope {
151 RewriteObjC &R;
152 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000153
John McCall4b9c2d22011-11-06 09:01:30 +0000154 public:
155 DisableReplaceStmtScope(RewriteObjC &R)
156 : R(R), SavedValue(R.DisableReplaceStmt) {
157 R.DisableReplaceStmt = true;
158 }
159 ~DisableReplaceStmtScope() {
160 R.DisableReplaceStmt = SavedValue;
161 }
162 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000163 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattner77cd2a02007-10-11 00:43:27 +0000165 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000166
Chris Lattnerf04da132007-10-24 17:06:59 +0000167 // Top Level Driver code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700168 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000169 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000170 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
171 if (!Class->isThisDeclarationADefinition()) {
172 RewriteForwardClassDecl(D);
173 break;
174 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000175 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000176
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000177 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
178 if (!Proto->isThisDeclarationADefinition()) {
179 RewriteForwardProtocolDecl(D);
180 break;
181 }
182 }
183
Chris Lattner682bf922009-03-29 16:50:03 +0000184 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000185 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000186 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000187 }
188 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000189 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000190 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000191 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000192 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000193
194 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Stephen Hines651f13c2014-04-23 16:59:28 -0700196 void HandleTranslationUnit(ASTContext &C) override;
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000198 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Steve Naroff4c3580e2008-12-04 23:50:32 +0000201 if (ReplacingStmt)
202 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000203
Steve Naroffb619d952008-12-09 12:56:34 +0000204 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000205 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000206
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000208 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000209 ReplacedNodes[Old] = New;
210 return;
211 }
212 if (SilenceRewriteMacroWarning)
213 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000214 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
215 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000216 }
Steve Naroffb619d952008-12-09 12:56:34 +0000217
218 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700219 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
John McCall4b9c2d22011-11-06 09:01:30 +0000220 if (DisableReplaceStmt)
221 return;
222
Nick Lewycky7e749242010-10-31 21:07:24 +0000223 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000224 int Size = Rewrite.getRangeSize(SrcRange);
225 if (Size == -1) {
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 return;
229 }
230 // Get the new text.
231 std::string SStr;
232 llvm::raw_string_ostream S(SStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700233 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000234 const std::string &Str = S.str();
235
236 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000238 ReplacedNodes[Old] = New;
239 return;
240 }
241 if (SilenceRewriteMacroWarning)
242 return;
243 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
244 << Old->getSourceRange();
245 }
246
Chris Lattner5f9e2722011-07-23 10:55:15 +0000247 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000248 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000249 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000250 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000251 SilenceRewriteMacroWarning)
252 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000254 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattneraadaf782008-01-31 19:51:04 +0000257 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000258 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000259 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000260 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000261 SilenceRewriteMacroWarning)
262 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattneraadaf782008-01-31 19:51:04 +0000264 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
265 }
Mike Stump1eb44332009-09-09 15:08:12 +0000266
Chris Lattnerf04da132007-10-24 17:06:59 +0000267 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000268 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000269 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000270 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000271 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000272 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000273 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000274 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000275 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
276 ObjCImplementationDecl *IMD,
277 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000278 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000279 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000280 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
281 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000282 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
283 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000284 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000285 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000286 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
287 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000288 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000289 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000290 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000291 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000292 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000293 void RewriteBlockPointerType(std::string& Str, QualType Type);
294 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000295 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000296 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000297 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000298 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000299
Chris Lattnerf04da132007-10-24 17:06:59 +0000300 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000301 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000302 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000303 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
304 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000305 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000306 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000307 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000308 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000309 void RewriteTryReturnStmts(Stmt *S);
310 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000311 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000312 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000313 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000314 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
315 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000316 Stmt *RewriteBreakStmt(BreakStmt *S);
317 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000318 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000319
Steve Naroff54055232008-10-27 17:20:55 +0000320 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000321 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000322
Mike Stump1eb44332009-09-09 15:08:12 +0000323 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000324 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000325 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000326 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000327 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000328 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000329
330 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
331 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700332
333 virtual void Initialize(ASTContext &context) override = 0;
334
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000335 // Metadata Rewriting.
336 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
337 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
338 StringRef prefix,
339 StringRef ClassName,
340 std::string &Result) = 0;
341 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
342 std::string &Result) = 0;
343 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
344 StringRef prefix,
345 StringRef ClassName,
346 std::string &Result) = 0;
347 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
348 std::string &Result) = 0;
349
350 // Rewriting ivar access
351 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
352 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
353 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000354
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000355 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000356 // rewriting routines on the new ASTs.
357 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
358 Expr **args, unsigned nargs,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000361 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
362 QualType msgSendType,
363 QualType returnType,
364 SmallVectorImpl<QualType> &ArgTypes,
365 SmallVectorImpl<Expr*> &MsgExprs,
366 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000367 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
368 SourceLocation StartLoc=SourceLocation(),
369 SourceLocation EndLoc=SourceLocation());
370
371 void SynthCountByEnumWithState(std::string &buf);
372 void SynthMsgSendFunctionDecl();
373 void SynthMsgSendSuperFunctionDecl();
374 void SynthMsgSendStretFunctionDecl();
375 void SynthMsgSendFpretFunctionDecl();
376 void SynthMsgSendSuperStretFunctionDecl();
377 void SynthGetClassFunctionDecl();
378 void SynthGetMetaClassFunctionDecl();
379 void SynthGetSuperClassFunctionDecl();
380 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000381 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000382
383 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000384 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000386 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000387 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000388 std::string SynthesizeBlockImpl(BlockExpr *CE,
389 std::string Tag, std::string Desc);
390 std::string SynthesizeBlockDescriptor(std::string DescTag,
391 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000392 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000393 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000394 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000397 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
398 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000399 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Fariborz Jahanian58457172011-12-05 18:43:13 +0000401 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000402 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000403 void WarnAboutReturnGotoStmts(Stmt *S);
404 void HasReturnStmts(Stmt *S, bool &hasReturns);
405 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
406 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
407 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
408
409 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000410 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000411 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000412 void GetInnerBlockDeclRefExprs(Stmt *S,
413 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000414 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Steve Naroff54055232008-10-27 17:20:55 +0000416 // We avoid calling Type::isBlockPointerType(), since it operates on the
417 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000418 bool isTopLevelBlockPointerType(QualType T) {
419 return isa<BlockPointerType>(T);
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000422 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
423 /// to a function pointer type and upon success, returns true; false
424 /// otherwise.
425 bool convertBlockPointerToFunctionPointer(QualType &T) {
426 if (isTopLevelBlockPointerType(T)) {
427 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
428 T = Context->getPointerType(BPT->getPointeeType());
429 return true;
430 }
431 return false;
432 }
433
Fariborz Jahanian58457172011-12-05 18:43:13 +0000434 bool needToScanForQualifiers(QualType T);
435 QualType getSuperStructType();
436 QualType getConstantStringStructType();
437 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
438 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
439
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000440 void convertToUnqualifiedObjCType(QualType &T) {
441 if (T->isObjCQualifiedIdType())
442 T = Context->getObjCIdType();
443 else if (T->isObjCQualifiedClassType())
444 T = Context->getObjCClassType();
445 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000446 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
447 if (const ObjCObjectPointerType * OBJPT =
448 T->getAsObjCInterfacePointerType()) {
449 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
450 T = QualType(IFaceT, 0);
451 T = Context->getPointerType(T);
452 }
453 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000454 }
455
Steve Naroff54055232008-10-27 17:20:55 +0000456 // FIXME: This predicate seems like it would be useful to add to ASTContext.
457 bool isObjCType(QualType T) {
458 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
459 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff54055232008-10-27 17:20:55 +0000461 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Steve Naroff54055232008-10-27 17:20:55 +0000463 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
464 OCT == Context->getCanonicalType(Context->getObjCClassType()))
465 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Ted Kremenek6217b802009-07-29 21:53:49 +0000467 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000468 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000469 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000470 return true;
471 }
472 return false;
473 }
474 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000475 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000476 void GetExtentOfArgList(const char *Name, const char *&LParen,
477 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000478
Steve Naroff621edce2009-04-29 16:37:50 +0000479 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000480 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000481 if (From[i] == '"')
482 To += "\\\"";
483 else
484 To += From[i];
485 }
486 }
John McCalle23cf432010-12-14 08:05:40 +0000487
488 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000489 ArrayRef<QualType> args,
John McCalle23cf432010-12-14 08:05:40 +0000490 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000491 if (result == Context->getObjCInstanceType())
492 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000493 FunctionProtoType::ExtProtoInfo fpi;
494 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000495 return Context->getFunctionType(result, args, fpi);
John McCalle23cf432010-12-14 08:05:40 +0000496 }
John McCall9d125032010-01-15 18:39:57 +0000497
Fariborz Jahanian58457172011-12-05 18:43:13 +0000498 // Helper function: create a CStyleCastExpr with trivial type source info.
499 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
500 CastKind Kind, Expr *E) {
501 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700502 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
503 TInfo, SourceLocation(), SourceLocation());
Fariborz Jahanian58457172011-12-05 18:43:13 +0000504 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700505
506 StringLiteral *getStringLiteral(StringRef Str) {
507 QualType StrType = Context->getConstantArrayType(
508 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
509 0);
510 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
511 /*Pascal=*/false, StrType, SourceLocation());
512 }
Fariborz Jahanian58457172011-12-05 18:43:13 +0000513 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000514
515 class RewriteObjCFragileABI : public RewriteObjC {
516 public:
517
518 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
519 DiagnosticsEngine &D, const LangOptions &LOpts,
520 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
521 D, LOpts,
522 silenceMacroWarn) {}
523
524 ~RewriteObjCFragileABI() {}
Stephen Hines651f13c2014-04-23 16:59:28 -0700525 virtual void Initialize(ASTContext &context) override;
526
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000527 // Rewriting metadata
528 template<typename MethodIterator>
529 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
530 MethodIterator MethodEnd,
531 bool IsInstanceMethod,
532 StringRef prefix,
533 StringRef ClassName,
534 std::string &Result);
Stephen Hines651f13c2014-04-23 16:59:28 -0700535 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
536 StringRef prefix, StringRef ClassName,
537 std::string &Result) override;
538 void RewriteObjCProtocolListMetaData(
539 const ObjCList<ObjCProtocolDecl> &Prots,
540 StringRef prefix, StringRef ClassName, std::string &Result) override;
541 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
542 std::string &Result) override;
543 void RewriteMetaDataIntoBuffer(std::string &Result) override;
544 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
545 std::string &Result) override;
546
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000547 // Rewriting ivar
Stephen Hines651f13c2014-04-23 16:59:28 -0700548 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
549 std::string &Result) override;
550 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000551 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000552}
553
Mike Stump1eb44332009-09-09 15:08:12 +0000554void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
555 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000556 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000557 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700558 for (const auto &I : fproto->param_types())
559 if (isTopLevelBlockPointerType(I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000560 // All the args are checked/rewritten. Don't call twice!
561 RewriteBlockPointerDecl(D);
562 break;
563 }
564 }
565}
566
567void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000568 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000569 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000570 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000571}
572
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000573static bool IsHeaderFile(const std::string &Filename) {
574 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000576 if (DotPos == std::string::npos) {
577 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000578 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000579 }
Mike Stump1eb44332009-09-09 15:08:12 +0000580
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000581 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
582 // C header: .h
583 // C++ header: .hh or .H;
584 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000585}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000586
Chris Lattner5f9e2722011-07-23 10:55:15 +0000587RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000588 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000589 bool silenceMacroWarn)
590 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
591 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000592 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000593 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000594 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000595 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
596 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000597 "rewriter doesn't support user-specified control flow semantics "
598 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000599}
600
Eli Friedmanbce831b2009-05-18 22:29:17 +0000601ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000602 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000603 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000604 const LangOptions &LOpts,
605 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000606 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000607}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000608
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000609void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610 Context = &context;
611 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000612 TUDecl = Context->getTranslationUnitDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700613 MsgSendFunctionDecl = nullptr;
614 MsgSendSuperFunctionDecl = nullptr;
615 MsgSendStretFunctionDecl = nullptr;
616 MsgSendSuperStretFunctionDecl = nullptr;
617 MsgSendFpretFunctionDecl = nullptr;
618 GetClassFunctionDecl = nullptr;
619 GetMetaClassFunctionDecl = nullptr;
620 GetSuperClassFunctionDecl = nullptr;
621 SelGetUidFunctionDecl = nullptr;
622 CFStringFunctionDecl = nullptr;
623 ConstantStringClassReference = nullptr;
624 NSStringRecord = nullptr;
625 CurMethodDef = nullptr;
626 CurFunctionDef = nullptr;
627 CurFunctionDeclToDeclareForBlock = nullptr;
628 GlobalVarDecl = nullptr;
629 SuperStructDecl = nullptr;
630 ProtocolTypeDecl = nullptr;
631 ConstantStringDecl = nullptr;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000632 BcLabelCount = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700633 SuperConstructorFunctionDecl = nullptr;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000634 NumObjCStringLiterals = 0;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700635 PropParentMap = nullptr;
636 CurrentBody = nullptr;
Steve Naroffb619d952008-12-09 12:56:34 +0000637 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000638 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000640 // Get the ID and start/end of the main file.
641 MainFileID = SM->getMainFileID();
642 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
643 MainFileStart = MainBuf->getBufferStart();
644 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000645
David Blaikie4e4d0842012-03-11 07:00:24 +0000646 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000647}
648
Chris Lattnerf04da132007-10-24 17:06:59 +0000649//===----------------------------------------------------------------------===//
650// Top Level Driver Code
651//===----------------------------------------------------------------------===//
652
Chris Lattner682bf922009-03-29 16:50:03 +0000653void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000654 if (Diags.hasErrorOccurred())
655 return;
656
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000657 // Two cases: either the decl could be in the main file, or it could be in a
658 // #included file. If the former, rewrite it now. If the later, check to see
659 // if we rewrote the #include/#import.
660 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000661 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000663 // If this is for a builtin, ignore it.
664 if (Loc.isInvalid()) return;
665
Steve Naroffebf2b562007-10-23 23:50:29 +0000666 // Look for built-in declarations that we need to refer during the rewrite.
667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000668 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000669 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000670 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000671 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000672 ConstantStringClassReference = FVD;
673 return;
674 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000675 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
676 if (ID->isThisDeclarationADefinition())
677 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000678 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000679 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000680 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000681 if (PD->isThisDeclarationADefinition())
682 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000683 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
684 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000685 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
686 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000687 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000688 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
689 if (!IFace->isThisDeclarationADefinition()) {
690 SmallVector<Decl *, 8> DG;
691 SourceLocation StartLoc = IFace->getLocStart();
692 do {
693 if (isa<ObjCInterfaceDecl>(*DI) &&
694 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
695 StartLoc == (*DI)->getLocStart())
696 DG.push_back(*DI);
697 else
698 break;
699
Douglas Gregor7723fec2011-12-15 20:29:51 +0000700 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000701 } while (DI != DIEnd);
702 RewriteForwardClassDecl(DG);
703 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000704 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000705 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000706
707 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
708 if (!Proto->isThisDeclarationADefinition()) {
709 SmallVector<Decl *, 8> DG;
710 SourceLocation StartLoc = Proto->getLocStart();
711 do {
712 if (isa<ObjCProtocolDecl>(*DI) &&
713 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
714 StartLoc == (*DI)->getLocStart())
715 DG.push_back(*DI);
716 else
717 break;
718
719 ++DI;
720 } while (DI != DIEnd);
721 RewriteForwardProtocolDecl(DG);
722 continue;
723 }
724 }
725
Chris Lattner682bf922009-03-29 16:50:03 +0000726 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000727 ++DI;
728 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000729 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000730 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000731 if (SM->isWrittenInMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000732 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000733}
734
Chris Lattnerf04da132007-10-24 17:06:59 +0000735//===----------------------------------------------------------------------===//
736// Syntactic (non-AST) Rewriting Code
737//===----------------------------------------------------------------------===//
738
Steve Naroffb29b4272008-04-14 22:03:09 +0000739void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000740 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000741 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000742 const char *MainBufStart = MainBuf.begin();
743 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000744 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000746 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000747 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
748 if (*BufPtr == '#') {
749 if (++BufPtr == MainBufEnd)
750 return;
751 while (*BufPtr == ' ' || *BufPtr == '\t')
752 if (++BufPtr == MainBufEnd)
753 return;
754 if (!strncmp(BufPtr, "import", ImportLen)) {
755 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000756 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000757 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000758 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000759 BufPtr += ImportLen;
760 }
761 }
762 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000763}
764
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000765static std::string getIvarAccessString(ObjCIvarDecl *OID) {
766 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000767 std::string S;
768 S = "((struct ";
769 S += ClassDecl->getIdentifier()->getName();
770 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000771 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772 return S;
773}
774
Steve Naroffa0876e82008-12-02 17:36:43 +0000775void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
776 ObjCImplementationDecl *IMD,
777 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000778 static bool objcGetPropertyDefined = false;
779 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000780 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000781 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000782 const char *startBuf = SM->getCharacterData(startLoc);
783 assert((*startBuf == '@') && "bogus @synthesize location");
784 const char *semiBuf = strchr(startBuf, ';');
785 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000786 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000787 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000788
789 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
790 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000796 if (!OID)
797 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000798 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000799 if (!PD->getGetterMethodDecl()->isDefined()) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000800 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
801 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000802 ObjCPropertyDecl::OBJC_PR_copy));
803 std::string Getr;
804 if (GenGetProperty && !objcGetPropertyDefined) {
805 objcGetPropertyDefined = true;
806 // FIXME. Is this attribute correct in all cases?
807 Getr = "\nextern \"C\" __declspec(dllimport) "
808 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000809 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000810 RewriteObjCMethodDecl(OID->getContainingInterface(),
811 PD->getGetterMethodDecl(), Getr);
812 Getr += "{ ";
813 // Synthesize an explicit cast to gain access to the ivar.
814 // See objc-act.c:objc_synthesize_new_getter() for details.
815 if (GenGetProperty) {
816 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
817 Getr += "typedef ";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700818 const FunctionType *FPRetType = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700819 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000820 FPRetType);
821 Getr += " _TYPE";
822 if (FPRetType) {
823 Getr += ")"; // close the precedence "scope" for "*".
824
825 // Now, emit the argument types (if any).
826 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
827 Getr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -0700828 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000829 if (i) Getr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -0700830 std::string ParamStr =
831 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000832 Getr += ParamStr;
833 }
834 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700835 if (FT->getNumParams())
836 Getr += ", ";
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000837 Getr += "...";
838 }
839 Getr += ")";
840 } else
841 Getr += "()";
842 }
843 Getr += ";\n";
844 Getr += "return (_TYPE)";
845 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000846 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000847 Getr += ", 1)";
848 }
849 else
850 Getr += "return " + getIvarAccessString(OID);
851 Getr += "; }";
852 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000853 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000854
855 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000856 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Steve Naroffeb0646c2008-12-02 15:48:25 +0000858 // Generate the 'setter' function.
859 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000860 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000861 ObjCPropertyDecl::OBJC_PR_copy);
862 if (GenSetProperty && !objcSetPropertyDefined) {
863 objcSetPropertyDefined = true;
864 // FIXME. Is this attribute correct in all cases?
865 Setr = "\nextern \"C\" __declspec(dllimport) "
866 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
867 }
868
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000869 RewriteObjCMethodDecl(OID->getContainingInterface(),
870 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000871 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000872 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000873 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000874 if (GenSetProperty) {
875 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000876 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000877 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000878 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000879 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000880 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000881 Setr += "0, ";
882 else
883 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000884 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000885 Setr += "1)";
886 else
887 Setr += "0)";
888 }
889 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000890 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000891 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000892 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000893 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000894 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000895}
Chris Lattner8a12c272007-10-11 18:38:32 +0000896
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000897static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
898 std::string &typedefString) {
899 typedefString += "#ifndef _REWRITER_typedef_";
900 typedefString += ForwardDecl->getNameAsString();
901 typedefString += "\n";
902 typedefString += "#define _REWRITER_typedef_";
903 typedefString += ForwardDecl->getNameAsString();
904 typedefString += "\n";
905 typedefString += "typedef struct objc_object ";
906 typedefString += ForwardDecl->getNameAsString();
907 typedefString += ";\n#endif\n";
908}
909
Douglas Gregor375bb142011-12-27 22:43:10 +0000910void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000911 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000912 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000913 const char *startBuf = SM->getCharacterData(startLoc);
914 const char *semiPtr = strchr(startBuf, ';');
915 // Replace the @class with typedefs corresponding to the classes.
916 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
917}
918
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000919void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000920 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000921 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000922 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000923 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000924 // Translate to typedef's that forward reference structs with the same name
925 // as the class. As a convenience, we include the original declaration
926 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000927 typedefString += "// @class ";
928 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000929 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000930 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000931 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000932 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000933 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000934 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000935}
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Craig Topper6b9240e2013-07-05 19:34:19 +0000937void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000938 std::string typedefString;
939 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000940 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000941 if (i == 0) {
942 typedefString += "// @class ";
943 typedefString += ForwardDecl->getNameAsString();
944 typedefString += ";\n";
945 }
946 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
947 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000948 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000949}
950
Steve Naroffb29b4272008-04-14 22:03:09 +0000951void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000952 // When method is a synthesized one, such as a getter/setter there is
953 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000954 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000955 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000956 SourceLocation LocStart = Method->getLocStart();
957 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000958
Chandler Carruth64211622011-07-25 21:09:52 +0000959 if (SM->getExpansionLineNumber(LocEnd) >
960 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000961 InsertText(LocStart, "#if 0\n");
962 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000963 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000964 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000965 }
966}
967
Mike Stump1eb44332009-09-09 15:08:12 +0000968void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000969 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Benjamin Kramerd999b372010-02-14 14:14:16 +0000971 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000972 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000973}
974
Steve Naroffb29b4272008-04-14 22:03:09 +0000975void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000976 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Steve Naroff423cb562007-10-30 13:30:57 +0000978 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000979 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Stephen Hines651f13c2014-04-23 16:59:28 -0700981 for (auto *I : CatDecl->properties())
982 RewriteProperty(I);
983 for (auto *I : CatDecl->instance_methods())
984 RewriteMethodDeclaration(I);
985 for (auto *I : CatDecl->class_methods())
986 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000987
Steve Naroff423cb562007-10-30 13:30:57 +0000988 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000989 ReplaceText(CatDecl->getAtEndRange().getBegin(),
990 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000991}
992
Steve Naroffb29b4272008-04-14 22:03:09 +0000993void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000994 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000995 assert(PDecl->isThisDeclarationADefinition());
996
Steve Naroff752d6ef2007-10-30 16:42:30 +0000997 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Stephen Hines651f13c2014-04-23 16:59:28 -07001000 for (auto *I : PDecl->instance_methods())
1001 RewriteMethodDeclaration(I);
1002 for (auto *I : PDecl->class_methods())
1003 RewriteMethodDeclaration(I);
1004 for (auto *I : PDecl->properties())
1005 RewriteProperty(I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001006
Steve Naroff752d6ef2007-10-30 16:42:30 +00001007 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001008 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001009 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001010
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001011 // Must comment out @optional/@required
1012 const char *startBuf = SM->getCharacterData(LocStart);
1013 const char *endBuf = SM->getCharacterData(LocEnd);
1014 for (const char *p = startBuf; p < endBuf; p++) {
1015 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001016 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001017 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001019 }
1020 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001021 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001022 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001024 }
1025 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001026}
1027
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001028void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1029 SourceLocation LocStart = (*D.begin())->getLocStart();
1030 if (LocStart.isInvalid())
1031 llvm_unreachable("Invalid SourceLocation");
1032 // FIXME: handle forward protocol that are declared across multiple lines.
1033 ReplaceText(LocStart, 0, "// ");
1034}
1035
1036void
Craig Topper6b9240e2013-07-05 19:34:19 +00001037RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001038 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001039 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001040 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001041 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001042 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001043}
1044
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001045void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1046 const FunctionType *&FPRetType) {
1047 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001048 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001049 else if (T->isFunctionPointerType() ||
1050 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001051 // needs special handling, since pointer-to-functions have special
1052 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001053 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001054 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001055 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001056 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001057 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001058 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001059 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001060 ResultStr +=
1061 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001062 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001063 }
1064 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001065 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001066}
1067
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001068void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1069 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001070 std::string &ResultStr) {
1071 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001072 const FunctionType *FPRetType = nullptr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001073 ResultStr += "\nstatic ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001074 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001075 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001078 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001080 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001081 NameStr += "_I_";
1082 else
1083 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001085 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001086 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001087
1088 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001089 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001090 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001091 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001092 }
Mike Stump1eb44332009-09-09 15:08:12 +00001093 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001094 {
1095 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 int len = selString.size();
1097 for (int i = 0; i < len; i++)
1098 if (selString[i] == ':')
1099 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001100 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001102 // Remember this name for metadata emission
1103 MethodInternalNames[OMD] = NameStr;
1104 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 // Rewrite arguments
1107 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001109 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001110 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001111 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001112 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001113 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001114 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001115 ResultStr += "struct ";
1116 }
1117 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001118 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001119 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001120 }
1121 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001122 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001123 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001125 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001126 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001127 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 // Method arguments.
Stephen Hines651f13c2014-04-23 16:59:28 -07001130 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001132 if (PDecl->getType()->isObjCQualifiedIdType()) {
1133 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001134 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001135 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001136 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001137 QualType QT = PDecl->getType();
1138 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001139 (void)convertBlockPointerToFunctionPointer(QT);
1140 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001141 ResultStr += Name;
1142 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001143 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001144 if (OMD->isVariadic())
1145 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001146 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Steve Naroff76e429d2008-07-16 14:40:40 +00001148 if (FPRetType) {
1149 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Steve Naroff76e429d2008-07-16 14:40:40 +00001151 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001152 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001153 ResultStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07001154 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001155 if (i) ResultStr += ", ";
Stephen Hines651f13c2014-04-23 16:59:28 -07001156 std::string ParamStr =
1157 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001158 ResultStr += ParamStr;
1159 }
1160 if (FT->isVariadic()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001161 if (FT->getNumParams())
1162 ResultStr += ", ";
Steve Naroff76e429d2008-07-16 14:40:40 +00001163 ResultStr += "...";
1164 }
1165 ResultStr += ")";
1166 } else {
1167 ResultStr += "()";
1168 }
1169 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001171void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001172 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1173 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001175 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Stephen Hines651f13c2014-04-23 16:59:28 -07001177 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 std::string ResultStr;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001179 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001180 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001181 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001182
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001183 const char *startBuf = SM->getCharacterData(LocStart);
1184 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001185 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 }
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Stephen Hines651f13c2014-04-23 16:59:28 -07001188 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001189 std::string ResultStr;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001190 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001191 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001192 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194 const char *startBuf = SM->getCharacterData(LocStart);
1195 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001196 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001197 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001198 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1199 RewritePropertyImplDecl(I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001200
Benjamin Kramerd999b372010-02-14 14:14:16 +00001201 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001202}
1203
Steve Naroffb29b4272008-04-14 22:03:09 +00001204void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001205 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001206 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001207 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001208 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001209 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001210 ResultStr += "\n";
1211 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001212 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001213 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001214 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001215 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001216 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001217 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001218 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001219 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001220 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Stephen Hines651f13c2014-04-23 16:59:28 -07001222 for (auto *I : ClassDecl->properties())
1223 RewriteProperty(I);
1224 for (auto *I : ClassDecl->instance_methods())
1225 RewriteMethodDeclaration(I);
1226 for (auto *I : ClassDecl->class_methods())
1227 RewriteMethodDeclaration(I);
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001228
Steve Naroff2feac5e2007-10-30 03:43:13 +00001229 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001230 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1231 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001232}
1233
John McCall4b9c2d22011-11-06 09:01:30 +00001234Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1235 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001236
John McCall4b9c2d22011-11-06 09:01:30 +00001237 // We just magically know some things about the structure of this
1238 // expression.
1239 ObjCMessageExpr *OldMsg =
1240 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1241 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCall4b9c2d22011-11-06 09:01:30 +00001243 // Because the rewriter doesn't allow us to rewrite rewritten code,
1244 // we need to suppress rewriting the sub-statements.
1245 Expr *Base, *RHS;
1246 {
1247 DisableReplaceStmtScope S(*this);
1248
1249 // Rebuild the base expression if we have one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001250 Base = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001251 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1252 Base = OldMsg->getInstanceReceiver();
1253 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1254 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1255 }
1256
1257 // Rebuild the RHS.
1258 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1259 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1260 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1261 }
1262
1263 // TODO: avoid this copy.
1264 SmallVector<SourceLocation, 1> SelLocs;
1265 OldMsg->getSelectorLocs(SelLocs);
1266
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001267 ObjCMessageExpr *NewMsg = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001268 switch (OldMsg->getReceiverKind()) {
1269 case ObjCMessageExpr::Class:
1270 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1271 OldMsg->getValueKind(),
1272 OldMsg->getLeftLoc(),
1273 OldMsg->getClassReceiverTypeInfo(),
1274 OldMsg->getSelector(),
1275 SelLocs,
1276 OldMsg->getMethodDecl(),
1277 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001278 OldMsg->getRightLoc(),
1279 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001280 break;
1281
1282 case ObjCMessageExpr::Instance:
1283 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1284 OldMsg->getValueKind(),
1285 OldMsg->getLeftLoc(),
1286 Base,
1287 OldMsg->getSelector(),
1288 SelLocs,
1289 OldMsg->getMethodDecl(),
1290 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001291 OldMsg->getRightLoc(),
1292 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001293 break;
1294
1295 case ObjCMessageExpr::SuperClass:
1296 case ObjCMessageExpr::SuperInstance:
1297 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1298 OldMsg->getValueKind(),
1299 OldMsg->getLeftLoc(),
1300 OldMsg->getSuperLoc(),
1301 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1302 OldMsg->getSuperType(),
1303 OldMsg->getSelector(),
1304 SelLocs,
1305 OldMsg->getMethodDecl(),
1306 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001307 OldMsg->getRightLoc(),
1308 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001309 break;
1310 }
1311
1312 Stmt *Replacement = SynthMessageExpr(NewMsg);
1313 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1314 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001315}
1316
John McCall4b9c2d22011-11-06 09:01:30 +00001317Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1318 SourceRange OldRange = PseudoOp->getSourceRange();
1319
1320 // We just magically know some things about the structure of this
1321 // expression.
1322 ObjCMessageExpr *OldMsg =
1323 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1324
1325 // Because the rewriter doesn't allow us to rewrite rewritten code,
1326 // we need to suppress rewriting the sub-statements.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001327 Expr *Base = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001328 {
1329 DisableReplaceStmtScope S(*this);
1330
1331 // Rebuild the base expression if we have one.
1332 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1333 Base = OldMsg->getInstanceReceiver();
1334 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1335 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001336 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001337 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001338
John McCall4b9c2d22011-11-06 09:01:30 +00001339 // Intentionally empty.
1340 SmallVector<SourceLocation, 1> SelLocs;
1341 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001342
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001343 ObjCMessageExpr *NewMsg = nullptr;
John McCall4b9c2d22011-11-06 09:01:30 +00001344 switch (OldMsg->getReceiverKind()) {
1345 case ObjCMessageExpr::Class:
1346 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1347 OldMsg->getValueKind(),
1348 OldMsg->getLeftLoc(),
1349 OldMsg->getClassReceiverTypeInfo(),
1350 OldMsg->getSelector(),
1351 SelLocs,
1352 OldMsg->getMethodDecl(),
1353 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001354 OldMsg->getRightLoc(),
1355 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001356 break;
1357
1358 case ObjCMessageExpr::Instance:
1359 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1360 OldMsg->getValueKind(),
1361 OldMsg->getLeftLoc(),
1362 Base,
1363 OldMsg->getSelector(),
1364 SelLocs,
1365 OldMsg->getMethodDecl(),
1366 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001367 OldMsg->getRightLoc(),
1368 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001369 break;
1370
1371 case ObjCMessageExpr::SuperClass:
1372 case ObjCMessageExpr::SuperInstance:
1373 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1374 OldMsg->getValueKind(),
1375 OldMsg->getLeftLoc(),
1376 OldMsg->getSuperLoc(),
1377 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1378 OldMsg->getSuperType(),
1379 OldMsg->getSelector(),
1380 SelLocs,
1381 OldMsg->getMethodDecl(),
1382 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001383 OldMsg->getRightLoc(),
1384 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001385 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001386 }
John McCall4b9c2d22011-11-06 09:01:30 +00001387
1388 Stmt *Replacement = SynthMessageExpr(NewMsg);
1389 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1390 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001391}
1392
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001393/// SynthCountByEnumWithState - To print:
1394/// ((unsigned int (*)
1395/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001396/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001397/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001398/// "countByEnumeratingWithState:objects:count:"),
1399/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001400/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001401///
Steve Naroffb29b4272008-04-14 22:03:09 +00001402void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001403 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1404 "id *, unsigned int))(void *)objc_msgSend)";
1405 buf += "\n\t\t";
1406 buf += "((id)l_collection,\n\t\t";
1407 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1408 buf += "\n\t\t";
1409 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001410 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001412
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001413/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1414/// statement to exit to its outer synthesized loop.
1415///
Steve Naroffb29b4272008-04-14 22:03:09 +00001416Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001417 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1418 return S;
1419 // replace break with goto __break_label
1420 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001422 SourceLocation startLoc = S->getLocStart();
1423 buf = "goto __break_label_";
1424 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001425 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001426
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001427 return nullptr;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001428}
1429
1430/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1431/// statement to continue with its inner synthesized loop.
1432///
Steve Naroffb29b4272008-04-14 22:03:09 +00001433Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001434 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1435 return S;
1436 // replace continue with goto __continue_label
1437 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001439 SourceLocation startLoc = S->getLocStart();
1440 buf = "goto __continue_label_";
1441 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001442 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001444 return nullptr;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445}
1446
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001447/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001448/// It rewrites:
1449/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001451/// Into:
1452/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001453/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001455/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001456/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001457/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001458/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001459/// if (limit) {
1460/// unsigned long startMutations = *enumState.mutationsPtr;
1461/// do {
1462/// unsigned long counter = 0;
1463/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001464/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001465/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001466/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001467/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001468/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001469/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001470/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001471/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001473/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001474/// }
1475/// else
1476/// elem = nil;
1477/// }
1478///
Steve Naroffb29b4272008-04-14 22:03:09 +00001479Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001480 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001481 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001482 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001483 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001484 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001485 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001489 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001490 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491 std::string buf;
1492 buf = "\n{\n\t";
1493 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1494 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001495 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001496 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001497 if (ElementType->isObjCQualifiedIdType() ||
1498 ElementType->isObjCQualifiedInterfaceType())
1499 // Simply use 'id' for all qualified types.
1500 elementTypeAsString = "id";
1501 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001502 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001503 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001504 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001505 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 buf += elementName;
1507 buf += ";\n\t";
1508 }
Chris Lattner06767512008-04-08 05:52:18 +00001509 else {
1510 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001511 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001512 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1513 if (VD->getType()->isObjCQualifiedIdType() ||
1514 VD->getType()->isObjCQualifiedInterfaceType())
1515 // Simply use 'id' for all qualified types.
1516 elementTypeAsString = "id";
1517 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001518 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 // struct __objcFastEnumerationState enumState = { 0 };
1522 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001523 // id __rw_items[16];
1524 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 // id l_collection = (id)
1526 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001527 // Find start location of 'collection' the hard way!
1528 const char *startCollectionBuf = startBuf;
1529 startCollectionBuf += 3; // skip 'for'
1530 startCollectionBuf = strchr(startCollectionBuf, '(');
1531 startCollectionBuf++; // skip '('
1532 // find 'in' and skip it.
1533 while (*startCollectionBuf != ' ' ||
1534 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1535 (*(startCollectionBuf+3) != ' ' &&
1536 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1537 startCollectionBuf++;
1538 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001539
1540 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001541 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001543 SourceLocation rightParenLoc = S->getRParenLoc();
1544 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001545 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001546 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001548 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001549 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001550 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001551 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001552 // ((unsigned int (*)
1553 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001554 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001555 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001556 // "countByEnumeratingWithState:objects:count:"),
1557 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001558 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001559 buf += "unsigned long limit =\n\t\t";
1560 SynthCountByEnumWithState(buf);
1561 buf += ";\n\t";
1562 /// if (limit) {
1563 /// unsigned long startMutations = *enumState.mutationsPtr;
1564 /// do {
1565 /// unsigned long counter = 0;
1566 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001567 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001569 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 buf += "if (limit) {\n\t";
1571 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1572 buf += "do {\n\t\t";
1573 buf += "unsigned long counter = 0;\n\t\t";
1574 buf += "do {\n\t\t\t";
1575 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1576 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1577 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001578 buf += " = (";
1579 buf += elementTypeAsString;
1580 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001582 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001584 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001585 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001586 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001587 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001588 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001590 /// }
1591 /// else
1592 /// elem = nil;
1593 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001594 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001595 buf = ";\n\t";
1596 buf += "__continue_label_";
1597 buf += utostr(ObjCBcLabelNo.back());
1598 buf += ": ;";
1599 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600 buf += "} while (counter < limit);\n\t";
1601 buf += "} while (limit = ";
1602 SynthCountByEnumWithState(buf);
1603 buf += ");\n\t";
1604 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001605 buf += " = ((";
1606 buf += elementTypeAsString;
1607 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 buf += "__break_label_";
1609 buf += utostr(ObjCBcLabelNo.back());
1610 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001611 buf += "}\n\t";
1612 buf += "else\n\t\t";
1613 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001614 buf += " = ((";
1615 buf += elementTypeAsString;
1616 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001620 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001621 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001622 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001623 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001624 } else {
1625 /* Need to treat single statements specially. For example:
1626 *
1627 * for (A *a in b) if (stuff()) break;
1628 * for (A *a in b) xxxyy;
1629 *
1630 * The following code simply scans ahead to the semi to find the actual end.
1631 */
1632 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1633 const char *semiBuf = strchr(stmtBuf, ';');
1634 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001635 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001636 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001637 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001638 Stmts.pop_back();
1639 ObjCBcLabelNo.pop_back();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001640 return nullptr;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001641}
1642
Mike Stump1eb44332009-09-09 15:08:12 +00001643/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001644/// This routine rewrites @synchronized(expr) stmt;
1645/// into:
1646/// objc_sync_enter(expr);
1647/// @try stmt @finally { objc_sync_exit(expr); }
1648///
Steve Naroffb29b4272008-04-14 22:03:09 +00001649Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001650 // Get the start location and compute the semi location.
1651 SourceLocation startLoc = S->getLocStart();
1652 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001654 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001655
1656 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001657 buf = "objc_sync_enter((id)";
1658 const char *lparenBuf = startBuf;
1659 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001660 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001661 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1662 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001663 // been rewritten! (which implies the SourceLocation's are invalid).
1664 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001665 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001666 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001667 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001668 buf = ");\n";
1669 // declare a new scope with two variables, _stack and _rethrow.
1670 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1671 buf += "int buf[18/*32-bit i386*/];\n";
1672 buf += "char *pointers[4];} _stack;\n";
1673 buf += "id volatile _rethrow = 0;\n";
1674 buf += "objc_exception_try_enter(&_stack);\n";
1675 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001676 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001677 startLoc = S->getSynchBody()->getLocEnd();
1678 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001679
Steve Naroffc7089f12008-08-19 13:04:19 +00001680 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001681 SourceLocation lastCurlyLoc = startLoc;
1682 buf = "}\nelse {\n";
1683 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001684 buf += "}\n";
1685 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001686 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001687
1688 std::string syncBuf;
1689 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001690
1691 Expr *syncExpr = S->getSynchExpr();
1692 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1693 ? CK_BitCast :
1694 syncExpr->getType()->isBlockPointerType()
1695 ? CK_BlockPointerToObjCPointerCast
1696 : CK_CPointerToObjCPointerCast;
1697 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1698 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001699 std::string syncExprBufS;
1700 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001701 assert(syncExpr != nullptr && "Expected non-null Expr");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001702 syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703 syncBuf += syncExprBuf.str();
1704 syncBuf += ");";
1705
1706 buf += syncBuf;
1707 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001708 buf += "}\n";
1709 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001710
Benjamin Kramerd999b372010-02-14 14:14:16 +00001711 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001712
1713 bool hasReturns = false;
1714 HasReturnStmts(S->getSynchBody(), hasReturns);
1715 if (hasReturns)
1716 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1717
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001718 return nullptr;
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001719}
1720
Steve Naroffb85e77a2009-12-05 21:43:12 +00001721void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1722{
Steve Naroff8c565152008-12-05 17:03:39 +00001723 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001724 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001725 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001726 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001727
Steve Naroffb85e77a2009-12-05 21:43:12 +00001728 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001729 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001730 TryFinallyContainsReturnDiag);
1731 }
1732 return;
1733}
1734
Steve Naroffb85e77a2009-12-05 21:43:12 +00001735void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1736{
1737 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001738 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001739 if (*CI)
1740 HasReturnStmts(*CI, hasReturns);
1741
1742 if (isa<ReturnStmt>(S))
1743 hasReturns = true;
1744 return;
1745}
1746
1747void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1748 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001749 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001750 if (*CI) {
1751 RewriteTryReturnStmts(*CI);
1752 }
1753 if (isa<ReturnStmt>(S)) {
1754 SourceLocation startLoc = S->getLocStart();
1755 const char *startBuf = SM->getCharacterData(startLoc);
1756
1757 const char *semiBuf = strchr(startBuf, ';');
1758 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001759 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001760
1761 std::string buf;
1762 buf = "{ objc_exception_try_exit(&_stack); return";
1763
Benjamin Kramerd999b372010-02-14 14:14:16 +00001764 ReplaceText(startLoc, 6, buf);
1765 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001766 }
1767 return;
1768}
1769
1770void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1771 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001772 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001773 if (*CI) {
1774 RewriteSyncReturnStmts(*CI, syncExitBuf);
1775 }
1776 if (isa<ReturnStmt>(S)) {
1777 SourceLocation startLoc = S->getLocStart();
1778 const char *startBuf = SM->getCharacterData(startLoc);
1779
1780 const char *semiBuf = strchr(startBuf, ';');
1781 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001782 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001783
1784 std::string buf;
1785 buf = "{ objc_exception_try_exit(&_stack);";
1786 buf += syncExitBuf;
1787 buf += " return";
1788
Benjamin Kramerd999b372010-02-14 14:14:16 +00001789 ReplaceText(startLoc, 6, buf);
1790 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001791 }
1792 return;
1793}
1794
Steve Naroffb29b4272008-04-14 22:03:09 +00001795Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001796 // Get the start location and compute the semi location.
1797 SourceLocation startLoc = S->getLocStart();
1798 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Steve Naroff75730982007-11-07 04:08:17 +00001800 assert((*startBuf == '@') && "bogus @try location");
1801
1802 std::string buf;
1803 // declare a new scope with two variables, _stack and _rethrow.
1804 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1805 buf += "int buf[18/*32-bit i386*/];\n";
1806 buf += "char *pointers[4];} _stack;\n";
1807 buf += "id volatile _rethrow = 0;\n";
1808 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001809 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001810
Benjamin Kramerd999b372010-02-14 14:14:16 +00001811 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001812
Steve Naroff75730982007-11-07 04:08:17 +00001813 startLoc = S->getTryBody()->getLocEnd();
1814 startBuf = SM->getCharacterData(startLoc);
1815
1816 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Steve Naroff75730982007-11-07 04:08:17 +00001818 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001819 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001820 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001821 buf = " /* @catch begin */ else {\n";
1822 buf += " id _caught = objc_exception_extract(&_stack);\n";
1823 buf += " objc_exception_try_enter (&_stack);\n";
1824 buf += " if (_setjmp(_stack.buf))\n";
1825 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1826 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Benjamin Kramerd999b372010-02-14 14:14:16 +00001828 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001829 } else { /* no catch list */
1830 buf = "}\nelse {\n";
1831 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1832 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001833 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001834 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001835 Stmt *lastCatchBody = nullptr;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001836 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1837 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001838 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001839
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001840 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001841 buf = "if ("; // we are generating code for the first catch clause
1842 else
1843 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001844 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001845 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Steve Naroff75730982007-11-07 04:08:17 +00001847 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Steve Naroff75730982007-11-07 04:08:17 +00001849 const char *lParenLoc = strchr(startBuf, '(');
1850
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001851 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001852 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001853 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001854 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1855 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001856 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001857 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001858 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Steve Naroffe12e6922008-02-01 20:02:07 +00001860 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001861 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001862 } else if (catchDecl) {
1863 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001864 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001865 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001866 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001867 } else if (const ObjCObjectPointerType *Ptr =
1868 t->getAs<ObjCObjectPointerType>()) {
1869 // Should be a pointer to a class.
1870 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1871 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001872 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001873 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001874 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001875 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001876 }
1877 }
1878 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001879 lastCatchBody = Catch->getCatchBody();
1880 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001881 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1882 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1883 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1884 assert((*rParenBuf == ')') && "bogus @catch paren location");
1885 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Mike Stump1eb44332009-09-09 15:08:12 +00001887 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001888 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001889 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001890 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001891 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001892 }
Steve Naroff75730982007-11-07 04:08:17 +00001893 }
1894 // Complete the catch list...
1895 if (lastCatchBody) {
1896 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001897 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1898 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Steve Naroff378f47a2008-09-11 15:29:03 +00001900 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001901 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001902 buf = "} /* last catch end */\n";
1903 buf += "else {\n";
1904 buf += " _rethrow = _caught;\n";
1905 buf += " objc_exception_try_exit(&_stack);\n";
1906 buf += "} } /* @catch end */\n";
1907 if (!S->getFinallyStmt())
1908 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001909 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Steve Naroff75730982007-11-07 04:08:17 +00001911 // Set lastCurlyLoc
1912 lastCurlyLoc = lastCatchBody->getLocEnd();
1913 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001914 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001915 startLoc = finalStmt->getLocStart();
1916 startBuf = SM->getCharacterData(startLoc);
1917 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Benjamin Kramerd999b372010-02-14 14:14:16 +00001919 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Steve Naroff75730982007-11-07 04:08:17 +00001921 Stmt *body = finalStmt->getFinallyBody();
1922 SourceLocation startLoc = body->getLocStart();
1923 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001924 assert(*SM->getCharacterData(startLoc) == '{' &&
1925 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001926 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001927 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001929 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001930 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001931 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001932 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Steve Naroff75730982007-11-07 04:08:17 +00001934 // Set lastCurlyLoc
1935 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Steve Naroff8c565152008-12-05 17:03:39 +00001937 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001938 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001939 } else { /* no finally clause - make sure we synthesize an implicit one */
1940 buf = "{ /* implicit finally clause */\n";
1941 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1942 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1943 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001944 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001945
1946 // Now check for any return/continue/go statements within the @try.
1947 // The implicit finally clause won't called if the @try contains any
1948 // jump statements.
1949 bool hasReturns = false;
1950 HasReturnStmts(S->getTryBody(), hasReturns);
1951 if (hasReturns)
1952 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001953 }
1954 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001955 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001956 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001957 return nullptr;
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001958}
1959
Mike Stump1eb44332009-09-09 15:08:12 +00001960// This can't be done with ReplaceStmt(S, ThrowExpr), since
1961// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001962// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001963Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001964 // Get the start location and compute the semi location.
1965 SourceLocation startLoc = S->getLocStart();
1966 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Steve Naroff2bd03922007-11-07 15:32:26 +00001968 assert((*startBuf == '@') && "bogus @throw location");
1969
1970 std::string buf;
1971 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001972 if (S->getThrowExpr())
1973 buf = "objc_exception_throw(";
1974 else // add an implicit argument
1975 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001977 // handle "@ throw" correctly.
1978 const char *wBuf = strchr(startBuf, 'w');
1979 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001980 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Steve Naroff2bd03922007-11-07 15:32:26 +00001982 const char *semiBuf = strchr(startBuf, ';');
1983 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001984 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001985 ReplaceText(semiLoc, 1, ");");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001986 return nullptr;
Steve Naroff2bd03922007-11-07 15:32:26 +00001987}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001988
Steve Naroffb29b4272008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001990 // Create a new string expression.
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001991 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001992 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Stephen Hines651f13c2014-04-23 16:59:28 -07001993 Expr *Replacement = getStringLiteral(StrEncoding);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001994 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattner07506182007-11-30 22:53:43 +00001996 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001997 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001998 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001999}
2000
Steve Naroffb29b4272008-04-14 22:03:09 +00002001Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002002 if (!SelGetUidFunctionDecl)
2003 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002004 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2005 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002006 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002007 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002008 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2009 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002010 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002011 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002012 return SelExp;
2013}
2014
Steve Naroffb29b4272008-04-14 22:03:09 +00002015CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002016 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2017 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002018 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002019 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Steve Naroffebf2b562007-10-23 23:50:29 +00002021 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002022 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2023 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Steve Naroffebf2b562007-10-23 23:50:29 +00002025 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002026 QualType pToFunc = Context->getPointerType(msgSendType);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002027 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002028 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002029 DRE, nullptr, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCall183700f2009-09-21 23:43:11 +00002031 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002033 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002034 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
John McCallf89e55a2010-11-18 06:31:45 +00002035 FT->getCallResultType(*Context),
2036 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002037 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002038}
2039
Steve Naroffd5255f52007-11-01 13:24:47 +00002040static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2041 const char *&startRef, const char *&endRef) {
2042 while (startBuf < endBuf) {
2043 if (*startBuf == '<')
2044 startRef = startBuf; // mark the start.
2045 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002046 if (startRef && *startRef == '<') {
2047 endRef = startBuf; // mark the end.
2048 return true;
2049 }
2050 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002051 }
2052 startBuf++;
2053 }
2054 return false;
2055}
2056
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002057static void scanToNextArgument(const char *&argRef) {
2058 int angle = 0;
2059 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2060 if (*argRef == '<')
2061 angle++;
2062 else if (*argRef == '>')
2063 angle--;
2064 argRef++;
2065 }
2066 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2067}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002068
Steve Naroffb29b4272008-04-14 22:03:09 +00002069bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002070 if (T->isObjCQualifiedIdType())
2071 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002072 if (const PointerType *PT = T->getAs<PointerType>()) {
2073 if (PT->getPointeeType()->isObjCQualifiedIdType())
2074 return true;
2075 }
2076 if (T->isObjCObjectPointerType()) {
2077 T = T->getPointeeType();
2078 return T->isObjCQualifiedInterfaceType();
2079 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002080 if (T->isArrayType()) {
2081 QualType ElemTy = Context->getBaseElementType(T);
2082 return needToScanForQualifiers(ElemTy);
2083 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002084 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002085}
2086
Steve Naroff4f95b752008-07-29 18:15:38 +00002087void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2088 QualType Type = E->getType();
2089 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002090 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Steve Naroffcda658e2008-11-19 21:15:47 +00002092 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2093 Loc = ECE->getLParenLoc();
2094 EndLoc = ECE->getRParenLoc();
2095 } else {
2096 Loc = E->getLocStart();
2097 EndLoc = E->getLocEnd();
2098 }
2099 // This will defend against trying to rewrite synthesized expressions.
2100 if (Loc.isInvalid() || EndLoc.isInvalid())
2101 return;
2102
Steve Naroff4f95b752008-07-29 18:15:38 +00002103 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002104 const char *endBuf = SM->getCharacterData(EndLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002105 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroff4f95b752008-07-29 18:15:38 +00002106 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2107 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002108 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2109 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002110 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002111 InsertText(LessLoc, "/*");
2112 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002113 }
2114 }
2115}
2116
Steve Naroffb29b4272008-04-14 22:03:09 +00002117void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002118 SourceLocation Loc;
2119 QualType Type;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002120 const FunctionProtoType *proto = nullptr;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002121 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2122 Loc = VD->getLocation();
2123 Type = VD->getType();
2124 }
2125 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2126 Loc = FD->getLocation();
2127 // Check for ObjC 'id' and class types that have been adorned with protocol
2128 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002129 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002130 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002131 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002132 if (!proto)
2133 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002134 Type = proto->getReturnType();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002135 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002136 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2137 Loc = FD->getLocation();
2138 Type = FD->getType();
2139 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002140 else
2141 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002143 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002144 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Steve Naroffd5255f52007-11-01 13:24:47 +00002146 const char *endBuf = SM->getCharacterData(Loc);
2147 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002148 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002149 startBuf--; // scan backward (from the decl location) for return type.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002150 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroffd5255f52007-11-01 13:24:47 +00002151 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2152 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002153 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2154 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002155 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002156 InsertText(LessLoc, "/*");
2157 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002158 }
2159 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002160 if (!proto)
2161 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002162 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002163 const char *startBuf = SM->getCharacterData(Loc);
2164 const char *startFuncBuf = startBuf;
Stephen Hines651f13c2014-04-23 16:59:28 -07002165 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2166 if (needToScanForQualifiers(proto->getParamType(i))) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002167 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Steve Naroffd5255f52007-11-01 13:24:47 +00002169 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002170 // scan forward (from the decl location) for argument types.
2171 scanToNextArgument(endBuf);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002172 const char *startRef = nullptr, *endRef = nullptr;
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2174 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002175 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002176 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002177 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002178 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002179 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002182 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002183 startBuf = ++endBuf;
2184 }
2185 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002186 // If the function name is derived from a macro expansion, then the
2187 // argument buffer will not follow the name. Need to speak with Chris.
2188 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 startBuf++; // scan forward (from the decl location) for argument types.
2190 startBuf++;
2191 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002192 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002193}
2194
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002195void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2196 QualType QT = ND->getType();
2197 const Type* TypePtr = QT->getAs<Type>();
2198 if (!isa<TypeOfExprType>(TypePtr))
2199 return;
2200 while (isa<TypeOfExprType>(TypePtr)) {
2201 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2202 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2203 TypePtr = QT->getAs<Type>();
2204 }
2205 // FIXME. This will not work for multiple declarators; as in:
2206 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002207 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002208 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2209 const char *startBuf = SM->getCharacterData(DeclLoc);
2210 if (ND->getInit()) {
2211 std::string Name(ND->getNameAsString());
2212 TypeAsString += " " + Name + " = ";
2213 Expr *E = ND->getInit();
2214 SourceLocation startLoc;
2215 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2216 startLoc = ECE->getLParenLoc();
2217 else
2218 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002219 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002220 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002221 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002222 }
2223 else {
2224 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002225 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002226 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002227 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002228 }
2229}
2230
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002231// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002232void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002233 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002234 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002235 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002236 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002237 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002238 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002239 SourceLocation(),
2240 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002241 SelGetUidIdent, getFuncType,
2242 nullptr, SC_Extern);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002243}
2244
Steve Naroffb29b4272008-04-14 22:03:09 +00002245void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002246 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002247 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002248 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002249 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002250 return;
2251 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002252 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002253}
2254
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002255void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002256 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002257 const char *argPtr = TypeString.c_str();
2258 if (!strchr(argPtr, '^')) {
2259 Str += TypeString;
2260 return;
2261 }
2262 while (*argPtr) {
2263 Str += (*argPtr == '^' ? '*' : *argPtr);
2264 argPtr++;
2265 }
2266}
2267
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002268// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002269void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2270 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002271 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002272 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002273 const char *argPtr = TypeString.c_str();
2274 int paren = 0;
2275 while (*argPtr) {
2276 switch (*argPtr) {
2277 case '(':
2278 Str += *argPtr;
2279 paren++;
2280 break;
2281 case ')':
2282 Str += *argPtr;
2283 paren--;
2284 break;
2285 case '^':
2286 Str += '*';
2287 if (paren == 1)
2288 Str += VD->getNameAsString();
2289 break;
2290 default:
2291 Str += *argPtr;
2292 break;
2293 }
2294 argPtr++;
2295 }
2296}
2297
2298
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002299void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2300 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2301 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2302 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2303 if (!proto)
2304 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07002305 QualType Type = proto->getReturnType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002306 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002307 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002308 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002309 FdStr += "(";
Stephen Hines651f13c2014-04-23 16:59:28 -07002310 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002311 for (unsigned i = 0; i < numArgs; i++) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002312 QualType ArgType = proto->getParamType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002313 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002314 if (i+1 < numArgs)
2315 FdStr += ", ";
2316 }
2317 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002318 InsertText(FunLocStart, FdStr);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002319 CurFunctionDeclToDeclareForBlock = nullptr;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002320}
2321
Benjamin Kramere5753592013-09-09 14:48:42 +00002322// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2323void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2324 if (SuperConstructorFunctionDecl)
Steve Naroffc0a123c2008-03-11 17:37:02 +00002325 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002326 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002327 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002328 QualType argT = Context->getObjCIdType();
2329 assert(!argT.isNull() && "Can't find 'id' type");
2330 ArgTys.push_back(argT);
2331 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002332 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002333 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002334 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002338 nullptr, SC_Extern);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002339}
2340
Steve Naroff09b266e2007-10-30 23:14:51 +00002341// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002342void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002343 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002344 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002345 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002346 assert(!argT.isNull() && "Can't find 'id' type");
2347 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002348 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002349 assert(!argT.isNull() && "Can't find 'SEL' type");
2350 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002351 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002352 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002353 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002354 SourceLocation(),
2355 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002356 msgSendIdent, msgSendType,
2357 nullptr, SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002358}
2359
Steve Naroff874e2322007-11-15 10:28:18 +00002360// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002361void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002362 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002363 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002364 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002365 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002366 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002367 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2368 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2369 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002371 assert(!argT.isNull() && "Can't find 'SEL' type");
2372 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002373 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002374 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002375 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002376 SourceLocation(),
2377 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002378 msgSendIdent, msgSendType,
2379 nullptr, SC_Extern);
Steve Naroff874e2322007-11-15 10:28:18 +00002380}
2381
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002382// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002383void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002384 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002385 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002386 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002387 assert(!argT.isNull() && "Can't find 'id' type");
2388 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002389 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002390 assert(!argT.isNull() && "Can't find 'SEL' type");
2391 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002392 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002393 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002394 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002395 SourceLocation(),
2396 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002397 msgSendIdent, msgSendType,
2398 nullptr, SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002399}
2400
Mike Stump1eb44332009-09-09 15:08:12 +00002401// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002402// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002403void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002404 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002405 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002406 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002407 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002408 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002409 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002410 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2411 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2412 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002413 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 assert(!argT.isNull() && "Can't find 'SEL' type");
2415 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002416 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002417 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002418 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002419 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002420 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002421 msgSendIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002422 msgSendType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002423 SC_Extern);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002424}
2425
Steve Naroff1284db82008-05-08 22:02:18 +00002426// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002427void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002428 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002429 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002430 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002431 assert(!argT.isNull() && "Can't find 'id' type");
2432 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002433 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002434 assert(!argT.isNull() && "Can't find 'SEL' type");
2435 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002436 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002437 ArgTys, /*isVariadic=*/true);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002438 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002439 SourceLocation(),
2440 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002441 msgSendIdent, msgSendType,
2442 nullptr, SC_Extern);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002443}
2444
Steve Naroff09b266e2007-10-30 23:14:51 +00002445// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002446void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002447 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002448 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002449 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002450 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002451 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002452 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002453 SourceLocation(),
2454 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002455 getClassIdent, getClassType,
2456 nullptr, SC_Extern);
Steve Naroff09b266e2007-10-30 23:14:51 +00002457}
2458
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002459// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2460void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2461 IdentifierInfo *getSuperClassIdent =
2462 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002463 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002464 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002465 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002466 ArgTys);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002467 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002468 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002469 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002470 getSuperClassIdent,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002471 getClassType, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002472 SC_Extern);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002473}
2474
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002475// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002476void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002477 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002478 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002479 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002480 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002481 ArgTys);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002482 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002483 SourceLocation(),
2484 SourceLocation(),
2485 getClassIdent, getClassType,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002486 nullptr, SC_Extern);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002487}
2488
Steve Naroffb29b4272008-04-14 22:03:09 +00002489Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002490 assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002491 QualType strType = getConstantStringStructType();
2492
2493 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002494
2495 std::string tmpName = InFileName;
2496 unsigned i;
2497 for (i=0; i < tmpName.length(); i++) {
2498 char c = tmpName.at(i);
Stephen Hines651f13c2014-04-23 16:59:28 -07002499 // replace any non-alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002500 if (!isAlphanumeric(c))
Steve Naroff7691d9b2008-05-31 03:35:42 +00002501 tmpName[i] = '_';
2502 }
2503 S += tmpName;
2504 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002505 S += utostr(NumObjCStringLiterals++);
2506
Steve Naroffba92b2e2008-03-27 22:29:16 +00002507 Preamble += "static __NSConstantStringImpl " + S;
2508 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2509 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002510 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002511 std::string prettyBufS;
2512 llvm::raw_string_ostream prettyBuf(prettyBufS);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002513 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002514 Preamble += prettyBuf.str();
2515 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002516 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002517
2518 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002519 SourceLocation(), &Context->Idents.get(S),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002520 strType, nullptr, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002521 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002522 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002523 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002524 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002525 VK_RValue, OK_Ordinary,
2526 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002527 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002528 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002529 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002530 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002531 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002532 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002533}
2534
Steve Naroff874e2322007-11-15 10:28:18 +00002535// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002536QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002537 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002538 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002539 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002540 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002541 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Steve Naroff874e2322007-11-15 10:28:18 +00002543 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002544 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002545 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002546 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002547
Steve Naroff874e2322007-11-15 10:28:18 +00002548 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002549 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002550 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002551 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002552 SourceLocation(), nullptr,
2553 FieldTypes[i], nullptr,
2554 /*BitWidth=*/nullptr,
Richard Smith7a614d82011-06-11 17:19:42 +00002555 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002556 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002557 }
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregor838db382010-02-11 01:19:42 +00002559 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002560 }
2561 return Context->getTagDeclType(SuperStructDecl);
2562}
2563
Steve Naroffb29b4272008-04-14 22:03:09 +00002564QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002565 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002566 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002567 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002568 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002569 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002571 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002572 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002573 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002574 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002575 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002576 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002577 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002578 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002579
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002580 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002581 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002582 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2583 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002584 SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002585 SourceLocation(), nullptr,
2586 FieldTypes[i], nullptr,
2587 /*BitWidth=*/nullptr,
Richard Smith7a614d82011-06-11 17:19:42 +00002588 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002589 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002590 }
2591
Douglas Gregor838db382010-02-11 01:19:42 +00002592 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002593 }
2594 return Context->getTagDeclType(ConstantStringDecl);
2595}
2596
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002597CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2598 QualType msgSendType,
2599 QualType returnType,
2600 SmallVectorImpl<QualType> &ArgTypes,
2601 SmallVectorImpl<Expr*> &MsgExprs,
2602 ObjCMethodDecl *Method) {
2603 // Create a reference to the objc_msgSend_stret() declaration.
2604 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2605 false, msgSendType,
2606 VK_LValue, SourceLocation());
2607 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2608 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2609 Context->getPointerType(Context->VoidTy),
2610 CK_BitCast, STDRE);
2611 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002612 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2613 Method ? Method->isVariadic()
2614 : false);
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002615 castType = Context->getPointerType(castType);
2616 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2617 cast);
2618
2619 // Don't forget the parens to enforce the proper binding.
2620 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2621
2622 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002623 CallExpr *STCE = new (Context) CallExpr(
2624 *Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002625 return STCE;
2626
2627}
2628
2629
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002630Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2631 SourceLocation StartLoc,
2632 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002633 if (!SelGetUidFunctionDecl)
2634 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002635 if (!MsgSendFunctionDecl)
2636 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002637 if (!MsgSendSuperFunctionDecl)
2638 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002639 if (!MsgSendStretFunctionDecl)
2640 SynthMsgSendStretFunctionDecl();
2641 if (!MsgSendSuperStretFunctionDecl)
2642 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002643 if (!MsgSendFpretFunctionDecl)
2644 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002645 if (!GetClassFunctionDecl)
2646 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002647 if (!GetSuperClassFunctionDecl)
2648 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002649 if (!GetMetaClassFunctionDecl)
2650 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Steve Naroff874e2322007-11-15 10:28:18 +00002652 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002653 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2654 // May need to use objc_msgSend_stret() as well.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002655 FunctionDecl *MsgSendStretFlavor = nullptr;
Steve Naroff621edce2009-04-29 16:37:50 +00002656 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002657 QualType resultType = mDecl->getReturnType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002658 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002659 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002660 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002661 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002662 }
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Steve Naroff934f2762007-10-24 22:48:43 +00002664 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002665 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002666 switch (Exp->getReceiverKind()) {
2667 case ObjCMessageExpr::SuperClass: {
2668 MsgSendFlavor = MsgSendSuperFunctionDecl;
2669 if (MsgSendStretFlavor)
2670 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2671 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Douglas Gregor04badcf2010-04-21 00:45:42 +00002673 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Chris Lattner5f9e2722011-07-23 10:55:15 +00002675 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002676
Douglas Gregor04badcf2010-04-21 00:45:42 +00002677 // set the receiver to self, the first argument to all methods.
2678 InitExprs.push_back(
2679 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002680 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002681 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002682 false,
John McCallf89e55a2010-11-18 06:31:45 +00002683 Context->getObjCIdType(),
2684 VK_RValue,
2685 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002686 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregor04badcf2010-04-21 00:45:42 +00002688 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002689 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002690 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002691 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2692 &ClsExprs[0],
2693 ClsExprs.size(),
2694 StartLoc,
2695 EndLoc);
2696 // (Class)objc_getClass("CurrentClass")
2697 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2698 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002699 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002700 ClsExprs.clear();
2701 ClsExprs.push_back(ArgExpr);
2702 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2703 &ClsExprs[0], ClsExprs.size(),
2704 StartLoc, EndLoc);
2705
2706 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2707 // To turn off a warning, type-cast to 'id'
2708 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2709 NoTypeInfoCStyleCastExpr(Context,
2710 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002711 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002712 // struct objc_super
2713 QualType superType = getSuperStructType();
2714 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002715
Francois Pichet62ec1f22011-09-17 17:15:52 +00002716 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002717 SynthSuperConstructorFunctionDecl();
2718 // Simulate a constructor call...
2719 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002720 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002721 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002722 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002723 superType, VK_LValue,
2724 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002725 // The code for super is a little tricky to prevent collision with
2726 // the structure definition in the header. The rewriter has it's own
2727 // internal definition (__rw_objc_super) that is uses. This is why
2728 // we need the cast below. For example:
2729 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2730 //
John McCall2de56d12010-08-25 11:45:40 +00002731 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002733 VK_RValue, OK_Ordinary,
2734 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002735 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2736 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002737 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002738 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 // (struct objc_super) { <exprs from above> }
2740 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002741 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002742 SourceLocation());
2743 TypeSourceInfo *superTInfo
2744 = Context->getTrivialTypeSourceInfo(superType);
2745 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002746 superType, VK_LValue,
2747 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002748 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002749 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002750 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002751 VK_RValue, OK_Ordinary,
2752 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002753 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002754 MsgExprs.push_back(SuperRep);
2755 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002756 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002757
2758 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002759 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002760 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002761 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 IdentifierInfo *clsName = Class->getIdentifier();
Stephen Hines651f13c2014-04-23 16:59:28 -07002763 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002764 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2765 &ClsExprs[0],
2766 ClsExprs.size(),
2767 StartLoc, EndLoc);
2768 MsgExprs.push_back(Cls);
2769 break;
2770 }
2771
2772 case ObjCMessageExpr::SuperInstance:{
2773 MsgSendFlavor = MsgSendSuperFunctionDecl;
2774 if (MsgSendStretFlavor)
2775 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2776 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2777 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002778 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002779
2780 InitExprs.push_back(
2781 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002782 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002783 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002784 false,
John McCallf89e55a2010-11-18 06:31:45 +00002785 Context->getObjCIdType(),
2786 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002787 ); // set the 'receiver'.
2788
2789 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002790 SmallVector<Expr*, 8> ClsExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002791 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002792 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2793 &ClsExprs[0],
2794 ClsExprs.size(),
2795 StartLoc, EndLoc);
2796 // (Class)objc_getClass("CurrentClass")
2797 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2798 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002799 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 ClsExprs.clear();
2801 ClsExprs.push_back(ArgExpr);
2802 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2803 &ClsExprs[0], ClsExprs.size(),
2804 StartLoc, EndLoc);
2805
2806 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2807 // To turn off a warning, type-cast to 'id'
2808 InitExprs.push_back(
2809 // set 'super class', using class_getSuperclass().
2810 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002811 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 // struct objc_super
2813 QualType superType = getSuperStructType();
2814 Expr *SuperRep;
2815
Francois Pichet62ec1f22011-09-17 17:15:52 +00002816 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00002817 SynthSuperConstructorFunctionDecl();
2818 // Simulate a constructor call...
2819 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002820 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002821 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002822 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00002823 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 // The code for super is a little tricky to prevent collision with
2825 // the structure definition in the header. The rewriter has it's own
2826 // internal definition (__rw_objc_super) that is uses. This is why
2827 // we need the cast below. For example:
2828 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2829 //
John McCall2de56d12010-08-25 11:45:40 +00002830 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002832 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 SourceLocation());
2834 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2835 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002836 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 } else {
2838 // (struct objc_super) { <exprs from above> }
2839 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002840 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002841 SourceLocation());
2842 TypeSourceInfo *superTInfo
2843 = Context->getTrivialTypeSourceInfo(superType);
2844 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002845 superType, VK_RValue, ILE,
2846 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 }
2848 MsgExprs.push_back(SuperRep);
2849 break;
2850 }
2851
2852 case ObjCMessageExpr::Instance: {
2853 // Remove all type-casts because it may contain objc-style types; e.g.
2854 // Foo<Proto> *.
2855 Expr *recExpr = Exp->getInstanceReceiver();
2856 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2857 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002858 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2859 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2860 ? CK_BlockPointerToObjCPointerCast
2861 : CK_CPointerToObjCPointerCast;
2862
Douglas Gregor04badcf2010-04-21 00:45:42 +00002863 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002864 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002865 MsgExprs.push_back(recExpr);
2866 break;
2867 }
2868 }
2869
Steve Naroffbeaf2992007-11-03 11:27:19 +00002870 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002871 SmallVector<Expr*, 8> SelExprs;
Stephen Hines651f13c2014-04-23 16:59:28 -07002872 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Steve Naroff934f2762007-10-24 22:48:43 +00002873 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002874 &SelExprs[0], SelExprs.size(),
2875 StartLoc,
2876 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002877 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002878
Steve Naroff934f2762007-10-24 22:48:43 +00002879 // Now push any user supplied arguments.
2880 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002881 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002882 // Make all implicit casts explicit...ICE comes in handy:-)
2883 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2884 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002885 QualType type = ICE->getType();
2886 if (needToScanForQualifiers(type))
2887 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002888 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002889 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002890 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002891 CastKind CK;
2892 if (SubExpr->getType()->isIntegralType(*Context) &&
2893 type->isBooleanType()) {
2894 CK = CK_IntegralToBoolean;
2895 } else if (type->isObjCObjectPointerType()) {
2896 if (SubExpr->getType()->isBlockPointerType()) {
2897 CK = CK_BlockPointerToObjCPointerCast;
2898 } else if (SubExpr->getType()->isPointerType()) {
2899 CK = CK_CPointerToObjCPointerCast;
2900 } else {
2901 CK = CK_BitCast;
2902 }
2903 } else {
2904 CK = CK_BitCast;
2905 }
2906
2907 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002908 }
2909 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002910 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002911 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002912 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002913 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002914 CastKind CK;
2915 if (userExpr->getType()->isIntegralType(*Context)) {
2916 CK = CK_IntegralToPointer;
2917 } else if (userExpr->getType()->isBlockPointerType()) {
2918 CK = CK_BlockPointerToObjCPointerCast;
2919 } else if (userExpr->getType()->isPointerType()) {
2920 CK = CK_CPointerToObjCPointerCast;
2921 } else {
2922 CK = CK_BitCast;
2923 }
John McCall9d125032010-01-15 18:39:57 +00002924 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002925 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002926 }
Mike Stump1eb44332009-09-09 15:08:12 +00002927 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002928 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002929 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2930 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002931 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002932 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002933 }
Steve Naroffab972d32007-11-04 22:37:50 +00002934 // Generate the funky cast.
2935 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002936 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002937 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002938
Steve Naroffab972d32007-11-04 22:37:50 +00002939 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002940 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2941 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2942 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002943 ArgTypes.push_back(Context->getObjCIdType());
2944 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002945 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002946 // Push any user argument types.
Stephen Hines651f13c2014-04-23 16:59:28 -07002947 for (const auto *PI : OMD->params()) {
2948 QualType t = PI->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002949 ? Context->getObjCIdType()
Stephen Hines651f13c2014-04-23 16:59:28 -07002950 : PI->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002951 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002952 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002953 ArgTypes.push_back(t);
2954 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002955 returnType = Exp->getType();
2956 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002957 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002958 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002959 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002960 }
2961 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002962 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Steve Naroffab972d32007-11-04 22:37:50 +00002964 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002965 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002966 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002967
Mike Stump1eb44332009-09-09 15:08:12 +00002968 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002969 // If we don't do this cast, we get the following bizarre warning/note:
2970 // xx.m:13: warning: function called through a non-compatible type
2971 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002972 cast = NoTypeInfoCStyleCastExpr(Context,
2973 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002974 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Steve Naroffab972d32007-11-04 22:37:50 +00002976 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00002977 // If we don't have a method decl, force a variadic cast.
2978 const ObjCMethodDecl *MD = Exp->getMethodDecl();
John McCalle23cf432010-12-14 08:05:40 +00002979 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002980 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002981 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002982 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002983 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002984
2985 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002986 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002987
John McCall183700f2009-09-21 23:43:11 +00002988 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Stephen Hines651f13c2014-04-23 16:59:28 -07002989 CallExpr *CE = new (Context)
2990 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002991 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002992 if (MsgSendStretFlavor) {
2993 // We have the method which returns a struct/union. Must also generate
2994 // call to objc_msgSend_stret and hang both varieties on a conditional
2995 // expression which dictate which one to envoke depending on size of
2996 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002997
2998 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2999 msgSendType, returnType,
3000 ArgTypes, MsgExprs,
3001 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003003 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003004 UnaryExprOrTypeTraitExpr *sizeofExpr =
3005 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3006 Context->getTrivialTypeSourceInfo(returnType),
3007 Context->getSizeType(), SourceLocation(),
3008 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003009 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3010 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3011 // For X86 it is more complicated and some kind of target specific routine
3012 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003013 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003014 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003015 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3016 llvm::APInt(IntSize, 8),
3017 Context->IntTy,
3018 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003019 BinaryOperator *lessThanExpr =
3020 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003021 VK_RValue, OK_Ordinary, SourceLocation(),
3022 false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003023 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003024 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003025 new (Context) ConditionalOperator(lessThanExpr,
3026 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003027 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003028 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003029 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3030 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003031 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003032 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003033 return ReplacingStmt;
3034}
3035
Steve Naroffb29b4272008-04-14 22:03:09 +00003036Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003037 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3038 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Steve Naroff934f2762007-10-24 22:48:43 +00003040 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003041 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003042
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003043 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003044 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003045}
3046
Steve Naroff621edce2009-04-29 16:37:50 +00003047// typedef struct objc_object Protocol;
3048QualType RewriteObjC::getProtocolType() {
3049 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003050 TypeSourceInfo *TInfo
3051 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003052 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003053 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003054 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003055 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003056 }
3057 return Context->getTypeDeclType(ProtocolTypeDecl);
3058}
3059
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003060/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003061/// a synthesized/forward data reference (to the protocol's metadata).
3062/// The forward references (and metadata) are generated in
3063/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003064Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003065 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3066 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003067 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003068 SourceLocation(), ID, getProtocolType(),
3069 nullptr, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003070 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3071 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003072 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003073 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003074 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003075 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003076 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003077 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003078 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003079 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003080 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003081 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003083}
3084
Mike Stump1eb44332009-09-09 15:08:12 +00003085bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003086 const char *endBuf) {
3087 while (startBuf < endBuf) {
3088 if (*startBuf == '#') {
3089 // Skip whitespace.
3090 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3091 ;
3092 if (!strncmp(startBuf, "if", strlen("if")) ||
3093 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3094 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3095 !strncmp(startBuf, "define", strlen("define")) ||
3096 !strncmp(startBuf, "undef", strlen("undef")) ||
3097 !strncmp(startBuf, "else", strlen("else")) ||
3098 !strncmp(startBuf, "elif", strlen("elif")) ||
3099 !strncmp(startBuf, "endif", strlen("endif")) ||
3100 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3101 !strncmp(startBuf, "include", strlen("include")) ||
3102 !strncmp(startBuf, "import", strlen("import")) ||
3103 !strncmp(startBuf, "include_next", strlen("include_next")))
3104 return true;
3105 }
3106 startBuf++;
3107 }
3108 return false;
3109}
3110
Fariborz Jahanian58457172011-12-05 18:43:13 +00003111/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003112/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003113void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003114 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003115 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003116 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003117 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003118 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003119 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003120 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003121 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003122 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003123 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003124 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Steve Narofffea763e82007-11-14 19:25:57 +00003126 const char *startBuf = SM->getCharacterData(LocStart);
3127 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003129 // If no ivars and no root or if its root, directly or indirectly,
3130 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003131 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003132 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003133 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003134 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003135 return;
3136 }
Mike Stump1eb44332009-09-09 15:08:12 +00003137
3138 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003139 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003140 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003141 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003142 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003143 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003144
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003145 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003146 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003147 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003148 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003149 // If the buffer contains preprocessor directives, we do more fine-grained
3150 // rewrites. This is intended to fix code that looks like (which occurs in
3151 // NSURL.h, for example):
3152 //
3153 // #ifdef XYZ
3154 // @interface Foo : NSObject
3155 // #else
3156 // @interface FooBar : NSObject
3157 // #endif
3158 // {
3159 // int i;
3160 // }
3161 // @end
3162 //
3163 // This clause is segregated to avoid breaking the common case.
3164 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003165 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003166 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003167 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003168 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003169
Chris Lattnercafeb352009-02-20 18:18:36 +00003170 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003171 // advance to the end of the referenced protocols.
3172 while (endHeader < cursor && *endHeader != '>') endHeader++;
3173 endHeader++;
3174 }
3175 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003176 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003177 } else {
3178 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003179 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003180 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003181 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003182 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003183 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003184 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003185 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003186 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003187
Steve Narofffea763e82007-11-14 19:25:57 +00003188 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003189 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003190 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003191 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003192 }
3193 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Steve Narofffea763e82007-11-14 19:25:57 +00003195 // Now comment out any visibility specifiers.
3196 while (cursor < endBuf) {
3197 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003198 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003199 // Skip whitespace.
3200 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3201 /*scan*/;
3202
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003203 // FIXME: presence of @public, etc. inside comment results in
3204 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003205 if (!strncmp(cursor, "public", strlen("public")) ||
3206 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003207 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003208 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003209 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003210 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003211 // FIXME: If there are cases where '<' is used in ivar declaration part
3212 // of user code, then scan the ivar list and use needToScanForQualifiers
3213 // for type checking.
3214 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003215 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003216 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003217 cursor = strchr(cursor, '>');
3218 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003219 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003220 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003221 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003222 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003223 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003224 }
Steve Narofffea763e82007-11-14 19:25:57 +00003225 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003226 }
Steve Narofffea763e82007-11-14 19:25:57 +00003227 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003228 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003229 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003230 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003231 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003232 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003233 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003235 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003236 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003237 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003238 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003239 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003240 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003241}
3242
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003243//===----------------------------------------------------------------------===//
3244// Meta Data Emission
3245//===----------------------------------------------------------------------===//
3246
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003247
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003248/// RewriteImplementations - This routine rewrites all method implementations
3249/// and emits meta-data.
3250
Steve Narofface66252008-11-13 20:07:04 +00003251void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003252 int ClsDefCount = ClassImplementation.size();
3253 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003255 // Rewrite implemented methods
3256 for (int i = 0; i < ClsDefCount; i++)
3257 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003259 for (int i = 0; i < CatDefCount; i++)
3260 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003261}
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003263void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3264 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003265 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003266 assert(BlockByRefDeclNo.count(VD) &&
3267 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003268 if (def)
3269 ResultStr += "struct ";
3270 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003271 "_" + utostr(BlockByRefDeclNo[VD]) ;
3272}
3273
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003274static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3275 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3276 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3277 return false;
3278}
3279
Steve Naroff54055232008-10-27 17:20:55 +00003280std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003281 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003282 std::string Tag) {
3283 const FunctionType *AFT = CE->getFunctionType();
Stephen Hines651f13c2014-04-23 16:59:28 -07003284 QualType RT = AFT->getReturnType();
Steve Naroff54055232008-10-27 17:20:55 +00003285 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003286 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003287 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003288
Steve Naroff54055232008-10-27 17:20:55 +00003289 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003290
Douglas Gregor72564e72009-02-26 23:50:07 +00003291 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003292 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003293 // block (to reference imported block decl refs).
3294 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003295 } else if (BD->param_empty()) {
3296 S += "(" + StructRef + " *__cself)";
3297 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003298 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003299 assert(FT && "SynthesizeBlockFunc: No function proto");
3300 S += '(';
3301 // first add the implicit argument.
3302 S += StructRef + " *__cself, ";
3303 std::string ParamStr;
3304 for (BlockDecl::param_iterator AI = BD->param_begin(),
3305 E = BD->param_end(); AI != E; ++AI) {
3306 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003307 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003308 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003309 (void)convertBlockPointerToFunctionPointer(QT);
3310 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003311 S += ParamStr;
3312 }
3313 if (FT->isVariadic()) {
3314 if (!BD->param_empty()) S += ", ";
3315 S += "...";
3316 }
3317 S += ')';
3318 }
3319 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Steve Naroff54055232008-10-27 17:20:55 +00003321 // Create local declarations to avoid rewriting all closure decl ref exprs.
3322 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00003323 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003324 E = BlockByRefDecls.end(); I != E; ++I) {
3325 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003326 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003327 std::string TypeString;
3328 RewriteByRefString(TypeString, Name, (*I));
3329 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003330 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003331 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003332 }
Steve Naroff54055232008-10-27 17:20:55 +00003333 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003334 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003335 E = BlockByCopyDecls.end(); I != E; ++I) {
3336 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003337 // Handle nested closure invocation. For example:
3338 //
3339 // void (^myImportedClosure)(void);
3340 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003341 //
Steve Naroff54055232008-10-27 17:20:55 +00003342 // void (^anotherClosure)(void);
3343 // anotherClosure = ^(void) {
3344 // myImportedClosure(); // import and invoke the closure
3345 // };
3346 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003347 if (isTopLevelBlockPointerType((*I)->getType())) {
3348 RewriteBlockPointerTypeVariable(S, (*I));
3349 S += " = (";
3350 RewriteBlockPointerType(S, (*I)->getType());
3351 S += ")";
3352 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3353 }
3354 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003355 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003356 QualType QT = (*I)->getType();
3357 if (HasLocalVariableExternalStorage(*I))
3358 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003359 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003360 S += Name + " = __cself->" +
3361 (*I)->getNameAsString() + "; // bound by copy\n";
3362 }
Steve Naroff54055232008-10-27 17:20:55 +00003363 }
3364 std::string RewrittenStr = RewrittenBlockExprs[CE];
3365 const char *cstr = RewrittenStr.c_str();
3366 while (*cstr++ != '{') ;
3367 S += cstr;
3368 S += "\n";
3369 return S;
3370}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003371
Steve Naroff54055232008-10-27 17:20:55 +00003372std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003373 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003374 std::string Tag) {
3375 std::string StructRef = "struct " + Tag;
3376 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003377
Steve Naroff54055232008-10-27 17:20:55 +00003378 S += funcName;
3379 S += "_block_copy_" + utostr(i);
3380 S += "(" + StructRef;
3381 S += "*dst, " + StructRef;
3382 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003383 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003384 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003385 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003386 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003387 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003388 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003390 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003391 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003392 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003393 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003394 else
3395 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003396 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003397 S += "}\n";
3398
Steve Naroff54055232008-10-27 17:20:55 +00003399 S += "\nstatic void __";
3400 S += funcName;
3401 S += "_block_dispose_" + utostr(i);
3402 S += "(" + StructRef;
3403 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003404 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003405 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003406 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003407 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003408 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003409 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003410 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003411 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003412 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003413 else
3414 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003415 }
Mike Stump1eb44332009-09-09 15:08:12 +00003416 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003417 return S;
3418}
3419
Steve Naroff01aec112009-12-06 21:14:13 +00003420std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3421 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003422 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003423 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Steve Naroff54055232008-10-27 17:20:55 +00003425 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003426 S += " struct " + Desc;
3427 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Steve Naroff01aec112009-12-06 21:14:13 +00003429 Constructor += "(void *fp, "; // Invoke function pointer.
3430 Constructor += "struct " + Desc; // Descriptor pointer.
3431 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Steve Naroff54055232008-10-27 17:20:55 +00003433 if (BlockDeclRefs.size()) {
3434 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003435 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003436 E = BlockByCopyDecls.end(); I != E; ++I) {
3437 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003438 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003439 std::string ArgName = "_" + FieldName;
3440 // Handle nested closure invocation. For example:
3441 //
3442 // void (^myImportedBlock)(void);
3443 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003444 //
Steve Naroff54055232008-10-27 17:20:55 +00003445 // void (^anotherBlock)(void);
3446 // anotherBlock = ^(void) {
3447 // myImportedBlock(); // import and invoke the closure
3448 // };
3449 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003450 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003451 S += "struct __block_impl *";
3452 Constructor += ", void *" + ArgName;
3453 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003454 QualType QT = (*I)->getType();
3455 if (HasLocalVariableExternalStorage(*I))
3456 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003457 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3458 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003459 Constructor += ", " + ArgName;
3460 }
3461 S += FieldName + ";\n";
3462 }
3463 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00003464 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003465 E = BlockByRefDecls.end(); I != E; ++I) {
3466 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003467 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003468 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003469 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003470 std::string TypeString;
3471 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003472 TypeString += " *";
3473 FieldName = TypeString + FieldName;
3474 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003475 Constructor += ", " + ArgName;
3476 }
3477 S += FieldName + "; // by ref\n";
3478 }
3479 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003480 Constructor += ", int flags=0)";
3481 // Initialize all "by copy" arguments.
3482 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00003483 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003484 E = BlockByCopyDecls.end(); I != E; ++I) {
3485 std::string Name = (*I)->getNameAsString();
3486 if (firsTime) {
3487 Constructor += " : ";
3488 firsTime = false;
3489 }
3490 else
3491 Constructor += ", ";
3492 if (isTopLevelBlockPointerType((*I)->getType()))
3493 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3494 else
3495 Constructor += Name + "(_" + Name + ")";
3496 }
3497 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00003498 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003499 E = BlockByRefDecls.end(); I != E; ++I) {
3500 std::string Name = (*I)->getNameAsString();
3501 if (firsTime) {
3502 Constructor += " : ";
3503 firsTime = false;
3504 }
3505 else
3506 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003507 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003508 }
3509
3510 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003511 if (GlobalVarDecl)
3512 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3513 else
3514 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003515 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003516
Steve Naroff01aec112009-12-06 21:14:13 +00003517 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003518 } else {
3519 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003520 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003521 if (GlobalVarDecl)
3522 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3523 else
3524 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003525 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3526 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003527 }
3528 Constructor += " ";
3529 Constructor += "}\n";
3530 S += Constructor;
3531 S += "};\n";
3532 return S;
3533}
3534
Steve Naroff01aec112009-12-06 21:14:13 +00003535std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3536 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003537 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003538 unsigned hasCopy) {
3539 std::string S = "\nstatic struct " + DescTag;
3540
3541 S += " {\n unsigned long reserved;\n";
3542 S += " unsigned long Block_size;\n";
3543 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003544 S += " void (*copy)(struct ";
3545 S += ImplTag; S += "*, struct ";
3546 S += ImplTag; S += "*);\n";
3547
3548 S += " void (*dispose)(struct ";
3549 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003550 }
3551 S += "} ";
3552
3553 S += DescTag + "_DATA = { 0, sizeof(struct ";
3554 S += ImplTag + ")";
3555 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003556 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3557 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003558 }
3559 S += "};\n";
3560 return S;
3561}
3562
Steve Naroff54055232008-10-27 17:20:55 +00003563void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003564 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003565 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003566 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003567 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003568 bool RewriteSC = (GlobalVarDecl &&
3569 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003570 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003571 GlobalVarDecl->getType().getCVRQualifiers());
3572 if (RewriteSC) {
3573 std::string SC(" void __");
3574 SC += GlobalVarDecl->getNameAsString();
3575 SC += "() {}";
3576 InsertText(FunLocStart, SC);
3577 }
3578
Steve Naroff54055232008-10-27 17:20:55 +00003579 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003580 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3581 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003582 // Need to copy-in the inner copied-in variables not actually used in this
3583 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003584 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003585 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003586 ValueDecl *VD = Exp->getDecl();
3587 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003588 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003589 BlockByCopyDeclsPtrSet.insert(VD);
3590 BlockByCopyDecls.push_back(VD);
3591 }
John McCallf4b88a42012-03-10 09:33:50 +00003592 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003593 BlockByRefDeclsPtrSet.insert(VD);
3594 BlockByRefDecls.push_back(VD);
3595 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003596 // imported objects in the inner blocks not used in the outer
3597 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003598 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003599 VD->getType()->isObjCObjectPointerType() ||
3600 VD->getType()->isBlockPointerType())
3601 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003602 }
Steve Naroff54055232008-10-27 17:20:55 +00003603
Daniel Dunbar4087f272010-08-17 22:39:59 +00003604 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3605 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003606
Steve Naroff01aec112009-12-06 21:14:13 +00003607 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003608
Benjamin Kramerd999b372010-02-14 14:14:16 +00003609 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003610
Steve Naroff01aec112009-12-06 21:14:13 +00003611 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Benjamin Kramerd999b372010-02-14 14:14:16 +00003613 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003614
3615 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003616 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003617 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003618 }
Steve Naroff01aec112009-12-06 21:14:13 +00003619 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3620 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003621 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Steve Naroff54055232008-10-27 17:20:55 +00003623 BlockDeclRefs.clear();
3624 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003625 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003626 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003627 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003628 ImportedBlockDecls.clear();
3629 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003630 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003631 // Must insert any 'const/volatile/static here. Since it has been
3632 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003633 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003634 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003635 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003636 if (GlobalVarDecl->getType().isConstQualified())
3637 SC += "const ";
3638 if (GlobalVarDecl->getType().isVolatileQualified())
3639 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003640 if (GlobalVarDecl->getType().isRestrictQualified())
3641 SC += "restrict ";
3642 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003643 }
3644
Steve Naroff54055232008-10-27 17:20:55 +00003645 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003646 InnerDeclRefsCount.clear();
3647 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003648 RewrittenBlockExprs.clear();
3649}
3650
3651void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3652 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003653 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Steve Naroff54055232008-10-27 17:20:55 +00003655 SynthesizeBlockLiterals(FunLocStart, FuncName);
3656}
3657
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003658static void BuildUniqueMethodName(std::string &Name,
3659 ObjCMethodDecl *MD) {
3660 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003661 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003662 Name += "__" + MD->getSelector().getAsString();
3663 // Convert colons to underscores.
3664 std::string::size_type loc = 0;
3665 while ((loc = Name.find(":", loc)) != std::string::npos)
3666 Name.replace(loc, 1, "_");
3667}
3668
Steve Naroff54055232008-10-27 17:20:55 +00003669void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003670 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3671 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003672 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003673 std::string FuncName;
3674 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003675 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003676}
3677
3678void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003679 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003680 if (*CI) {
3681 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3682 GetBlockDeclRefExprs(CBE->getBody());
3683 else
3684 GetBlockDeclRefExprs(*CI);
3685 }
3686 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003687 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3688 if (DRE->refersToEnclosingLocal()) {
3689 // FIXME: Handle enums.
3690 if (!isa<FunctionDecl>(DRE->getDecl()))
3691 BlockDeclRefs.push_back(DRE);
3692 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3693 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003694 }
John McCallf4b88a42012-03-10 09:33:50 +00003695 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003696
Steve Naroff54055232008-10-27 17:20:55 +00003697 return;
3698}
3699
Craig Topper6b9240e2013-07-05 19:34:19 +00003700void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3701 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003702 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003703 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003704 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003705 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3706 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003707 GetInnerBlockDeclRefExprs(CBE->getBody(),
3708 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003709 InnerContexts);
3710 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003711 else
3712 GetInnerBlockDeclRefExprs(*CI,
3713 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003714 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003715
3716 }
3717 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003718 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3719 if (DRE->refersToEnclosingLocal()) {
3720 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3721 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3722 InnerBlockDeclRefs.push_back(DRE);
3723 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3724 if (Var->isFunctionOrMethodVarDecl())
3725 ImportedLocalExternalDecls.insert(Var);
3726 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003727 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003728
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003729 return;
3730}
3731
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003732/// convertFunctionTypeOfBlocks - This routine converts a function type
3733/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003734/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003735/// all block pointers to function pointers.
3736QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3737 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3738 // FTP will be null for closures that don't take arguments.
3739 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003740 SmallVector<QualType, 8> ArgTypes;
Stephen Hines651f13c2014-04-23 16:59:28 -07003741 QualType Res = FT->getReturnType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003742 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003743
3744 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003745 for (auto &I : FTP->param_types()) {
3746 QualType t = I;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003747 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003748 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003749 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003750 ArgTypes.push_back(t);
3751 }
3752 }
3753 QualType FuncType;
3754 // FIXME. Does this work if block takes no argument but has a return type
3755 // which is of block type?
3756 if (HasBlockType)
Jordan Rosebea522f2013-03-08 21:51:21 +00003757 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003758 else FuncType = QualType(FT, 0);
3759 return FuncType;
3760}
3761
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003762Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003763 // Navigate to relevant type information.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003764 const BlockPointerType *CPT = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00003765
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003766 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003768 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003769 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003770 }
3771 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3772 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3773 }
3774 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3775 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3776 else if (const ConditionalOperator *CEXPR =
3777 dyn_cast<ConditionalOperator>(BlockExp)) {
3778 Expr *LHSExp = CEXPR->getLHS();
3779 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3780 Expr *RHSExp = CEXPR->getRHS();
3781 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3782 Expr *CONDExp = CEXPR->getCond();
3783 ConditionalOperator *CondExpr =
3784 new (Context) ConditionalOperator(CONDExp,
3785 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003786 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003787 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003788 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003789 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3790 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003791 } else if (const PseudoObjectExpr *POE
3792 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3793 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003794 } else {
3795 assert(1 && "RewriteBlockClass: Bad type");
3796 }
3797 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003798 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003799 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003800 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003801 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003803 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003804 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003805 &Context->Idents.get("__block_impl"));
3806 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003807
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003808 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003809 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003810
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003811 // Push the block argument type.
3812 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003813 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003814 for (auto &I : FTP->param_types()) {
3815 QualType t = I;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003816 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003817 if (!convertBlockPointerToFunctionPointer(t))
3818 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003819 ArgTypes.push_back(t);
3820 }
Steve Naroff54055232008-10-27 17:20:55 +00003821 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003822 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003823 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003825 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003826
John McCall9d125032010-01-15 18:39:57 +00003827 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003828 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003829 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003831 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3832 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003833 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003835 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003836 SourceLocation(),
3837 &Context->Idents.get("FuncPtr"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003838 Context->VoidPtrTy, nullptr,
3839 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003840 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003841 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003842 FD->getType(), VK_LValue,
3843 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003845
John McCall9d125032010-01-15 18:39:57 +00003846 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003847 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003848 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Chris Lattner5f9e2722011-07-23 10:55:15 +00003850 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003851 // Add the implicit argument.
3852 BlkExprs.push_back(BlkCast);
3853 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003854 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003855 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003856 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003857 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003858 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
John McCallf89e55a2010-11-18 06:31:45 +00003859 Exp->getType(), VK_RValue,
3860 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003861 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003862}
3863
Steve Naroff621edce2009-04-29 16:37:50 +00003864// We need to return the rewritten expression to handle cases where the
3865// BlockDeclRefExpr is embedded in another expression being rewritten.
3866// For example:
3867//
3868// int main() {
3869// __block Foo *f;
3870// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003871//
Steve Naroff621edce2009-04-29 16:37:50 +00003872// void (^myblock)() = ^() {
3873// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3874// i = 77;
3875// };
3876//}
John McCallf4b88a42012-03-10 09:33:50 +00003877Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003878 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003879 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003880 ValueDecl *VD = DeclRefExp->getDecl();
3881 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003882
3883 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003884 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003885 &Context->Idents.get("__forwarding"),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003886 Context->VoidPtrTy, nullptr,
3887 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003888 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003889 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3890 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003891 FD->getType(), VK_LValue,
3892 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003893
Chris Lattner5f9e2722011-07-23 10:55:15 +00003894 StringRef Name = VD->getName();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003895 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003896 &Context->Idents.get(Name),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003897 Context->VoidPtrTy, nullptr,
3898 /*BitWidth=*/nullptr, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003899 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003900 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003901 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003902
3903
3904
Steve Naroffdf8570d2009-02-02 17:19:26 +00003905 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003906 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3907 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003908 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003909 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003910 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003911}
3912
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003913// Rewrites the imported local variable V with external storage
3914// (static, extern, etc.) as *V
3915//
3916Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3917 ValueDecl *VD = DRE->getDecl();
3918 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3919 if (!ImportedLocalExternalDecls.count(Var))
3920 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003921 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3922 VK_LValue, OK_Ordinary,
3923 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003924 // Need parens to enforce precedence.
3925 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3926 Exp);
3927 ReplaceStmt(DRE, PE);
3928 return PE;
3929}
3930
Steve Naroffb2f9e512008-11-03 23:29:32 +00003931void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3932 SourceLocation LocStart = CE->getLParenLoc();
3933 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003934
3935 // Need to avoid trying to rewrite synthesized casts.
3936 if (LocStart.isInvalid())
3937 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003938 // Need to avoid trying to rewrite casts contained in macros.
3939 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3940 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003941
Steve Naroff54055232008-10-27 17:20:55 +00003942 const char *startBuf = SM->getCharacterData(LocStart);
3943 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003944 QualType QT = CE->getType();
3945 const Type* TypePtr = QT->getAs<Type>();
3946 if (isa<TypeOfExprType>(TypePtr)) {
3947 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3948 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3949 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003950 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003951 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003952 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003953 return;
3954 }
Steve Naroff54055232008-10-27 17:20:55 +00003955 // advance the location to startArgList.
3956 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Steve Naroff54055232008-10-27 17:20:55 +00003958 while (*argPtr++ && (argPtr < endBuf)) {
3959 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003960 case '^':
3961 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003962 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003963 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003964 break;
Steve Naroff54055232008-10-27 17:20:55 +00003965 }
3966 }
3967 return;
3968}
3969
3970void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3971 SourceLocation DeclLoc = FD->getLocation();
3972 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003973
Steve Naroff54055232008-10-27 17:20:55 +00003974 // We have 1 or more arguments that have closure pointers.
3975 const char *startBuf = SM->getCharacterData(DeclLoc);
3976 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Steve Naroff54055232008-10-27 17:20:55 +00003978 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00003979
Steve Naroff54055232008-10-27 17:20:55 +00003980 parenCount++;
3981 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003982 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00003983 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Steve Naroff54055232008-10-27 17:20:55 +00003985 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00003986
Steve Naroff54055232008-10-27 17:20:55 +00003987 while (*argPtr++ && parenCount) {
3988 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003989 case '^':
3990 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003991 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003992 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003993 break;
3994 case '(':
3995 parenCount++;
3996 break;
3997 case ')':
3998 parenCount--;
3999 break;
Steve Naroff54055232008-10-27 17:20:55 +00004000 }
4001 }
4002 return;
4003}
4004
4005bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004006 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004007 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004008 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004009 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004010 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004011 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004012 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004013 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004014 }
4015 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004016 for (const auto &I : FTP->param_types())
4017 if (isTopLevelBlockPointerType(I))
Steve Naroff54055232008-10-27 17:20:55 +00004018 return true;
4019 }
4020 return false;
4021}
4022
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004023bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4024 const FunctionProtoType *FTP;
4025 const PointerType *PT = QT->getAs<PointerType>();
4026 if (PT) {
4027 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4028 } else {
4029 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4030 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4031 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4032 }
4033 if (FTP) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004034 for (const auto &I : FTP->param_types()) {
4035 if (I->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004036 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07004037 if (I->isObjCObjectPointerType() &&
4038 I->getPointeeType()->isObjCQualifiedInterfaceType())
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004039 return true;
4040 }
4041
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004042 }
4043 return false;
4044}
4045
Ted Kremenek8189cde2009-02-07 01:47:29 +00004046void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4047 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004048 const char *argPtr = strchr(Name, '(');
4049 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Steve Naroff54055232008-10-27 17:20:55 +00004051 LParen = argPtr; // output the start.
4052 argPtr++; // skip past the left paren.
4053 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004054
Steve Naroff54055232008-10-27 17:20:55 +00004055 while (*argPtr && parenCount) {
4056 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004057 case '(': parenCount++; break;
4058 case ')': parenCount--; break;
4059 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004060 }
4061 if (parenCount) argPtr++;
4062 }
4063 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4064 RParen = argPtr; // output the end
4065}
4066
4067void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4068 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4069 RewriteBlockPointerFunctionArgs(FD);
4070 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004071 }
Steve Naroff54055232008-10-27 17:20:55 +00004072 // Handle Variables and Typedefs.
4073 SourceLocation DeclLoc = ND->getLocation();
4074 QualType DeclT;
4075 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4076 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004077 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004078 DeclT = TDD->getUnderlyingType();
4079 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4080 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004081 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004082 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Steve Naroff54055232008-10-27 17:20:55 +00004084 const char *startBuf = SM->getCharacterData(DeclLoc);
4085 const char *endBuf = startBuf;
4086 // scan backward (from the decl location) for the end of the previous decl.
4087 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4088 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004089 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004090 std::string buf;
4091 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004092 // *startBuf != '^' if we are dealing with a pointer to function that
4093 // may take block argument types (which will be handled below).
4094 if (*startBuf == '^') {
4095 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004096 buf = '*';
4097 startBuf++;
4098 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004099 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004100 while (*startBuf != ')') {
4101 buf += *startBuf;
4102 startBuf++;
4103 OrigLength++;
4104 }
4105 buf += ')';
4106 OrigLength++;
4107
4108 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4109 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004110 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004111 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004112 DeclLoc = ND->getLocation();
4113 startBuf = SM->getCharacterData(DeclLoc);
4114 const char *argListBegin, *argListEnd;
4115 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4116 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004117 if (*argListBegin == '^')
4118 buf += '*';
4119 else if (*argListBegin == '<') {
4120 buf += "/*";
4121 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004122 OrigLength++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004123 while (*argListBegin != '>') {
4124 buf += *argListBegin++;
4125 OrigLength++;
4126 }
4127 buf += *argListBegin;
4128 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004129 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004130 else
4131 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004132 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004133 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004134 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004135 buf += ')';
4136 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004137 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004138 ReplaceText(Start, OrigLength, buf);
4139
Steve Naroff54055232008-10-27 17:20:55 +00004140 return;
4141}
4142
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004143
4144/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4145/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4146/// struct Block_byref_id_object *src) {
4147/// _Block_object_assign (&_dest->object, _src->object,
4148/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4149/// [|BLOCK_FIELD_IS_WEAK]) // object
4150/// _Block_object_assign(&_dest->object, _src->object,
4151/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4152/// [|BLOCK_FIELD_IS_WEAK]) // block
4153/// }
4154/// And:
4155/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4156/// _Block_object_dispose(_src->object,
4157/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4158/// [|BLOCK_FIELD_IS_WEAK]) // object
4159/// _Block_object_dispose(_src->object,
4160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4161/// [|BLOCK_FIELD_IS_WEAK]) // block
4162/// }
4163
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004164std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4165 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004166 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004167 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004168 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004169 CopyDestroyCache.insert(flag);
4170 S = "static void __Block_byref_id_object_copy_";
4171 S += utostr(flag);
4172 S += "(void *dst, void *src) {\n";
4173
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004174 // offset into the object pointer is computed as:
4175 // void * + void* + int + int + void* + void *
4176 unsigned IntSize =
4177 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4178 unsigned VoidPtrSize =
4179 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4180
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004181 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004182 S += " _Block_object_assign((char*)dst + ";
4183 S += utostr(offset);
4184 S += ", *(void * *) ((char*)src + ";
4185 S += utostr(offset);
4186 S += "), ";
4187 S += utostr(flag);
4188 S += ");\n}\n";
4189
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004190 S += "static void __Block_byref_id_object_dispose_";
4191 S += utostr(flag);
4192 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004193 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4194 S += utostr(offset);
4195 S += "), ";
4196 S += utostr(flag);
4197 S += ");\n}\n";
4198 return S;
4199}
4200
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004201/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4202/// the declaration into:
4203/// struct __Block_byref_ND {
4204/// void *__isa; // NULL for everything except __weak pointers
4205/// struct __Block_byref_ND *__forwarding;
4206/// int32_t __flags;
4207/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004208/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4209/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004210/// typex ND;
4211/// };
4212///
4213/// It then replaces declaration of ND variable with:
4214/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4215/// __size=sizeof(struct __Block_byref_ND),
4216/// ND=initializer-if-any};
4217///
4218///
4219void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004220 // Insert declaration for the function in which block literal is
4221 // used.
4222 if (CurFunctionDeclToDeclareForBlock)
4223 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004224 int flag = 0;
4225 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004226 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004227 if (DeclLoc.isInvalid())
4228 // If type location is missing, it is because of missing type (a warning).
4229 // Use variable's location which is good for this case.
4230 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004231 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004232 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004233 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004234 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004235 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004236 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004237 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004238 ByrefType += " {\n";
4239 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004240 RewriteByRefString(ByrefType, Name, ND);
4241 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004242 ByrefType += " int __flags;\n";
4243 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004244 // Add void *__Block_byref_id_object_copy;
4245 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004246 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00004247 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004248 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004249 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4250 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004251 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004252
4253 QualType T = Ty;
4254 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004255 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004256
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004257 ByrefType += " " + Name + ";\n";
4258 ByrefType += "};\n";
4259 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004260 SourceLocation FunLocStart;
4261 if (CurFunctionDef)
4262 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4263 else {
4264 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4265 FunLocStart = CurMethodDef->getLocStart();
4266 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004267 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004268 if (Ty.isObjCGCWeak()) {
4269 flag |= BLOCK_FIELD_IS_WEAK;
4270 isa = 1;
4271 }
4272
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004273 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004274 flag = BLOCK_BYREF_CALLER;
4275 QualType Ty = ND->getType();
4276 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4277 if (Ty->isBlockPointerType())
4278 flag |= BLOCK_FIELD_IS_BLOCK;
4279 else
4280 flag |= BLOCK_FIELD_IS_OBJECT;
4281 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004282 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004283 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004284 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004285
4286 // struct __Block_byref_ND ND =
4287 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4288 // initializer-if-any};
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004289 bool hasInit = (ND->getInit() != nullptr);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004290 unsigned flags = 0;
4291 if (HasCopyAndDispose)
4292 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004293 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004294 ByrefType.clear();
4295 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004296 std::string ForwardingCastType("(");
4297 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004298 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004299 ByrefType += " " + Name + " = {(void*)";
4300 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004301 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004302 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004303 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004304 ByrefType += "sizeof(";
4305 RewriteByRefString(ByrefType, Name, ND);
4306 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004307 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004308 ByrefType += ", __Block_byref_id_object_copy_";
4309 ByrefType += utostr(flag);
4310 ByrefType += ", __Block_byref_id_object_dispose_";
4311 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004312 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004313 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004314 unsigned nameSize = Name.size();
4315 // for block or function pointer declaration. Name is aleady
4316 // part of the declaration.
4317 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4318 nameSize = 1;
4319 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004320 }
4321 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004322 SourceLocation startLoc;
4323 Expr *E = ND->getInit();
4324 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4325 startLoc = ECE->getLParenLoc();
4326 else
4327 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004328 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004329 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004330 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004331 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004332 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004333 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004334 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004335 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004336 ByrefType += "sizeof(";
4337 RewriteByRefString(ByrefType, Name, ND);
4338 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004339 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004340 ByrefType += "__Block_byref_id_object_copy_";
4341 ByrefType += utostr(flag);
4342 ByrefType += ", __Block_byref_id_object_dispose_";
4343 ByrefType += utostr(flag);
4344 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004345 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004346 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004347
4348 // Complete the newly synthesized compound expression by inserting a right
4349 // curly brace before the end of the declaration.
4350 // FIXME: This approach avoids rewriting the initializer expression. It
4351 // also assumes there is only one declarator. For example, the following
4352 // isn't currently supported by this routine (in general):
4353 //
4354 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4355 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004356 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4357 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004358 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4359 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004360 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004361
Benjamin Kramerd999b372010-02-14 14:14:16 +00004362 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004363 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004364 return;
4365}
4366
Mike Stump1eb44332009-09-09 15:08:12 +00004367void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004368 // Add initializers for any closure decl refs.
4369 GetBlockDeclRefExprs(Exp->getBody());
4370 if (BlockDeclRefs.size()) {
4371 // Unique all "by copy" declarations.
4372 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004373 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004374 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4375 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4376 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4377 }
4378 }
Steve Naroff54055232008-10-27 17:20:55 +00004379 // Unique all "by ref" declarations.
4380 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004381 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004382 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4383 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4384 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4385 }
Steve Naroff54055232008-10-27 17:20:55 +00004386 }
4387 // Find any imported blocks...they will need special attention.
4388 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004389 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004390 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004391 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004392 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004393 }
4394}
4395
Chris Lattner5f9e2722011-07-23 10:55:15 +00004396FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004397 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004398 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004399 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004400 SourceLocation(), ID, FType, nullptr, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004401 false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004402}
4403
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004404Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00004405 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004406 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004407 Blocks.push_back(Exp);
4408
4409 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004410
4411 // Add inner imported variables now used in current block.
4412 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004413 if (!InnerBlockDeclRefs.empty()) {
4414 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004415 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004416 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004417 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004418 // We need to save the copied-in variables in nested
4419 // blocks because it is needed at the end for some of the API generations.
4420 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004421 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4422 BlockDeclRefs.push_back(Exp);
4423 BlockByCopyDeclsPtrSet.insert(VD);
4424 BlockByCopyDecls.push_back(VD);
4425 }
John McCallf4b88a42012-03-10 09:33:50 +00004426 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004427 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4428 BlockDeclRefs.push_back(Exp);
4429 BlockByRefDeclsPtrSet.insert(VD);
4430 BlockByRefDecls.push_back(VD);
4431 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004432 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004433 // Find any imported blocks...they will need special attention.
4434 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004435 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004436 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4437 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4438 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004439 }
4440 InnerDeclRefsCount.push_back(countOfInnerDecls);
4441
Steve Narofffa15fd92008-10-28 20:29:00 +00004442 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004443
Steve Narofffa15fd92008-10-28 20:29:00 +00004444 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004445 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004446 else if (CurMethodDef)
4447 BuildUniqueMethodName(FuncName, CurMethodDef);
4448 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004449 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Steve Narofffa15fd92008-10-28 20:29:00 +00004451 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004452
Steve Narofffa15fd92008-10-28 20:29:00 +00004453 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4454 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Steve Narofffa15fd92008-10-28 20:29:00 +00004456 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004457 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4458 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004459
4460 FunctionDecl *FD;
4461 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004462
Benjamin Kramere5753592013-09-09 14:48:42 +00004463 // Simulate a constructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004464 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004465 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004466 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004467
Chris Lattner5f9e2722011-07-23 10:55:15 +00004468 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004469
Steve Narofffdc03722008-10-29 21:23:59 +00004470 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004471 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004472 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4473 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004474 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004475 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004476 InitExprs.push_back(castExpr);
4477
Steve Naroff01aec112009-12-06 21:14:13 +00004478 // Initialize the block descriptor.
4479 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004481 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4482 SourceLocation(), SourceLocation(),
4483 &Context->Idents.get(DescData.c_str()),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004484 Context->VoidPtrTy, nullptr,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00004485 SC_Static);
John McCallf89e55a2010-11-18 06:31:45 +00004486 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004487 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004488 Context->VoidPtrTy,
4489 VK_LValue,
4490 SourceLocation()),
4491 UO_AddrOf,
4492 Context->getPointerType(Context->VoidPtrTy),
4493 VK_RValue, OK_Ordinary,
4494 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004495 InitExprs.push_back(DescRefExpr);
4496
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 // Add initializers for any closure decl refs.
4498 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004499 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004500 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004501 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004502 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004503 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004504 // FIXME: Conform to ABI ([[obj retain] autorelease]).
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 Jahaniana5a79872010-05-24 18:32:56 +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 Jahaniana5a79872010-05-24 18:32:56 +00004513 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004514 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004515 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004516 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004517 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004518 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004519 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004521 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004522 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004523 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004524 if (HasLocalVariableExternalStorage(*I)) {
4525 QualType QT = (*I)->getType();
4526 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004527 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4528 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004529 }
4530
Steve Narofffa15fd92008-10-28 20:29:00 +00004531 }
Mike Stump1eb44332009-09-09 15:08:12 +00004532 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004533 }
4534 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004535 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004536 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004537 ValueDecl *ND = (*I);
4538 std::string Name(ND->getNameAsString());
4539 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004540 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004541 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4542 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004543 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004544 SourceLocation(), SourceLocation(),
4545 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004546 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4547 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4548
Daniel Dunbar4087f272010-08-17 22:39:59 +00004549 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004550 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004551 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004552 bool isNestedCapturedVar = false;
4553 if (block)
Stephen Hines651f13c2014-04-23 16:59:28 -07004554 for (const auto &CI : block->captures()) {
4555 const VarDecl *variable = CI.getVariable();
4556 if (variable == ND && CI.isNested()) {
4557 assert (CI.isByRef() &&
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004558 "SynthBlockInitExpr - captured block variable is not byref");
4559 isNestedCapturedVar = true;
4560 break;
4561 }
4562 }
4563 // captured nested byref variable has its address passed. Do not take
4564 // its address again.
4565 if (!isNestedCapturedVar)
4566 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004567 Context->getPointerType(Exp->getType()),
4568 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004569 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004570 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004571 }
4572 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004573 if (ImportedBlockDecls.size()) {
4574 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4575 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004576 unsigned IntSize =
4577 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004578 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4579 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004580 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004581 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004582 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
John McCallf89e55a2010-11-18 06:31:45 +00004583 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004584 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004585 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004586 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004587 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004588 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004589 BlockDeclRefs.clear();
4590 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004591 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004592 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004593 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004594 ImportedBlockDecls.clear();
4595 return NewRep;
4596}
4597
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004598bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4599 if (const ObjCForCollectionStmt * CS =
4600 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4601 return CS->getElement() == DS;
4602 return false;
4603}
4604
Steve Narofffa15fd92008-10-28 20:29:00 +00004605//===----------------------------------------------------------------------===//
4606// Function Body / Expression rewriting
4607//===----------------------------------------------------------------------===//
4608
4609Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004610 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004611 isa<DoStmt>(S) || isa<ForStmt>(S))
4612 Stmts.push_back(S);
4613 else if (isa<ObjCForCollectionStmt>(S)) {
4614 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004615 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004616 }
Mike Stump1eb44332009-09-09 15:08:12 +00004617
John McCall4b9c2d22011-11-06 09:01:30 +00004618 // Pseudo-object operations and ivar references need special
4619 // treatment because we're going to recursively rewrite them.
4620 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4621 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4622 return RewritePropertyOrImplicitSetter(PseudoOp);
4623 } else {
4624 return RewritePropertyOrImplicitGetter(PseudoOp);
4625 }
4626 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4627 return RewriteObjCIvarRefExpr(IvarRefExpr);
4628 }
4629
Steve Narofffa15fd92008-10-28 20:29:00 +00004630 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004631
Steve Narofffa15fd92008-10-28 20:29:00 +00004632 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004633 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004634 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004635 Stmt *childStmt = (*CI);
4636 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004637 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004638 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004639 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004640 }
Mike Stump1eb44332009-09-09 15:08:12 +00004641
Steve Narofffa15fd92008-10-28 20:29:00 +00004642 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004643 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004644 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4645 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004646 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004647 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004648 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004649 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004650 Stmt *SaveCurrentBody = CurrentBody;
4651 CurrentBody = BE->getBody();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004652 PropParentMap = nullptr;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004653 // block literal on rhs of a property-dot-sytax assignment
4654 // must be replaced by its synthesize ast so getRewrittenText
4655 // works as expected. In this case, what actually ends up on RHS
4656 // is the blockTranscribed which is the helper function for the
4657 // block literal; as in: self.c = ^() {[ace ARR];};
4658 bool saveDisableReplaceStmt = DisableReplaceStmt;
4659 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004660 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004661 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004662 CurrentBody = SaveCurrentBody;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004663 PropParentMap = nullptr;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004664 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004665 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004666 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004667 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004669 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4670
Steve Narofffa15fd92008-10-28 20:29:00 +00004671 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004672 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 return blockTranscribed;
4674 }
4675 // Handle specific things.
4676 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4677 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004678
Steve Narofffa15fd92008-10-28 20:29:00 +00004679 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4680 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004681
Steve Narofffa15fd92008-10-28 20:29:00 +00004682 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4683 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004684
Steve Narofffa15fd92008-10-28 20:29:00 +00004685 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004686#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004687 // Before we rewrite it, put the original message expression in a comment.
4688 SourceLocation startLoc = MessExpr->getLocStart();
4689 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004690
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 const char *startBuf = SM->getCharacterData(startLoc);
4692 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004693
Steve Narofffa15fd92008-10-28 20:29:00 +00004694 std::string messString;
4695 messString += "// ";
4696 messString.append(startBuf, endBuf-startBuf+1);
4697 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004698
4699 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004700 // InsertText(clang::SourceLocation, char const*, unsigned int).
4701 // InsertText(startLoc, messString.c_str(), messString.size());
4702 // Tried this, but it didn't work either...
4703 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004704#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004705 return RewriteMessageExpr(MessExpr);
4706 }
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Steve Narofffa15fd92008-10-28 20:29:00 +00004708 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4709 return RewriteObjCTryStmt(StmtTry);
4710
4711 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4712 return RewriteObjCSynchronizedStmt(StmtTry);
4713
4714 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4715 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Steve Narofffa15fd92008-10-28 20:29:00 +00004717 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4718 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004719
4720 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004721 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004722 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004723 OrigStmtRange.getEnd());
4724 if (BreakStmt *StmtBreakStmt =
4725 dyn_cast<BreakStmt>(S))
4726 return RewriteBreakStmt(StmtBreakStmt);
4727 if (ContinueStmt *StmtContinueStmt =
4728 dyn_cast<ContinueStmt>(S))
4729 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004730
4731 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004732 // and cast exprs.
4733 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4734 // FIXME: What we're doing here is modifying the type-specifier that
4735 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004736 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004737 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4738 // the context of an ObjCForCollectionStmt. For example:
4739 // NSArray *someArray;
4740 // for (id <FooProtocol> index in someArray) ;
4741 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4742 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004743 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004744 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Steve Narofffa15fd92008-10-28 20:29:00 +00004746 // Blocks rewrite rules.
Stephen Hines651f13c2014-04-23 16:59:28 -07004747 for (auto *SD : DS->decls()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004749 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004750 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004751 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004752 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004753 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004754 if (VD->hasAttr<BlocksAttr>()) {
4755 static unsigned uniqueByrefDeclCount = 0;
4756 assert(!BlockByRefDeclNo.count(ND) &&
4757 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4758 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004759 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004760 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004761 else
4762 RewriteTypeOfDecl(VD);
4763 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004764 }
Richard Smith162e1c12011-04-15 14:24:37 +00004765 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004766 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004767 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004768 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004769 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4770 }
4771 }
4772 }
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4775 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004776
4777 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4779 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004780 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4781 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004782 && "Statement stack mismatch");
4783 Stmts.pop_back();
4784 }
4785 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004786 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4787 ValueDecl *VD = DRE->getDecl();
4788 if (VD->hasAttr<BlocksAttr>())
4789 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004790 if (HasLocalVariableExternalStorage(VD))
4791 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004792 }
4793
Steve Narofffa15fd92008-10-28 20:29:00 +00004794 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004795 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004796 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004797 ReplaceStmt(S, BlockCall);
4798 return BlockCall;
4799 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004801 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004802 RewriteCastExpr(CE);
4803 }
4804#if 0
4805 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004806 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4807 ICE->getSubExpr(),
4808 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004809 // Get the new text.
4810 std::string SStr;
4811 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004812 Replacement->printPretty(Buf);
Steve Narofffa15fd92008-10-28 20:29:00 +00004813 const std::string &Str = Buf.str();
4814
4815 printf("CAST = %s\n", &Str[0]);
4816 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4817 delete S;
4818 return Replacement;
4819 }
4820#endif
4821 // Return this stmt unmodified.
4822 return S;
4823}
4824
Steve Naroff3d7e7862009-12-05 15:55:59 +00004825void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004826 for (auto *FD : RD->fields()) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00004827 if (isTopLevelBlockPointerType(FD->getType()))
4828 RewriteBlockPointerDecl(FD);
4829 if (FD->getType()->isObjCQualifiedIdType() ||
4830 FD->getType()->isObjCQualifiedInterfaceType())
4831 RewriteObjCQualifiedInterfaceTypes(FD);
4832 }
4833}
4834
Steve Narofffa15fd92008-10-28 20:29:00 +00004835/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4836/// main file of the input.
4837void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004838 switch (D->getKind()) {
4839 case Decl::Function: {
4840 FunctionDecl *FD = cast<FunctionDecl>(D);
4841 if (FD->isOverloadedOperator())
4842 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004844 // Since function prototypes don't have ParmDecl's, we check the function
4845 // prototype. This enables us to rewrite function declarations and
4846 // definitions using the same code.
4847 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004848
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004849 if (!FD->isThisDeclarationADefinition())
4850 break;
4851
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004852 // FIXME: If this should support Obj-C++, support CXXTryStmt
4853 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4854 CurFunctionDef = FD;
4855 CurFunctionDeclToDeclareForBlock = FD;
4856 CurrentBody = Body;
4857 Body =
4858 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4859 FD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004860 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004861 if (PropParentMap) {
4862 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004863 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004864 }
4865 // This synthesizes and inserts the block "impl" struct, invoke function,
4866 // and any copy/dispose helper functions.
4867 InsertBlockLiteralsWithinFunction(FD);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004868 CurFunctionDef = nullptr;
4869 CurFunctionDeclToDeclareForBlock = nullptr;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004870 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004871 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004872 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004873 case Decl::ObjCMethod: {
4874 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4875 if (CompoundStmt *Body = MD->getCompoundBody()) {
4876 CurMethodDef = MD;
4877 CurrentBody = Body;
4878 Body =
4879 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4880 MD->setBody(Body);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004881 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004882 if (PropParentMap) {
4883 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004884 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004885 }
4886 InsertBlockLiteralsWithinMethod(MD);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004887 CurMethodDef = nullptr;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004888 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004889 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004890 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004891 case Decl::ObjCImplementation: {
4892 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4893 ClassImplementation.push_back(CI);
4894 break;
4895 }
4896 case Decl::ObjCCategoryImpl: {
4897 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4898 CategoryImplementation.push_back(CI);
4899 break;
4900 }
4901 case Decl::Var: {
4902 VarDecl *VD = cast<VarDecl>(D);
4903 RewriteObjCQualifiedInterfaceTypes(VD);
4904 if (isTopLevelBlockPointerType(VD->getType()))
4905 RewriteBlockPointerDecl(VD);
4906 else if (VD->getType()->isFunctionPointerType()) {
4907 CheckFunctionPointerDecl(VD->getType(), VD);
4908 if (VD->getInit()) {
4909 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4910 RewriteCastExpr(CE);
4911 }
4912 }
4913 } else if (VD->getType()->isRecordType()) {
4914 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4915 if (RD->isCompleteDefinition())
4916 RewriteRecordBody(RD);
4917 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004918 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004919 GlobalVarDecl = VD;
4920 CurrentBody = VD->getInit();
4921 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004922 CurrentBody = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004923 if (PropParentMap) {
4924 delete PropParentMap;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004925 PropParentMap = nullptr;
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004926 }
4927 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004928 GlobalVarDecl = nullptr;
4929
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004930 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004931 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004932 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004933 }
4934 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004935 break;
4936 }
4937 case Decl::TypeAlias:
4938 case Decl::Typedef: {
4939 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4940 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4941 RewriteBlockPointerDecl(TD);
4942 else if (TD->getUnderlyingType()->isFunctionPointerType())
4943 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4944 }
4945 break;
4946 }
4947 case Decl::CXXRecord:
4948 case Decl::Record: {
4949 RecordDecl *RD = cast<RecordDecl>(D);
4950 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004951 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004952 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004953 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004954 default:
4955 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004956 }
4957 // Nothing yet.
4958}
4959
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004960void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004961 if (Diags.hasErrorOccurred())
4962 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004963
Steve Narofffa15fd92008-10-28 20:29:00 +00004964 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004965
Steve Naroff621edce2009-04-29 16:37:50 +00004966 // Here's a great place to add any extra declarations that may be needed.
4967 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00004968 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004969 E = ProtocolExprDecls.end(); I != E; ++I)
4970 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4971
Benjamin Kramerd999b372010-02-14 14:14:16 +00004972 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00004973 if (ClassImplementation.size() || CategoryImplementation.size())
4974 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00004975
Steve Narofffa15fd92008-10-28 20:29:00 +00004976 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4977 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00004978 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00004979 Rewrite.getRewriteBufferFor(MainFileID)) {
4980 //printf("Changed:\n");
4981 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4982 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00004983 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00004984 }
Steve Narofface66252008-11-13 20:07:04 +00004985
Steve Naroff621edce2009-04-29 16:37:50 +00004986 if (ClassImplementation.size() || CategoryImplementation.size() ||
4987 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00004988 // Rewrite Objective-c meta data*
4989 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00004990 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00004991 // Emit metadata.
4992 *OutFile << ResultStr;
4993 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004994 OutFile->flush();
4995}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00004996
4997void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4998 InitializeCommon(context);
4999
5000 // declaring objc_selector outside the parameter list removes a silly
5001 // scope related warning...
5002 if (IsHeader)
5003 Preamble = "#pragma once\n";
5004 Preamble += "struct objc_selector; struct objc_class;\n";
5005 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5006 Preamble += "struct objc_object *superClass; ";
5007 if (LangOpts.MicrosoftExt) {
5008 // Add a constructor for creating temporary objects.
5009 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5010 ": ";
5011 Preamble += "object(o), superClass(s) {} ";
5012 }
5013 Preamble += "};\n";
5014 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5015 Preamble += "typedef struct objc_object Protocol;\n";
5016 Preamble += "#define _REWRITER_typedef_Protocol\n";
5017 Preamble += "#endif\n";
5018 if (LangOpts.MicrosoftExt) {
5019 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5020 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5021 } else
5022 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5023 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5024 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5025 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5026 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5027 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5028 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5029 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5030 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5031 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5032 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5033 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5034 Preamble += "(const char *);\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5036 Preamble += "(struct objc_class *);\n";
5037 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5038 Preamble += "(const char *);\n";
5039 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5040 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5041 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5042 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5043 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5044 Preamble += "(struct objc_class *, struct objc_object *);\n";
5045 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005046 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
5047 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005048 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5049 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5050 Preamble += "struct __objcFastEnumerationState {\n\t";
5051 Preamble += "unsigned long state;\n\t";
5052 Preamble += "void **itemsPtr;\n\t";
5053 Preamble += "unsigned long *mutationsPtr;\n\t";
5054 Preamble += "unsigned long extra[5];\n};\n";
5055 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5056 Preamble += "#define __FASTENUMERATIONSTATE\n";
5057 Preamble += "#endif\n";
5058 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5059 Preamble += "struct __NSConstantStringImpl {\n";
5060 Preamble += " int *isa;\n";
5061 Preamble += " int flags;\n";
5062 Preamble += " char *str;\n";
5063 Preamble += " long length;\n";
5064 Preamble += "};\n";
5065 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5066 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5067 Preamble += "#else\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5069 Preamble += "#endif\n";
5070 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5071 Preamble += "#endif\n";
5072 // Blocks preamble.
5073 Preamble += "#ifndef BLOCK_IMPL\n";
5074 Preamble += "#define BLOCK_IMPL\n";
5075 Preamble += "struct __block_impl {\n";
5076 Preamble += " void *isa;\n";
5077 Preamble += " int Flags;\n";
5078 Preamble += " int Reserved;\n";
5079 Preamble += " void *FuncPtr;\n";
5080 Preamble += "};\n";
5081 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5082 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5083 Preamble += "extern \"C\" __declspec(dllexport) "
5084 "void _Block_object_assign(void *, const void *, const int);\n";
5085 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5086 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5087 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5088 Preamble += "#else\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5093 Preamble += "#endif\n";
5094 Preamble += "#endif\n";
5095 if (LangOpts.MicrosoftExt) {
5096 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5097 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5098 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5099 Preamble += "#define __attribute__(X)\n";
5100 Preamble += "#endif\n";
5101 Preamble += "#define __weak\n";
5102 }
5103 else {
5104 Preamble += "#define __block\n";
5105 Preamble += "#define __weak\n";
5106 }
5107 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5108 // as this avoids warning in any 64bit/32bit compilation model.
5109 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5110}
5111
5112/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5113/// ivar offset.
5114void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5115 std::string &Result) {
5116 if (ivar->isBitField()) {
5117 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5118 // place all bitfields at offset 0.
5119 Result += "0";
5120 } else {
5121 Result += "__OFFSETOFIVAR__(struct ";
5122 Result += ivar->getContainingInterface()->getNameAsString();
5123 if (LangOpts.MicrosoftExt)
5124 Result += "_IMPL";
5125 Result += ", ";
5126 Result += ivar->getNameAsString();
5127 Result += ")";
5128 }
5129}
5130
5131/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5132void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5133 ObjCProtocolDecl *PDecl, StringRef prefix,
5134 StringRef ClassName, std::string &Result) {
5135 static bool objc_protocol_methods = false;
5136
5137 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005138 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005139 /* struct protocol_methods {
5140 SEL _cmd;
5141 char *method_types;
5142 }
5143 */
5144 Result += "\nstruct _protocol_methods {\n";
5145 Result += "\tstruct objc_selector *_cmd;\n";
5146 Result += "\tchar *method_types;\n";
5147 Result += "};\n";
5148
5149 objc_protocol_methods = true;
5150 }
5151 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005152 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005153 return;
5154
Douglas Gregor61cc2962012-01-02 02:00:30 +00005155 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5156 PDecl = Def;
5157
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005158 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5159 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5160 PDecl->instmeth_end());
5161 /* struct _objc_protocol_method_list {
5162 int protocol_method_count;
5163 struct protocol_methods protocols[];
5164 }
5165 */
5166 Result += "\nstatic struct {\n";
5167 Result += "\tint protocol_method_count;\n";
5168 Result += "\tstruct _protocol_methods protocol_methods[";
5169 Result += utostr(NumMethods);
5170 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5171 Result += PDecl->getNameAsString();
5172 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5173 "{\n\t" + utostr(NumMethods) + "\n";
5174
5175 // Output instance methods declared in this protocol.
5176 for (ObjCProtocolDecl::instmeth_iterator
5177 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5178 I != E; ++I) {
5179 if (I == PDecl->instmeth_begin())
5180 Result += "\t ,{{(struct objc_selector *)\"";
5181 else
5182 Result += "\t ,{(struct objc_selector *)\"";
5183 Result += (*I)->getSelector().getAsString();
5184 std::string MethodTypeString;
5185 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5186 Result += "\", \"";
5187 Result += MethodTypeString;
5188 Result += "\"}\n";
5189 }
5190 Result += "\t }\n};\n";
5191 }
5192
5193 // Output class methods declared in this protocol.
5194 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5195 PDecl->classmeth_end());
5196 if (NumMethods > 0) {
5197 /* struct _objc_protocol_method_list {
5198 int protocol_method_count;
5199 struct protocol_methods protocols[];
5200 }
5201 */
5202 Result += "\nstatic struct {\n";
5203 Result += "\tint protocol_method_count;\n";
5204 Result += "\tstruct _protocol_methods protocol_methods[";
5205 Result += utostr(NumMethods);
5206 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5207 Result += PDecl->getNameAsString();
5208 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5209 "{\n\t";
5210 Result += utostr(NumMethods);
5211 Result += "\n";
5212
5213 // Output instance methods declared in this protocol.
5214 for (ObjCProtocolDecl::classmeth_iterator
5215 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5216 I != E; ++I) {
5217 if (I == PDecl->classmeth_begin())
5218 Result += "\t ,{{(struct objc_selector *)\"";
5219 else
5220 Result += "\t ,{(struct objc_selector *)\"";
5221 Result += (*I)->getSelector().getAsString();
5222 std::string MethodTypeString;
5223 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5224 Result += "\", \"";
5225 Result += MethodTypeString;
5226 Result += "\"}\n";
5227 }
5228 Result += "\t }\n};\n";
5229 }
5230
5231 // Output:
5232 /* struct _objc_protocol {
5233 // Objective-C 1.0 extensions
5234 struct _objc_protocol_extension *isa;
5235 char *protocol_name;
5236 struct _objc_protocol **protocol_list;
5237 struct _objc_protocol_method_list *instance_methods;
5238 struct _objc_protocol_method_list *class_methods;
5239 };
5240 */
5241 static bool objc_protocol = false;
5242 if (!objc_protocol) {
5243 Result += "\nstruct _objc_protocol {\n";
5244 Result += "\tstruct _objc_protocol_extension *isa;\n";
5245 Result += "\tchar *protocol_name;\n";
5246 Result += "\tstruct _objc_protocol **protocol_list;\n";
5247 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5248 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5249 Result += "};\n";
5250
5251 objc_protocol = true;
5252 }
5253
5254 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5255 Result += PDecl->getNameAsString();
5256 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5257 "{\n\t0, \"";
5258 Result += PDecl->getNameAsString();
5259 Result += "\", 0, ";
5260 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5261 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5262 Result += PDecl->getNameAsString();
5263 Result += ", ";
5264 }
5265 else
5266 Result += "0, ";
5267 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5268 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5269 Result += PDecl->getNameAsString();
5270 Result += "\n";
5271 }
5272 else
5273 Result += "0\n";
5274 Result += "};\n";
5275
5276 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005277 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005278 llvm_unreachable("protocol already synthesized");
5279
5280}
5281
5282void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5283 const ObjCList<ObjCProtocolDecl> &Protocols,
5284 StringRef prefix, StringRef ClassName,
5285 std::string &Result) {
5286 if (Protocols.empty()) return;
5287
5288 for (unsigned i = 0; i != Protocols.size(); i++)
5289 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5290
5291 // Output the top lovel protocol meta-data for the class.
5292 /* struct _objc_protocol_list {
5293 struct _objc_protocol_list *next;
5294 int protocol_count;
5295 struct _objc_protocol *class_protocols[];
5296 }
5297 */
5298 Result += "\nstatic struct {\n";
5299 Result += "\tstruct _objc_protocol_list *next;\n";
5300 Result += "\tint protocol_count;\n";
5301 Result += "\tstruct _objc_protocol *class_protocols[";
5302 Result += utostr(Protocols.size());
5303 Result += "];\n} _OBJC_";
5304 Result += prefix;
5305 Result += "_PROTOCOLS_";
5306 Result += ClassName;
5307 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5308 "{\n\t0, ";
5309 Result += utostr(Protocols.size());
5310 Result += "\n";
5311
5312 Result += "\t,{&_OBJC_PROTOCOL_";
5313 Result += Protocols[0]->getNameAsString();
5314 Result += " \n";
5315
5316 for (unsigned i = 1; i != Protocols.size(); i++) {
5317 Result += "\t ,&_OBJC_PROTOCOL_";
5318 Result += Protocols[i]->getNameAsString();
5319 Result += "\n";
5320 }
5321 Result += "\t }\n};\n";
5322}
5323
5324void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5325 std::string &Result) {
5326 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5327
5328 // Explicitly declared @interface's are already synthesized.
5329 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005330 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005331 // produce correct synthesis as yet.
5332 RewriteObjCInternalStruct(CDecl, Result);
5333 }
5334
5335 // Build _objc_ivar_list metadata for classes ivars if needed
5336 unsigned NumIvars = !IDecl->ivar_empty()
5337 ? IDecl->ivar_size()
5338 : (CDecl ? CDecl->ivar_size() : 0);
5339 if (NumIvars > 0) {
5340 static bool objc_ivar = false;
5341 if (!objc_ivar) {
5342 /* struct _objc_ivar {
5343 char *ivar_name;
5344 char *ivar_type;
5345 int ivar_offset;
5346 };
5347 */
5348 Result += "\nstruct _objc_ivar {\n";
5349 Result += "\tchar *ivar_name;\n";
5350 Result += "\tchar *ivar_type;\n";
5351 Result += "\tint ivar_offset;\n";
5352 Result += "};\n";
5353
5354 objc_ivar = true;
5355 }
5356
5357 /* struct {
5358 int ivar_count;
5359 struct _objc_ivar ivar_list[nIvars];
5360 };
5361 */
5362 Result += "\nstatic struct {\n";
5363 Result += "\tint ivar_count;\n";
5364 Result += "\tstruct _objc_ivar ivar_list[";
5365 Result += utostr(NumIvars);
5366 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5367 Result += IDecl->getNameAsString();
5368 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5369 "{\n\t";
5370 Result += utostr(NumIvars);
5371 Result += "\n";
5372
5373 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5374 SmallVector<ObjCIvarDecl *, 8> IVars;
5375 if (!IDecl->ivar_empty()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07005376 for (auto *IV : IDecl->ivars())
5377 IVars.push_back(IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005378 IVI = IDecl->ivar_begin();
5379 IVE = IDecl->ivar_end();
5380 } else {
5381 IVI = CDecl->ivar_begin();
5382 IVE = CDecl->ivar_end();
5383 }
5384 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005385 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005386 Result += "\", \"";
5387 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005388 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005389 QuoteDoublequotes(TmpString, StrEncoding);
5390 Result += StrEncoding;
5391 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005392 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005393 Result += "}\n";
5394 for (++IVI; IVI != IVE; ++IVI) {
5395 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005396 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005397 Result += "\", \"";
5398 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005399 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005400 QuoteDoublequotes(TmpString, StrEncoding);
5401 Result += StrEncoding;
5402 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005403 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005404 Result += "}\n";
5405 }
5406
5407 Result += "\t }\n};\n";
5408 }
5409
5410 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005411 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005412
5413 // If any of our property implementations have associated getters or
5414 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005415 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005416 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005417 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005418 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005419 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005420 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005421 if (!PD)
5422 continue;
5423 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5424 if (!Getter->isDefined())
5425 InstanceMethods.push_back(Getter);
5426 if (PD->isReadOnly())
5427 continue;
5428 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5429 if (!Setter->isDefined())
5430 InstanceMethods.push_back(Setter);
5431 }
5432 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5433 true, "", IDecl->getName(), Result);
5434
5435 // Build _objc_method_list for class's class methods if needed
5436 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5437 false, "", IDecl->getName(), Result);
5438
5439 // Protocols referenced in class declaration?
5440 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5441 "CLASS", CDecl->getName(), Result);
5442
5443 // Declaration of class/meta-class metadata
5444 /* struct _objc_class {
5445 struct _objc_class *isa; // or const char *root_class_name when metadata
5446 const char *super_class_name;
5447 char *name;
5448 long version;
5449 long info;
5450 long instance_size;
5451 struct _objc_ivar_list *ivars;
5452 struct _objc_method_list *methods;
5453 struct objc_cache *cache;
5454 struct objc_protocol_list *protocols;
5455 const char *ivar_layout;
5456 struct _objc_class_ext *ext;
5457 };
5458 */
5459 static bool objc_class = false;
5460 if (!objc_class) {
5461 Result += "\nstruct _objc_class {\n";
5462 Result += "\tstruct _objc_class *isa;\n";
5463 Result += "\tconst char *super_class_name;\n";
5464 Result += "\tchar *name;\n";
5465 Result += "\tlong version;\n";
5466 Result += "\tlong info;\n";
5467 Result += "\tlong instance_size;\n";
5468 Result += "\tstruct _objc_ivar_list *ivars;\n";
5469 Result += "\tstruct _objc_method_list *methods;\n";
5470 Result += "\tstruct objc_cache *cache;\n";
5471 Result += "\tstruct _objc_protocol_list *protocols;\n";
5472 Result += "\tconst char *ivar_layout;\n";
5473 Result += "\tstruct _objc_class_ext *ext;\n";
5474 Result += "};\n";
5475 objc_class = true;
5476 }
5477
5478 // Meta-class metadata generation.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005479 ObjCInterfaceDecl *RootClass = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005480 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5481 while (SuperClass) {
5482 RootClass = SuperClass;
5483 SuperClass = SuperClass->getSuperClass();
5484 }
5485 SuperClass = CDecl->getSuperClass();
5486
5487 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5488 Result += CDecl->getNameAsString();
5489 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5490 "{\n\t(struct _objc_class *)\"";
5491 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5492 Result += "\"";
5493
5494 if (SuperClass) {
5495 Result += ", \"";
5496 Result += SuperClass->getNameAsString();
5497 Result += "\", \"";
5498 Result += CDecl->getNameAsString();
5499 Result += "\"";
5500 }
5501 else {
5502 Result += ", 0, \"";
5503 Result += CDecl->getNameAsString();
5504 Result += "\"";
5505 }
5506 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5507 // 'info' field is initialized to CLS_META(2) for metaclass
5508 Result += ", 0,2, sizeof(struct _objc_class), 0";
5509 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5510 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5511 Result += IDecl->getNameAsString();
5512 Result += "\n";
5513 }
5514 else
5515 Result += ", 0\n";
5516 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5517 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5518 Result += CDecl->getNameAsString();
5519 Result += ",0,0\n";
5520 }
5521 else
5522 Result += "\t,0,0,0,0\n";
5523 Result += "};\n";
5524
5525 // class metadata generation.
5526 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5527 Result += CDecl->getNameAsString();
5528 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5529 "{\n\t&_OBJC_METACLASS_";
5530 Result += CDecl->getNameAsString();
5531 if (SuperClass) {
5532 Result += ", \"";
5533 Result += SuperClass->getNameAsString();
5534 Result += "\", \"";
5535 Result += CDecl->getNameAsString();
5536 Result += "\"";
5537 }
5538 else {
5539 Result += ", 0, \"";
5540 Result += CDecl->getNameAsString();
5541 Result += "\"";
5542 }
5543 // 'info' field is initialized to CLS_CLASS(1) for class
5544 Result += ", 0,1";
5545 if (!ObjCSynthesizedStructs.count(CDecl))
5546 Result += ",0";
5547 else {
5548 // class has size. Must synthesize its size.
5549 Result += ",sizeof(struct ";
5550 Result += CDecl->getNameAsString();
5551 if (LangOpts.MicrosoftExt)
5552 Result += "_IMPL";
5553 Result += ")";
5554 }
5555 if (NumIvars > 0) {
5556 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5557 Result += CDecl->getNameAsString();
5558 Result += "\n\t";
5559 }
5560 else
5561 Result += ",0";
5562 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5563 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5564 Result += CDecl->getNameAsString();
5565 Result += ", 0\n\t";
5566 }
5567 else
5568 Result += ",0,0";
5569 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5570 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5571 Result += CDecl->getNameAsString();
5572 Result += ", 0,0\n";
5573 }
5574 else
5575 Result += ",0,0,0\n";
5576 Result += "};\n";
5577}
5578
5579void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5580 int ClsDefCount = ClassImplementation.size();
5581 int CatDefCount = CategoryImplementation.size();
5582
5583 // For each implemented class, write out all its meta data.
5584 for (int i = 0; i < ClsDefCount; i++)
5585 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5586
5587 // For each implemented category, write out all its meta data.
5588 for (int i = 0; i < CatDefCount; i++)
5589 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5590
5591 // Write objc_symtab metadata
5592 /*
5593 struct _objc_symtab
5594 {
5595 long sel_ref_cnt;
5596 SEL *refs;
5597 short cls_def_cnt;
5598 short cat_def_cnt;
5599 void *defs[cls_def_cnt + cat_def_cnt];
5600 };
5601 */
5602
5603 Result += "\nstruct _objc_symtab {\n";
5604 Result += "\tlong sel_ref_cnt;\n";
5605 Result += "\tSEL *refs;\n";
5606 Result += "\tshort cls_def_cnt;\n";
5607 Result += "\tshort cat_def_cnt;\n";
5608 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5609 Result += "};\n\n";
5610
5611 Result += "static struct _objc_symtab "
5612 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5613 Result += "\t0, 0, " + utostr(ClsDefCount)
5614 + ", " + utostr(CatDefCount) + "\n";
5615 for (int i = 0; i < ClsDefCount; i++) {
5616 Result += "\t,&_OBJC_CLASS_";
5617 Result += ClassImplementation[i]->getNameAsString();
5618 Result += "\n";
5619 }
5620
5621 for (int i = 0; i < CatDefCount; i++) {
5622 Result += "\t,&_OBJC_CATEGORY_";
5623 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5624 Result += "_";
5625 Result += CategoryImplementation[i]->getNameAsString();
5626 Result += "\n";
5627 }
5628
5629 Result += "};\n\n";
5630
5631 // Write objc_module metadata
5632
5633 /*
5634 struct _objc_module {
5635 long version;
5636 long size;
5637 const char *name;
5638 struct _objc_symtab *symtab;
5639 }
5640 */
5641
5642 Result += "\nstruct _objc_module {\n";
5643 Result += "\tlong version;\n";
5644 Result += "\tlong size;\n";
5645 Result += "\tconst char *name;\n";
5646 Result += "\tstruct _objc_symtab *symtab;\n";
5647 Result += "};\n\n";
5648 Result += "static struct _objc_module "
5649 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5650 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5651 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5652 Result += "};\n\n";
5653
5654 if (LangOpts.MicrosoftExt) {
5655 if (ProtocolExprDecls.size()) {
5656 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5657 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5658 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5659 E = ProtocolExprDecls.end(); I != E; ++I) {
5660 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5661 Result += (*I)->getNameAsString();
5662 Result += " = &_OBJC_PROTOCOL_";
5663 Result += (*I)->getNameAsString();
5664 Result += ";\n";
5665 }
5666 Result += "#pragma data_seg(pop)\n\n";
5667 }
5668 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5669 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5670 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5671 Result += "&_OBJC_MODULES;\n";
5672 Result += "#pragma data_seg(pop)\n\n";
5673 }
5674}
5675
5676/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5677/// implementation.
5678void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5679 std::string &Result) {
5680 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5681 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00005682 ObjCCategoryDecl *CDecl
5683 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005684
5685 std::string FullCategoryName = ClassDecl->getNameAsString();
5686 FullCategoryName += '_';
5687 FullCategoryName += IDecl->getNameAsString();
5688
5689 // Build _objc_method_list for class's instance methods if needed
Stephen Hines651f13c2014-04-23 16:59:28 -07005690 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005691
5692 // If any of our property implementations have associated getters or
5693 // setters, produce metadata for them as well.
Stephen Hines651f13c2014-04-23 16:59:28 -07005694 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie262bc182012-04-30 02:36:29 +00005695 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005696 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005697 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005698 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005699 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005700 if (!PD)
5701 continue;
5702 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5703 InstanceMethods.push_back(Getter);
5704 if (PD->isReadOnly())
5705 continue;
5706 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5707 InstanceMethods.push_back(Setter);
5708 }
5709 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5710 true, "CATEGORY_", FullCategoryName.c_str(),
5711 Result);
5712
5713 // Build _objc_method_list for class's class methods if needed
5714 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5715 false, "CATEGORY_", FullCategoryName.c_str(),
5716 Result);
5717
5718 // Protocols referenced in class declaration?
5719 // Null CDecl is case of a category implementation with no category interface
5720 if (CDecl)
5721 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5722 FullCategoryName, Result);
5723 /* struct _objc_category {
5724 char *category_name;
5725 char *class_name;
5726 struct _objc_method_list *instance_methods;
5727 struct _objc_method_list *class_methods;
5728 struct _objc_protocol_list *protocols;
5729 // Objective-C 1.0 extensions
5730 uint32_t size; // sizeof (struct _objc_category)
5731 struct _objc_property_list *instance_properties; // category's own
5732 // @property decl.
5733 };
5734 */
5735
5736 static bool objc_category = false;
5737 if (!objc_category) {
5738 Result += "\nstruct _objc_category {\n";
5739 Result += "\tchar *category_name;\n";
5740 Result += "\tchar *class_name;\n";
5741 Result += "\tstruct _objc_method_list *instance_methods;\n";
5742 Result += "\tstruct _objc_method_list *class_methods;\n";
5743 Result += "\tstruct _objc_protocol_list *protocols;\n";
5744 Result += "\tunsigned int size;\n";
5745 Result += "\tstruct _objc_property_list *instance_properties;\n";
5746 Result += "};\n";
5747 objc_category = true;
5748 }
5749 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5750 Result += FullCategoryName;
5751 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5752 Result += IDecl->getNameAsString();
5753 Result += "\"\n\t, \"";
5754 Result += ClassDecl->getNameAsString();
5755 Result += "\"\n";
5756
5757 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5758 Result += "\t, (struct _objc_method_list *)"
5759 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5760 Result += FullCategoryName;
5761 Result += "\n";
5762 }
5763 else
5764 Result += "\t, 0\n";
5765 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5766 Result += "\t, (struct _objc_method_list *)"
5767 "&_OBJC_CATEGORY_CLASS_METHODS_";
5768 Result += FullCategoryName;
5769 Result += "\n";
5770 }
5771 else
5772 Result += "\t, 0\n";
5773
5774 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5775 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5776 Result += FullCategoryName;
5777 Result += "\n";
5778 }
5779 else
5780 Result += "\t, 0\n";
5781 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5782}
5783
5784// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5785/// class methods.
5786template<typename MethodIterator>
5787void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5788 MethodIterator MethodEnd,
5789 bool IsInstanceMethod,
5790 StringRef prefix,
5791 StringRef ClassName,
5792 std::string &Result) {
5793 if (MethodBegin == MethodEnd) return;
5794
5795 if (!objc_impl_method) {
5796 /* struct _objc_method {
5797 SEL _cmd;
5798 char *method_types;
5799 void *_imp;
5800 }
5801 */
5802 Result += "\nstruct _objc_method {\n";
5803 Result += "\tSEL _cmd;\n";
5804 Result += "\tchar *method_types;\n";
5805 Result += "\tvoid *_imp;\n";
5806 Result += "};\n";
5807
5808 objc_impl_method = true;
5809 }
5810
5811 // Build _objc_method_list for class's methods if needed
5812
5813 /* struct {
5814 struct _objc_method_list *next_method;
5815 int method_count;
5816 struct _objc_method method_list[];
5817 }
5818 */
5819 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5820 Result += "\nstatic struct {\n";
5821 Result += "\tstruct _objc_method_list *next_method;\n";
5822 Result += "\tint method_count;\n";
5823 Result += "\tstruct _objc_method method_list[";
5824 Result += utostr(NumMethods);
5825 Result += "];\n} _OBJC_";
5826 Result += prefix;
5827 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5828 Result += "_METHODS_";
5829 Result += ClassName;
5830 Result += " __attribute__ ((used, section (\"__OBJC, __";
5831 Result += IsInstanceMethod ? "inst" : "cls";
5832 Result += "_meth\")))= ";
5833 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5834
5835 Result += "\t,{{(SEL)\"";
5836 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5837 std::string MethodTypeString;
5838 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5839 Result += "\", \"";
5840 Result += MethodTypeString;
5841 Result += "\", (void *)";
5842 Result += MethodInternalNames[*MethodBegin];
5843 Result += "}\n";
5844 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5845 Result += "\t ,{(SEL)\"";
5846 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5847 std::string MethodTypeString;
5848 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5849 Result += "\", \"";
5850 Result += MethodTypeString;
5851 Result += "\", (void *)";
5852 Result += MethodInternalNames[*MethodBegin];
5853 Result += "}\n";
5854 }
5855 Result += "\t }\n};\n";
5856}
5857
5858Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5859 SourceRange OldRange = IV->getSourceRange();
5860 Expr *BaseExpr = IV->getBase();
5861
5862 // Rewrite the base, but without actually doing replaces.
5863 {
5864 DisableReplaceStmtScope S(*this);
5865 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5866 IV->setBase(BaseExpr);
5867 }
5868
5869 ObjCIvarDecl *D = IV->getDecl();
5870
5871 Expr *Replacement = IV;
5872 if (CurMethodDef) {
5873 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5874 const ObjCInterfaceType *iFaceDecl =
5875 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5876 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5877 // lookup which class implements the instance variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005878 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005879 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5880 clsDeclared);
5881 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5882
5883 // Synthesize an explicit cast to gain access to the ivar.
5884 std::string RecName = clsDeclared->getIdentifier()->getName();
5885 RecName += "_IMPL";
5886 IdentifierInfo *II = &Context->Idents.get(RecName);
5887 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5888 SourceLocation(), SourceLocation(),
5889 II);
5890 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5891 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5892 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5893 CK_BitCast,
5894 IV->getBase());
5895 // Don't forget the parens to enforce the proper binding.
5896 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5897 OldRange.getEnd(),
5898 castExpr);
5899 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005900 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005901 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5902 IV->getLocation(),
5903 D->getType(),
5904 VK_LValue, OK_Ordinary);
5905 Replacement = ME;
5906 } else {
5907 IV->setBase(PE);
5908 }
5909 }
5910 } else { // we are outside a method.
5911 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5912
5913 // Explicit ivar refs need to have a cast inserted.
5914 // FIXME: consider sharing some of this code with the code above.
5915 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5916 const ObjCInterfaceType *iFaceDecl =
5917 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5918 // lookup which class implements the instance variable.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005919 ObjCInterfaceDecl *clsDeclared = nullptr;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005920 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5921 clsDeclared);
5922 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5923
5924 // Synthesize an explicit cast to gain access to the ivar.
5925 std::string RecName = clsDeclared->getIdentifier()->getName();
5926 RecName += "_IMPL";
5927 IdentifierInfo *II = &Context->Idents.get(RecName);
5928 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5929 SourceLocation(), SourceLocation(),
5930 II);
5931 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5932 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5933 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5934 CK_BitCast,
5935 IV->getBase());
5936 // Don't forget the parens to enforce the proper binding.
5937 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5938 IV->getBase()->getLocEnd(), castExpr);
5939 // Cannot delete IV->getBase(), since PE points to it.
5940 // Replace the old base with the cast. This is important when doing
5941 // embedded rewrites. For example, [newInv->_container addObject:0].
5942 IV->setBase(PE);
5943 }
5944 }
5945
5946 ReplaceStmtWithRange(IV, Replacement, OldRange);
5947 return Replacement;
5948}