blob: 425cd77751cab21d29337faa9c8e7670e590db6b [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000122 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
John McCallf4b88a42012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000174
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
Chris Lattner682bf922009-03-29 16:50:03 +0000182 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000183 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000184 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000185 }
186 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000187 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000188 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000189 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000190 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000191
192 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000194 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000201
Steve Naroffb619d952008-12-09 12:56:34 +0000202 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000203 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000204
Steve Naroff4c3580e2008-12-04 23:50:32 +0000205 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000206 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000214 }
Steve Naroffb619d952008-12-09 12:56:34 +0000215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000217 if (DisableReplaceStmt)
218 return;
219
Nick Lewycky7e749242010-10-31 21:07:24 +0000220 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000245 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000255 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000256 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 SilenceRewriteMacroWarning)
259 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattneraadaf782008-01-31 19:51:04 +0000261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000265 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000266 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000267 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000270 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000271 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000276 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000282 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000288 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000289 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000294 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000316
Steve Naroff54055232008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000319
Mike Stump1eb44332009-09-09 15:08:12 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000322 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000323 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000329
330 virtual void Initialize(ASTContext &context) = 0;
331
332 // Metadata Rewriting.
333 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
334 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
339 std::string &Result) = 0;
340 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
341 StringRef prefix,
342 StringRef ClassName,
343 std::string &Result) = 0;
344 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
345 std::string &Result) = 0;
346
347 // Rewriting ivar access
348 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
349 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
350 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000352 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +0000358 CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
359 QualType msgSendType,
360 QualType returnType,
361 SmallVectorImpl<QualType> &ArgTypes,
362 SmallVectorImpl<Expr*> &MsgExprs,
363 ObjCMethodDecl *Method);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000364 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 void SynthCountByEnumWithState(std::string &buf);
369 void SynthMsgSendFunctionDecl();
370 void SynthMsgSendSuperFunctionDecl();
371 void SynthMsgSendStretFunctionDecl();
372 void SynthMsgSendFpretFunctionDecl();
373 void SynthMsgSendSuperStretFunctionDecl();
374 void SynthGetClassFunctionDecl();
375 void SynthGetMetaClassFunctionDecl();
376 void SynthGetSuperClassFunctionDecl();
377 void SynthSelGetUidFunctionDecl();
378 void SynthSuperContructorFunctionDecl();
379
380 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000382 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000383 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000385 std::string SynthesizeBlockImpl(BlockExpr *CE,
386 std::string Tag, std::string Desc);
387 std::string SynthesizeBlockDescriptor(std::string DescTag,
388 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000389 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000390 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000391 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000392 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000394 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
395 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000396 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Fariborz Jahanian58457172011-12-05 18:43:13 +0000398 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000399 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000400 void WarnAboutReturnGotoStmts(Stmt *S);
401 void HasReturnStmts(Stmt *S, bool &hasReturns);
402 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
403 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
404 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
405
406 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000407 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000408 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000409 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000410 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000411 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Naroff54055232008-10-27 17:20:55 +0000413 // We avoid calling Type::isBlockPointerType(), since it operates on the
414 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000415 bool isTopLevelBlockPointerType(QualType T) {
416 return isa<BlockPointerType>(T);
417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000419 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
420 /// to a function pointer type and upon success, returns true; false
421 /// otherwise.
422 bool convertBlockPointerToFunctionPointer(QualType &T) {
423 if (isTopLevelBlockPointerType(T)) {
424 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
425 T = Context->getPointerType(BPT->getPointeeType());
426 return true;
427 }
428 return false;
429 }
430
Fariborz Jahanian58457172011-12-05 18:43:13 +0000431 bool needToScanForQualifiers(QualType T);
432 QualType getSuperStructType();
433 QualType getConstantStringStructType();
434 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
435 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
436
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000437 void convertToUnqualifiedObjCType(QualType &T) {
438 if (T->isObjCQualifiedIdType())
439 T = Context->getObjCIdType();
440 else if (T->isObjCQualifiedClassType())
441 T = Context->getObjCClassType();
442 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000443 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
444 if (const ObjCObjectPointerType * OBJPT =
445 T->getAsObjCInterfacePointerType()) {
446 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
447 T = QualType(IFaceT, 0);
448 T = Context->getPointerType(T);
449 }
450 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000451 }
452
Steve Naroff54055232008-10-27 17:20:55 +0000453 // FIXME: This predicate seems like it would be useful to add to ASTContext.
454 bool isObjCType(QualType T) {
455 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
456 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Steve Naroff54055232008-10-27 17:20:55 +0000458 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Steve Naroff54055232008-10-27 17:20:55 +0000460 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
461 OCT == Context->getCanonicalType(Context->getObjCClassType()))
462 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Ted Kremenek6217b802009-07-29 21:53:49 +0000464 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000465 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000466 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000467 return true;
468 }
469 return false;
470 }
471 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000472 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000473 void GetExtentOfArgList(const char *Name, const char *&LParen,
474 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000475
Steve Naroff621edce2009-04-29 16:37:50 +0000476 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000477 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000478 if (From[i] == '"')
479 To += "\\\"";
480 else
481 To += From[i];
482 }
483 }
John McCalle23cf432010-12-14 08:05:40 +0000484
485 QualType getSimpleFunctionType(QualType result,
486 const QualType *args,
487 unsigned numArgs,
488 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000489 if (result == Context->getObjCInstanceType())
490 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000491 FunctionProtoType::ExtProtoInfo fpi;
492 fpi.Variadic = variadic;
493 return Context->getFunctionType(result, args, numArgs, fpi);
494 }
John McCall9d125032010-01-15 18:39:57 +0000495
Fariborz Jahanian58457172011-12-05 18:43:13 +0000496 // Helper function: create a CStyleCastExpr with trivial type source info.
497 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
498 CastKind Kind, Expr *E) {
499 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
500 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
501 SourceLocation(), SourceLocation());
502 }
503 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000504
505 class RewriteObjCFragileABI : public RewriteObjC {
506 public:
507
508 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
509 DiagnosticsEngine &D, const LangOptions &LOpts,
510 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
511 D, LOpts,
512 silenceMacroWarn) {}
513
514 ~RewriteObjCFragileABI() {}
515 virtual void Initialize(ASTContext &context);
516
517 // Rewriting metadata
518 template<typename MethodIterator>
519 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
520 MethodIterator MethodEnd,
521 bool IsInstanceMethod,
522 StringRef prefix,
523 StringRef ClassName,
524 std::string &Result);
525 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
526 StringRef prefix,
527 StringRef ClassName,
528 std::string &Result);
529 virtual void RewriteObjCProtocolListMetaData(
530 const ObjCList<ObjCProtocolDecl> &Prots,
531 StringRef prefix, StringRef ClassName, std::string &Result);
532 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
533 std::string &Result);
534 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
535 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
536 std::string &Result);
537
538 // Rewriting ivar
539 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
540 std::string &Result);
541 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
542 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000543}
544
Mike Stump1eb44332009-09-09 15:08:12 +0000545void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
546 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000547 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000548 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000549 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000550 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000551 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000552 // All the args are checked/rewritten. Don't call twice!
553 RewriteBlockPointerDecl(D);
554 break;
555 }
556 }
557}
558
559void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000560 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000561 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000562 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000563}
564
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000565static bool IsHeaderFile(const std::string &Filename) {
566 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000568 if (DotPos == std::string::npos) {
569 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000570 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000571 }
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000573 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
574 // C header: .h
575 // C++ header: .hh or .H;
576 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000577}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000578
Chris Lattner5f9e2722011-07-23 10:55:15 +0000579RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000580 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000581 bool silenceMacroWarn)
582 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
583 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000584 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000585 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000586 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000587 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
588 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000589 "rewriter doesn't support user-specified control flow semantics "
590 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000591}
592
Eli Friedmanbce831b2009-05-18 22:29:17 +0000593ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000594 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000595 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000596 const LangOptions &LOpts,
597 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000598 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000599}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000600
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000601void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000602 Context = &context;
603 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000604 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000605 MsgSendFunctionDecl = 0;
606 MsgSendSuperFunctionDecl = 0;
607 MsgSendStretFunctionDecl = 0;
608 MsgSendSuperStretFunctionDecl = 0;
609 MsgSendFpretFunctionDecl = 0;
610 GetClassFunctionDecl = 0;
611 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000612 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000613 SelGetUidFunctionDecl = 0;
614 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000615 ConstantStringClassReference = 0;
616 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000617 CurMethodDef = 0;
618 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000619 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000620 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000621 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000622 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000623 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000624 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000625 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000626 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000627 PropParentMap = 0;
628 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000629 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000630 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000632 // Get the ID and start/end of the main file.
633 MainFileID = SM->getMainFileID();
634 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
635 MainFileStart = MainBuf->getBufferStart();
636 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000637
David Blaikie4e4d0842012-03-11 07:00:24 +0000638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000639}
640
Chris Lattnerf04da132007-10-24 17:06:59 +0000641//===----------------------------------------------------------------------===//
642// Top Level Driver Code
643//===----------------------------------------------------------------------===//
644
Chris Lattner682bf922009-03-29 16:50:03 +0000645void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000646 if (Diags.hasErrorOccurred())
647 return;
648
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000649 // Two cases: either the decl could be in the main file, or it could be in a
650 // #included file. If the former, rewrite it now. If the later, check to see
651 // if we rewrote the #include/#import.
652 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000653 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000654
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000655 // If this is for a builtin, ignore it.
656 if (Loc.isInvalid()) return;
657
Steve Naroffebf2b562007-10-23 23:50:29 +0000658 // Look for built-in declarations that we need to refer during the rewrite.
659 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000660 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000661 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000662 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000663 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000664 ConstantStringClassReference = FVD;
665 return;
666 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000667 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
668 if (ID->isThisDeclarationADefinition())
669 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000671 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
676 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000677 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
678 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000679 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000680 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
681 if (!IFace->isThisDeclarationADefinition()) {
682 SmallVector<Decl *, 8> DG;
683 SourceLocation StartLoc = IFace->getLocStart();
684 do {
685 if (isa<ObjCInterfaceDecl>(*DI) &&
686 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
687 StartLoc == (*DI)->getLocStart())
688 DG.push_back(*DI);
689 else
690 break;
691
Douglas Gregor7723fec2011-12-15 20:29:51 +0000692 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000693 } while (DI != DIEnd);
694 RewriteForwardClassDecl(DG);
695 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000696 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000697 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000698
699 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
700 if (!Proto->isThisDeclarationADefinition()) {
701 SmallVector<Decl *, 8> DG;
702 SourceLocation StartLoc = Proto->getLocStart();
703 do {
704 if (isa<ObjCProtocolDecl>(*DI) &&
705 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
706 StartLoc == (*DI)->getLocStart())
707 DG.push_back(*DI);
708 else
709 break;
710
711 ++DI;
712 } while (DI != DIEnd);
713 RewriteForwardProtocolDecl(DG);
714 continue;
715 }
716 }
717
Chris Lattner682bf922009-03-29 16:50:03 +0000718 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000719 ++DI;
720 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000721 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000723 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000724 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000725}
726
Chris Lattnerf04da132007-10-24 17:06:59 +0000727//===----------------------------------------------------------------------===//
728// Syntactic (non-AST) Rewriting Code
729//===----------------------------------------------------------------------===//
730
Steve Naroffb29b4272008-04-14 22:03:09 +0000731void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000732 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000733 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000734 const char *MainBufStart = MainBuf.begin();
735 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000736 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000738 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000739 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
740 if (*BufPtr == '#') {
741 if (++BufPtr == MainBufEnd)
742 return;
743 while (*BufPtr == ' ' || *BufPtr == '\t')
744 if (++BufPtr == MainBufEnd)
745 return;
746 if (!strncmp(BufPtr, "import", ImportLen)) {
747 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000748 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000749 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000750 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000751 BufPtr += ImportLen;
752 }
753 }
754 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000755}
756
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000757static std::string getIvarAccessString(ObjCIvarDecl *OID) {
758 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 std::string S;
760 S = "((struct ";
761 S += ClassDecl->getIdentifier()->getName();
762 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000763 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 return S;
765}
766
Steve Naroffa0876e82008-12-02 17:36:43 +0000767void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
768 ObjCImplementationDecl *IMD,
769 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000770 static bool objcGetPropertyDefined = false;
771 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000772 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000773 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000774 const char *startBuf = SM->getCharacterData(startLoc);
775 assert((*startBuf == '@') && "bogus @synthesize location");
776 const char *semiBuf = strchr(startBuf, ';');
777 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000778 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000779 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780
781 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
782 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000785 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000787
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000788 if (!OID)
789 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000790 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000791 if (!PD->getGetterMethodDecl()->isDefined()) {
792 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794 ObjCPropertyDecl::OBJC_PR_copy));
795 std::string Getr;
796 if (GenGetProperty && !objcGetPropertyDefined) {
797 objcGetPropertyDefined = true;
798 // FIXME. Is this attribute correct in all cases?
799 Getr = "\nextern \"C\" __declspec(dllimport) "
800 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000801 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000802 RewriteObjCMethodDecl(OID->getContainingInterface(),
803 PD->getGetterMethodDecl(), Getr);
804 Getr += "{ ";
805 // Synthesize an explicit cast to gain access to the ivar.
806 // See objc-act.c:objc_synthesize_new_getter() for details.
807 if (GenGetProperty) {
808 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809 Getr += "typedef ";
810 const FunctionType *FPRetType = 0;
811 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
812 FPRetType);
813 Getr += " _TYPE";
814 if (FPRetType) {
815 Getr += ")"; // close the precedence "scope" for "*".
816
817 // Now, emit the argument types (if any).
818 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819 Getr += "(";
820 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
821 if (i) Getr += ", ";
822 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000823 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000824 Getr += ParamStr;
825 }
826 if (FT->isVariadic()) {
827 if (FT->getNumArgs()) Getr += ", ";
828 Getr += "...";
829 }
830 Getr += ")";
831 } else
832 Getr += "()";
833 }
834 Getr += ";\n";
835 Getr += "return (_TYPE)";
836 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000837 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000838 Getr += ", 1)";
839 }
840 else
841 Getr += "return " + getIvarAccessString(OID);
842 Getr += "; }";
843 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000845
846 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000847 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Steve Naroffeb0646c2008-12-02 15:48:25 +0000849 // Generate the 'setter' function.
850 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000851 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
852 ObjCPropertyDecl::OBJC_PR_copy);
853 if (GenSetProperty && !objcSetPropertyDefined) {
854 objcSetPropertyDefined = true;
855 // FIXME. Is this attribute correct in all cases?
856 Setr = "\nextern \"C\" __declspec(dllimport) "
857 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
858 }
859
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000860 RewriteObjCMethodDecl(OID->getContainingInterface(),
861 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000862 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000863 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000864 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 if (GenSetProperty) {
866 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000867 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000869 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000870 Setr += ", ";
871 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
872 Setr += "0, ";
873 else
874 Setr += "1, ";
875 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
876 Setr += "1)";
877 else
878 Setr += "0)";
879 }
880 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000881 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000882 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000883 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000884 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000885 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000886}
Chris Lattner8a12c272007-10-11 18:38:32 +0000887
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000888static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
889 std::string &typedefString) {
890 typedefString += "#ifndef _REWRITER_typedef_";
891 typedefString += ForwardDecl->getNameAsString();
892 typedefString += "\n";
893 typedefString += "#define _REWRITER_typedef_";
894 typedefString += ForwardDecl->getNameAsString();
895 typedefString += "\n";
896 typedefString += "typedef struct objc_object ";
897 typedefString += ForwardDecl->getNameAsString();
898 typedefString += ";\n#endif\n";
899}
900
Douglas Gregor375bb142011-12-27 22:43:10 +0000901void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000902 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000903 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000904 const char *startBuf = SM->getCharacterData(startLoc);
905 const char *semiPtr = strchr(startBuf, ';');
906 // Replace the @class with typedefs corresponding to the classes.
907 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
908}
909
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000910void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000911 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000912 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000913 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000914 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000915 // Translate to typedef's that forward reference structs with the same name
916 // as the class. As a convenience, we include the original declaration
917 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000918 typedefString += "// @class ";
919 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000920 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000921 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000923 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000924 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000925 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000926}
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000928void RewriteObjC::RewriteForwardClassDecl(
929 const llvm::SmallVector<Decl*, 8> &D) {
930 std::string typedefString;
931 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000932 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000933 if (i == 0) {
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000940 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000941}
942
Steve Naroffb29b4272008-04-14 22:03:09 +0000943void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000944 // When method is a synthesized one, such as a getter/setter there is
945 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000946 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000947 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000948 SourceLocation LocStart = Method->getLocStart();
949 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Chandler Carruth64211622011-07-25 21:09:52 +0000951 if (SM->getExpansionLineNumber(LocEnd) >
952 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000953 InsertText(LocStart, "#if 0\n");
954 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000955 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000956 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000957 }
958}
959
Mike Stump1eb44332009-09-09 15:08:12 +0000960void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000961 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Benjamin Kramerd999b372010-02-14 14:14:16 +0000963 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000964 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000965}
966
Steve Naroffb29b4272008-04-14 22:03:09 +0000967void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000968 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Steve Naroff423cb562007-10-30 13:30:57 +0000970 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000971 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000973 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
974 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +0000975 RewriteProperty(*I);
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000976
Mike Stump1eb44332009-09-09 15:08:12 +0000977 for (ObjCCategoryDecl::instmeth_iterator
978 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000979 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000980 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000981 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000982 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000983 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 RewriteMethodDeclaration(*I);
985
Steve Naroff423cb562007-10-30 13:30:57 +0000986 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000987 ReplaceText(CatDecl->getAtEndRange().getBegin(),
988 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000989}
990
Steve Naroffb29b4272008-04-14 22:03:09 +0000991void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000993 assert(PDecl->isThisDeclarationADefinition());
994
Steve Naroff752d6ef2007-10-30 16:42:30 +0000995 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000996 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000997
998 for (ObjCProtocolDecl::instmeth_iterator
999 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001000 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001001 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001002 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001003 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001004 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001005 RewriteMethodDeclaration(*I);
1006
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001007 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1008 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001009 RewriteProperty(*I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001010
Steve Naroff752d6ef2007-10-30 16:42:30 +00001011 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001012 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001013 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001014
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001015 // Must comment out @optional/@required
1016 const char *startBuf = SM->getCharacterData(LocStart);
1017 const char *endBuf = SM->getCharacterData(LocEnd);
1018 for (const char *p = startBuf; p < endBuf; p++) {
1019 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001020 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001023 }
1024 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001025 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001026 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001028 }
1029 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030}
1031
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001032void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1033 SourceLocation LocStart = (*D.begin())->getLocStart();
1034 if (LocStart.isInvalid())
1035 llvm_unreachable("Invalid SourceLocation");
1036 // FIXME: handle forward protocol that are declared across multiple lines.
1037 ReplaceText(LocStart, 0, "// ");
1038}
1039
1040void
1041RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1042 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001043 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001044 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001045 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001046 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001047}
1048
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001049void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1050 const FunctionType *&FPRetType) {
1051 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001052 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001053 else if (T->isFunctionPointerType() ||
1054 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001055 // needs special handling, since pointer-to-functions have special
1056 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001057 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001058 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001059 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001060 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001061 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001062 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001063 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001064 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001065 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001066 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001067 }
1068 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001069 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001070}
1071
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001072void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1073 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001074 std::string &ResultStr) {
1075 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1076 const FunctionType *FPRetType = 0;
1077 ResultStr += "\nstatic ";
1078 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001079 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001082 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001085 NameStr += "_I_";
1086 else
1087 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001088
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001090 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001091
1092 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001093 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001094 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001095 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001098 {
1099 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 int len = selString.size();
1101 for (int i = 0; i < len; i++)
1102 if (selString[i] == ':')
1103 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001104 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001106 // Remember this name for metadata emission
1107 MethodInternalNames[OMD] = NameStr;
1108 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001110 // Rewrite arguments
1111 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001113 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001114 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001115 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001116 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001117 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001118 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001119 ResultStr += "struct ";
1120 }
1121 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001122 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001123 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 }
1125 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001126 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001127 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001130 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001134 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1135 E = OMD->param_end(); PI != E; ++PI) {
1136 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001137 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001138 if (PDecl->getType()->isObjCQualifiedIdType()) {
1139 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001140 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001141 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001142 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001143 QualType QT = PDecl->getType();
1144 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001145 (void)convertBlockPointerToFunctionPointer(QT);
1146 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001147 ResultStr += Name;
1148 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001149 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001150 if (OMD->isVariadic())
1151 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001152 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 if (FPRetType) {
1155 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001156
Steve Naroff76e429d2008-07-16 14:40:40 +00001157 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001158 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001159 ResultStr += "(";
1160 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1161 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001162 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001163 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001164 ResultStr += ParamStr;
1165 }
1166 if (FT->isVariadic()) {
1167 if (FT->getNumArgs()) ResultStr += ", ";
1168 ResultStr += "...";
1169 }
1170 ResultStr += ")";
1171 } else {
1172 ResultStr += "()";
1173 }
1174 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001176void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1178 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001180 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001182 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1184 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001185 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001187 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001188 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001189 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001190 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001191
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001192 const char *startBuf = SM->getCharacterData(LocStart);
1193 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001194 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001195 }
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001197 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001198 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1199 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001200 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001201 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001202 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001203 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001204 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001205 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001206
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001207 const char *startBuf = SM->getCharacterData(LocStart);
1208 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001209 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001210 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001211 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001213 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001214 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001215 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001216 }
1217
Benjamin Kramerd999b372010-02-14 14:14:16 +00001218 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001219}
1220
Steve Naroffb29b4272008-04-14 22:03:09 +00001221void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001222 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001223 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001224 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001225 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001226 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001227 ResultStr += "\n";
1228 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001230 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001231 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001232 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001233 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001234 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001235 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001236 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001237 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001238
1239 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001241 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001242 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001243 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001244 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001245 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001246 for (ObjCInterfaceDecl::classmeth_iterator
1247 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001248 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001249 RewriteMethodDeclaration(*I);
1250
Steve Naroff2feac5e2007-10-30 03:43:13 +00001251 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001252 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1253 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001254}
1255
John McCall4b9c2d22011-11-06 09:01:30 +00001256Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1257 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001258
John McCall4b9c2d22011-11-06 09:01:30 +00001259 // We just magically know some things about the structure of this
1260 // expression.
1261 ObjCMessageExpr *OldMsg =
1262 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1263 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001264
John McCall4b9c2d22011-11-06 09:01:30 +00001265 // Because the rewriter doesn't allow us to rewrite rewritten code,
1266 // we need to suppress rewriting the sub-statements.
1267 Expr *Base, *RHS;
1268 {
1269 DisableReplaceStmtScope S(*this);
1270
1271 // Rebuild the base expression if we have one.
1272 Base = 0;
1273 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1274 Base = OldMsg->getInstanceReceiver();
1275 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1276 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1277 }
1278
1279 // Rebuild the RHS.
1280 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1281 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1282 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1283 }
1284
1285 // TODO: avoid this copy.
1286 SmallVector<SourceLocation, 1> SelLocs;
1287 OldMsg->getSelectorLocs(SelLocs);
1288
Chad Rosier0774ba72012-01-06 20:05:14 +00001289 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001290 switch (OldMsg->getReceiverKind()) {
1291 case ObjCMessageExpr::Class:
1292 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1293 OldMsg->getValueKind(),
1294 OldMsg->getLeftLoc(),
1295 OldMsg->getClassReceiverTypeInfo(),
1296 OldMsg->getSelector(),
1297 SelLocs,
1298 OldMsg->getMethodDecl(),
1299 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001300 OldMsg->getRightLoc(),
1301 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001302 break;
1303
1304 case ObjCMessageExpr::Instance:
1305 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1306 OldMsg->getValueKind(),
1307 OldMsg->getLeftLoc(),
1308 Base,
1309 OldMsg->getSelector(),
1310 SelLocs,
1311 OldMsg->getMethodDecl(),
1312 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001313 OldMsg->getRightLoc(),
1314 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001315 break;
1316
1317 case ObjCMessageExpr::SuperClass:
1318 case ObjCMessageExpr::SuperInstance:
1319 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1320 OldMsg->getValueKind(),
1321 OldMsg->getLeftLoc(),
1322 OldMsg->getSuperLoc(),
1323 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1324 OldMsg->getSuperType(),
1325 OldMsg->getSelector(),
1326 SelLocs,
1327 OldMsg->getMethodDecl(),
1328 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001329 OldMsg->getRightLoc(),
1330 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001331 break;
1332 }
1333
1334 Stmt *Replacement = SynthMessageExpr(NewMsg);
1335 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1336 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001337}
1338
John McCall4b9c2d22011-11-06 09:01:30 +00001339Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1340 SourceRange OldRange = PseudoOp->getSourceRange();
1341
1342 // We just magically know some things about the structure of this
1343 // expression.
1344 ObjCMessageExpr *OldMsg =
1345 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1346
1347 // Because the rewriter doesn't allow us to rewrite rewritten code,
1348 // we need to suppress rewriting the sub-statements.
1349 Expr *Base = 0;
1350 {
1351 DisableReplaceStmtScope S(*this);
1352
1353 // Rebuild the base expression if we have one.
1354 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1355 Base = OldMsg->getInstanceReceiver();
1356 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1357 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001358 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001359 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001360
John McCall4b9c2d22011-11-06 09:01:30 +00001361 // Intentionally empty.
1362 SmallVector<SourceLocation, 1> SelLocs;
1363 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001364
Chad Rosier0774ba72012-01-06 20:05:14 +00001365 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001366 switch (OldMsg->getReceiverKind()) {
1367 case ObjCMessageExpr::Class:
1368 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1369 OldMsg->getValueKind(),
1370 OldMsg->getLeftLoc(),
1371 OldMsg->getClassReceiverTypeInfo(),
1372 OldMsg->getSelector(),
1373 SelLocs,
1374 OldMsg->getMethodDecl(),
1375 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001376 OldMsg->getRightLoc(),
1377 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001378 break;
1379
1380 case ObjCMessageExpr::Instance:
1381 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1382 OldMsg->getValueKind(),
1383 OldMsg->getLeftLoc(),
1384 Base,
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
1388 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001391 break;
1392
1393 case ObjCMessageExpr::SuperClass:
1394 case ObjCMessageExpr::SuperInstance:
1395 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1396 OldMsg->getValueKind(),
1397 OldMsg->getLeftLoc(),
1398 OldMsg->getSuperLoc(),
1399 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1400 OldMsg->getSuperType(),
1401 OldMsg->getSelector(),
1402 SelLocs,
1403 OldMsg->getMethodDecl(),
1404 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001405 OldMsg->getRightLoc(),
1406 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001407 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001408 }
John McCall4b9c2d22011-11-06 09:01:30 +00001409
1410 Stmt *Replacement = SynthMessageExpr(NewMsg);
1411 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1412 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001413}
1414
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415/// SynthCountByEnumWithState - To print:
1416/// ((unsigned int (*)
1417/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001418/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001419/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001420/// "countByEnumeratingWithState:objects:count:"),
1421/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001422/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001423///
Steve Naroffb29b4272008-04-14 22:03:09 +00001424void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001425 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1426 "id *, unsigned int))(void *)objc_msgSend)";
1427 buf += "\n\t\t";
1428 buf += "((id)l_collection,\n\t\t";
1429 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1430 buf += "\n\t\t";
1431 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001432 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001433}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001434
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001435/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1436/// statement to exit to its outer synthesized loop.
1437///
Steve Naroffb29b4272008-04-14 22:03:09 +00001438Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001439 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1440 return S;
1441 // replace break with goto __break_label
1442 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001444 SourceLocation startLoc = S->getLocStart();
1445 buf = "goto __break_label_";
1446 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001447 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001448
1449 return 0;
1450}
1451
1452/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1453/// statement to continue with its inner synthesized loop.
1454///
Steve Naroffb29b4272008-04-14 22:03:09 +00001455Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1457 return S;
1458 // replace continue with goto __continue_label
1459 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 SourceLocation startLoc = S->getLocStart();
1462 buf = "goto __continue_label_";
1463 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001464 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001466 return 0;
1467}
1468
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001469/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001470/// It rewrites:
1471/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001473/// Into:
1474/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001475/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001476/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001477/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001478/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001479/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001480/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001481/// if (limit) {
1482/// unsigned long startMutations = *enumState.mutationsPtr;
1483/// do {
1484/// unsigned long counter = 0;
1485/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001486/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001488/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001489/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001490/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001491/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001492/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001493/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001494/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001495/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001496/// }
1497/// else
1498/// elem = nil;
1499/// }
1500///
Steve Naroffb29b4272008-04-14 22:03:09 +00001501Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001502 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001503 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001504 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001505 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001506 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001507 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001509 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001511 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001512 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001513 std::string buf;
1514 buf = "\n{\n\t";
1515 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1516 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001517 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001518 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001519 if (ElementType->isObjCQualifiedIdType() ||
1520 ElementType->isObjCQualifiedInterfaceType())
1521 // Simply use 'id' for all qualified types.
1522 elementTypeAsString = "id";
1523 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001524 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001525 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001526 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001527 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001528 buf += elementName;
1529 buf += ";\n\t";
1530 }
Chris Lattner06767512008-04-08 05:52:18 +00001531 else {
1532 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001533 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001534 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1535 if (VD->getType()->isObjCQualifiedIdType() ||
1536 VD->getType()->isObjCQualifiedInterfaceType())
1537 // Simply use 'id' for all qualified types.
1538 elementTypeAsString = "id";
1539 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001540 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001541 }
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 // struct __objcFastEnumerationState enumState = { 0 };
1544 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001545 // id __rw_items[16];
1546 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001547 // id l_collection = (id)
1548 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001549 // Find start location of 'collection' the hard way!
1550 const char *startCollectionBuf = startBuf;
1551 startCollectionBuf += 3; // skip 'for'
1552 startCollectionBuf = strchr(startCollectionBuf, '(');
1553 startCollectionBuf++; // skip '('
1554 // find 'in' and skip it.
1555 while (*startCollectionBuf != ' ' ||
1556 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1557 (*(startCollectionBuf+3) != ' ' &&
1558 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1559 startCollectionBuf++;
1560 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
1562 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001563 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001565 SourceLocation rightParenLoc = S->getRParenLoc();
1566 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001567 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001569
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001571 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 // ((unsigned int (*)
1575 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001576 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001578 // "countByEnumeratingWithState:objects:count:"),
1579 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001580 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001581 buf += "unsigned long limit =\n\t\t";
1582 SynthCountByEnumWithState(buf);
1583 buf += ";\n\t";
1584 /// if (limit) {
1585 /// unsigned long startMutations = *enumState.mutationsPtr;
1586 /// do {
1587 /// unsigned long counter = 0;
1588 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001589 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001590 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001591 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592 buf += "if (limit) {\n\t";
1593 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1594 buf += "do {\n\t\t";
1595 buf += "unsigned long counter = 0;\n\t\t";
1596 buf += "do {\n\t\t\t";
1597 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1598 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1599 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001600 buf += " = (";
1601 buf += elementTypeAsString;
1602 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001604 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001608 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001609 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001610 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001612 /// }
1613 /// else
1614 /// elem = nil;
1615 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001616 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001617 buf = ";\n\t";
1618 buf += "__continue_label_";
1619 buf += utostr(ObjCBcLabelNo.back());
1620 buf += ": ;";
1621 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001622 buf += "} while (counter < limit);\n\t";
1623 buf += "} while (limit = ";
1624 SynthCountByEnumWithState(buf);
1625 buf += ");\n\t";
1626 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001627 buf += " = ((";
1628 buf += elementTypeAsString;
1629 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001630 buf += "__break_label_";
1631 buf += utostr(ObjCBcLabelNo.back());
1632 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 buf += "}\n\t";
1634 buf += "else\n\t\t";
1635 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001636 buf += " = ((";
1637 buf += elementTypeAsString;
1638 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001641 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001642 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001643 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001644 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001645 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001646 } else {
1647 /* Need to treat single statements specially. For example:
1648 *
1649 * for (A *a in b) if (stuff()) break;
1650 * for (A *a in b) xxxyy;
1651 *
1652 * The following code simply scans ahead to the semi to find the actual end.
1653 */
1654 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1655 const char *semiBuf = strchr(stmtBuf, ';');
1656 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001657 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001658 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001659 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001660 Stmts.pop_back();
1661 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001662 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001663}
1664
Mike Stump1eb44332009-09-09 15:08:12 +00001665/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001666/// This routine rewrites @synchronized(expr) stmt;
1667/// into:
1668/// objc_sync_enter(expr);
1669/// @try stmt @finally { objc_sync_exit(expr); }
1670///
Steve Naroffb29b4272008-04-14 22:03:09 +00001671Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001672 // Get the start location and compute the semi location.
1673 SourceLocation startLoc = S->getLocStart();
1674 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001676 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001677
1678 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001679 buf = "objc_sync_enter((id)";
1680 const char *lparenBuf = startBuf;
1681 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001682 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001683 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1684 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001685 // been rewritten! (which implies the SourceLocation's are invalid).
1686 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001687 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001688 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001689 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001690 buf = ");\n";
1691 // declare a new scope with two variables, _stack and _rethrow.
1692 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1693 buf += "int buf[18/*32-bit i386*/];\n";
1694 buf += "char *pointers[4];} _stack;\n";
1695 buf += "id volatile _rethrow = 0;\n";
1696 buf += "objc_exception_try_enter(&_stack);\n";
1697 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001698 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001699 startLoc = S->getSynchBody()->getLocEnd();
1700 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001701
Steve Naroffc7089f12008-08-19 13:04:19 +00001702 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001703 SourceLocation lastCurlyLoc = startLoc;
1704 buf = "}\nelse {\n";
1705 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001706 buf += "}\n";
1707 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001708 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001709
1710 std::string syncBuf;
1711 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001712
1713 Expr *syncExpr = S->getSynchExpr();
1714 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1715 ? CK_BitCast :
1716 syncExpr->getType()->isBlockPointerType()
1717 ? CK_BlockPointerToObjCPointerCast
1718 : CK_CPointerToObjCPointerCast;
1719 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1720 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001721 std::string syncExprBufS;
1722 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001723 syncExpr->printPretty(syncExprBuf, *Context, 0,
1724 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001725 syncBuf += syncExprBuf.str();
1726 syncBuf += ");";
1727
1728 buf += syncBuf;
1729 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001730 buf += "}\n";
1731 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001732
Benjamin Kramerd999b372010-02-14 14:14:16 +00001733 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001734
1735 bool hasReturns = false;
1736 HasReturnStmts(S->getSynchBody(), hasReturns);
1737 if (hasReturns)
1738 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1739
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001740 return 0;
1741}
1742
Steve Naroffb85e77a2009-12-05 21:43:12 +00001743void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1744{
Steve Naroff8c565152008-12-05 17:03:39 +00001745 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001746 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001747 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001748 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001749
Steve Naroffb85e77a2009-12-05 21:43:12 +00001750 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001751 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001752 TryFinallyContainsReturnDiag);
1753 }
1754 return;
1755}
1756
Steve Naroffb85e77a2009-12-05 21:43:12 +00001757void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1758{
1759 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001760 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001761 if (*CI)
1762 HasReturnStmts(*CI, hasReturns);
1763
1764 if (isa<ReturnStmt>(S))
1765 hasReturns = true;
1766 return;
1767}
1768
1769void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1770 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001771 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001772 if (*CI) {
1773 RewriteTryReturnStmts(*CI);
1774 }
1775 if (isa<ReturnStmt>(S)) {
1776 SourceLocation startLoc = S->getLocStart();
1777 const char *startBuf = SM->getCharacterData(startLoc);
1778
1779 const char *semiBuf = strchr(startBuf, ';');
1780 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001781 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001782
1783 std::string buf;
1784 buf = "{ objc_exception_try_exit(&_stack); return";
1785
Benjamin Kramerd999b372010-02-14 14:14:16 +00001786 ReplaceText(startLoc, 6, buf);
1787 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001788 }
1789 return;
1790}
1791
1792void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1793 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001794 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001795 if (*CI) {
1796 RewriteSyncReturnStmts(*CI, syncExitBuf);
1797 }
1798 if (isa<ReturnStmt>(S)) {
1799 SourceLocation startLoc = S->getLocStart();
1800 const char *startBuf = SM->getCharacterData(startLoc);
1801
1802 const char *semiBuf = strchr(startBuf, ';');
1803 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001804 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001805
1806 std::string buf;
1807 buf = "{ objc_exception_try_exit(&_stack);";
1808 buf += syncExitBuf;
1809 buf += " return";
1810
Benjamin Kramerd999b372010-02-14 14:14:16 +00001811 ReplaceText(startLoc, 6, buf);
1812 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001813 }
1814 return;
1815}
1816
Steve Naroffb29b4272008-04-14 22:03:09 +00001817Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001818 // Get the start location and compute the semi location.
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Steve Naroff75730982007-11-07 04:08:17 +00001822 assert((*startBuf == '@') && "bogus @try location");
1823
1824 std::string buf;
1825 // declare a new scope with two variables, _stack and _rethrow.
1826 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1827 buf += "int buf[18/*32-bit i386*/];\n";
1828 buf += "char *pointers[4];} _stack;\n";
1829 buf += "id volatile _rethrow = 0;\n";
1830 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001831 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001832
Benjamin Kramerd999b372010-02-14 14:14:16 +00001833 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff75730982007-11-07 04:08:17 +00001835 startLoc = S->getTryBody()->getLocEnd();
1836 startBuf = SM->getCharacterData(startLoc);
1837
1838 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Steve Naroff75730982007-11-07 04:08:17 +00001840 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001841 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001842 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001843 buf = " /* @catch begin */ else {\n";
1844 buf += " id _caught = objc_exception_extract(&_stack);\n";
1845 buf += " objc_exception_try_enter (&_stack);\n";
1846 buf += " if (_setjmp(_stack.buf))\n";
1847 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1848 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001849
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001851 } else { /* no catch list */
1852 buf = "}\nelse {\n";
1853 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1854 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001855 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001856 }
Steve Naroff75730982007-11-07 04:08:17 +00001857 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001858 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1859 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001860 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001861
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001862 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001863 buf = "if ("; // we are generating code for the first catch clause
1864 else
1865 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001866 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001867 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Steve Naroff75730982007-11-07 04:08:17 +00001869 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Steve Naroff75730982007-11-07 04:08:17 +00001871 const char *lParenLoc = strchr(startBuf, '(');
1872
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001873 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001874 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001875 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001876 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1877 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001878 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001879 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001880 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Steve Naroffe12e6922008-02-01 20:02:07 +00001882 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001883 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001884 } else if (catchDecl) {
1885 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001886 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001887 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001888 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001889 } else if (const ObjCObjectPointerType *Ptr =
1890 t->getAs<ObjCObjectPointerType>()) {
1891 // Should be a pointer to a class.
1892 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1893 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001894 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001895 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001896 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001897 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001898 }
1899 }
1900 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001901 lastCatchBody = Catch->getCatchBody();
1902 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001903 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1904 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1905 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1906 assert((*rParenBuf == ')') && "bogus @catch paren location");
1907 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Mike Stump1eb44332009-09-09 15:08:12 +00001909 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001910 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001911 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001912 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001913 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001914 }
Steve Naroff75730982007-11-07 04:08:17 +00001915 }
1916 // Complete the catch list...
1917 if (lastCatchBody) {
1918 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001919 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1920 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001921
Steve Naroff378f47a2008-09-11 15:29:03 +00001922 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001923 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001924 buf = "} /* last catch end */\n";
1925 buf += "else {\n";
1926 buf += " _rethrow = _caught;\n";
1927 buf += " objc_exception_try_exit(&_stack);\n";
1928 buf += "} } /* @catch end */\n";
1929 if (!S->getFinallyStmt())
1930 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Steve Naroff75730982007-11-07 04:08:17 +00001933 // Set lastCurlyLoc
1934 lastCurlyLoc = lastCatchBody->getLocEnd();
1935 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001936 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001937 startLoc = finalStmt->getLocStart();
1938 startBuf = SM->getCharacterData(startLoc);
1939 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Benjamin Kramerd999b372010-02-14 14:14:16 +00001941 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Steve Naroff75730982007-11-07 04:08:17 +00001943 Stmt *body = finalStmt->getFinallyBody();
1944 SourceLocation startLoc = body->getLocStart();
1945 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001946 assert(*SM->getCharacterData(startLoc) == '{' &&
1947 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001948 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001949 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001951 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001952 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001953 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001954 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff75730982007-11-07 04:08:17 +00001956 // Set lastCurlyLoc
1957 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroff8c565152008-12-05 17:03:39 +00001959 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001960 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001961 } else { /* no finally clause - make sure we synthesize an implicit one */
1962 buf = "{ /* implicit finally clause */\n";
1963 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1964 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1965 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001966 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001967
1968 // Now check for any return/continue/go statements within the @try.
1969 // The implicit finally clause won't called if the @try contains any
1970 // jump statements.
1971 bool hasReturns = false;
1972 HasReturnStmts(S->getTryBody(), hasReturns);
1973 if (hasReturns)
1974 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001975 }
1976 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001977 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001978 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001979 return 0;
1980}
1981
Mike Stump1eb44332009-09-09 15:08:12 +00001982// This can't be done with ReplaceStmt(S, ThrowExpr), since
1983// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001984// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001985Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001986 // Get the start location and compute the semi location.
1987 SourceLocation startLoc = S->getLocStart();
1988 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Steve Naroff2bd03922007-11-07 15:32:26 +00001990 assert((*startBuf == '@') && "bogus @throw location");
1991
1992 std::string buf;
1993 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001994 if (S->getThrowExpr())
1995 buf = "objc_exception_throw(";
1996 else // add an implicit argument
1997 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001999 // handle "@ throw" correctly.
2000 const char *wBuf = strchr(startBuf, 'w');
2001 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Steve Naroff2bd03922007-11-07 15:32:26 +00002004 const char *semiBuf = strchr(startBuf, ';');
2005 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002006 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002007 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002008 return 0;
2009}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002010
Steve Naroffb29b4272008-04-14 22:03:09 +00002011Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002012 // Create a new string expression.
2013 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002014 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002015 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002016 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002017 StringLiteral::Ascii, false,
2018 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002019 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Chris Lattner07506182007-11-30 22:53:43 +00002021 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002022 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002023 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002024}
2025
Steve Naroffb29b4272008-04-14 22:03:09 +00002026Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002027 if (!SelGetUidFunctionDecl)
2028 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002029 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2030 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002031 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002032 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002033 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002034 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002035 StringLiteral::Ascii, false,
2036 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002037 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2038 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002039 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002040 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002041 return SelExp;
2042}
2043
Steve Naroffb29b4272008-04-14 22:03:09 +00002044CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002045 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2046 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002047 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002048 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroffebf2b562007-10-23 23:50:29 +00002050 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002051 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2052 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroffebf2b562007-10-23 23:50:29 +00002054 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002055 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002056 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002057 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002058 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002059
John McCall183700f2009-09-21 23:43:11 +00002060 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002062 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002063 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002064 FT->getCallResultType(*Context),
2065 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002066 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002067}
2068
Steve Naroffd5255f52007-11-01 13:24:47 +00002069static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2070 const char *&startRef, const char *&endRef) {
2071 while (startBuf < endBuf) {
2072 if (*startBuf == '<')
2073 startRef = startBuf; // mark the start.
2074 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002075 if (startRef && *startRef == '<') {
2076 endRef = startBuf; // mark the end.
2077 return true;
2078 }
2079 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002080 }
2081 startBuf++;
2082 }
2083 return false;
2084}
2085
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002086static void scanToNextArgument(const char *&argRef) {
2087 int angle = 0;
2088 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2089 if (*argRef == '<')
2090 angle++;
2091 else if (*argRef == '>')
2092 angle--;
2093 argRef++;
2094 }
2095 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2096}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002097
Steve Naroffb29b4272008-04-14 22:03:09 +00002098bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002099 if (T->isObjCQualifiedIdType())
2100 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002101 if (const PointerType *PT = T->getAs<PointerType>()) {
2102 if (PT->getPointeeType()->isObjCQualifiedIdType())
2103 return true;
2104 }
2105 if (T->isObjCObjectPointerType()) {
2106 T = T->getPointeeType();
2107 return T->isObjCQualifiedInterfaceType();
2108 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002109 if (T->isArrayType()) {
2110 QualType ElemTy = Context->getBaseElementType(T);
2111 return needToScanForQualifiers(ElemTy);
2112 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002113 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002114}
2115
Steve Naroff4f95b752008-07-29 18:15:38 +00002116void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2117 QualType Type = E->getType();
2118 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002119 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
Steve Naroffcda658e2008-11-19 21:15:47 +00002121 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2122 Loc = ECE->getLParenLoc();
2123 EndLoc = ECE->getRParenLoc();
2124 } else {
2125 Loc = E->getLocStart();
2126 EndLoc = E->getLocEnd();
2127 }
2128 // This will defend against trying to rewrite synthesized expressions.
2129 if (Loc.isInvalid() || EndLoc.isInvalid())
2130 return;
2131
Steve Naroff4f95b752008-07-29 18:15:38 +00002132 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002133 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002134 const char *startRef = 0, *endRef = 0;
2135 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2136 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002137 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2138 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002139 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002140 InsertText(LessLoc, "/*");
2141 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002142 }
2143 }
2144}
2145
Steve Naroffb29b4272008-04-14 22:03:09 +00002146void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002147 SourceLocation Loc;
2148 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002149 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002150 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2151 Loc = VD->getLocation();
2152 Type = VD->getType();
2153 }
2154 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2155 Loc = FD->getLocation();
2156 // Check for ObjC 'id' and class types that have been adorned with protocol
2157 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002158 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002159 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002160 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002161 if (!proto)
2162 return;
2163 Type = proto->getResultType();
2164 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002165 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2166 Loc = FD->getLocation();
2167 Type = FD->getType();
2168 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002169 else
2170 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002172 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 const char *endBuf = SM->getCharacterData(Loc);
2176 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002177 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002178 startBuf--; // scan backward (from the decl location) for return type.
2179 const char *startRef = 0, *endRef = 0;
2180 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2181 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002182 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2183 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002184 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002185 InsertText(LessLoc, "/*");
2186 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002187 }
2188 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 if (!proto)
2190 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002191 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002192 const char *startBuf = SM->getCharacterData(Loc);
2193 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002194 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2195 if (needToScanForQualifiers(proto->getArgType(i))) {
2196 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Steve Naroffd5255f52007-11-01 13:24:47 +00002198 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002199 // scan forward (from the decl location) for argument types.
2200 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002201 const char *startRef = 0, *endRef = 0;
2202 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2203 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002204 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002205 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002206 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002207 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002209 InsertText(LessLoc, "/*");
2210 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002211 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002212 startBuf = ++endBuf;
2213 }
2214 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002215 // If the function name is derived from a macro expansion, then the
2216 // argument buffer will not follow the name. Need to speak with Chris.
2217 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002218 startBuf++; // scan forward (from the decl location) for argument types.
2219 startBuf++;
2220 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002221 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002222}
2223
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002224void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2225 QualType QT = ND->getType();
2226 const Type* TypePtr = QT->getAs<Type>();
2227 if (!isa<TypeOfExprType>(TypePtr))
2228 return;
2229 while (isa<TypeOfExprType>(TypePtr)) {
2230 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2231 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2232 TypePtr = QT->getAs<Type>();
2233 }
2234 // FIXME. This will not work for multiple declarators; as in:
2235 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002236 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002237 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2238 const char *startBuf = SM->getCharacterData(DeclLoc);
2239 if (ND->getInit()) {
2240 std::string Name(ND->getNameAsString());
2241 TypeAsString += " " + Name + " = ";
2242 Expr *E = ND->getInit();
2243 SourceLocation startLoc;
2244 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2245 startLoc = ECE->getLParenLoc();
2246 else
2247 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002248 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002249 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002250 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002251 }
2252 else {
2253 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002254 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002255 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002256 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002257 }
2258}
2259
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002260// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002261void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002262 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002263 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002264 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002265 QualType getFuncType =
2266 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002267 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002268 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002269 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002270 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002271 SC_Extern,
2272 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002273}
2274
Steve Naroffb29b4272008-04-14 22:03:09 +00002275void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002277 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002278 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002279 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002280 return;
2281 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002283}
2284
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002285void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002286 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002287 const char *argPtr = TypeString.c_str();
2288 if (!strchr(argPtr, '^')) {
2289 Str += TypeString;
2290 return;
2291 }
2292 while (*argPtr) {
2293 Str += (*argPtr == '^' ? '*' : *argPtr);
2294 argPtr++;
2295 }
2296}
2297
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002299void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2300 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002301 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002302 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002303 const char *argPtr = TypeString.c_str();
2304 int paren = 0;
2305 while (*argPtr) {
2306 switch (*argPtr) {
2307 case '(':
2308 Str += *argPtr;
2309 paren++;
2310 break;
2311 case ')':
2312 Str += *argPtr;
2313 paren--;
2314 break;
2315 case '^':
2316 Str += '*';
2317 if (paren == 1)
2318 Str += VD->getNameAsString();
2319 break;
2320 default:
2321 Str += *argPtr;
2322 break;
2323 }
2324 argPtr++;
2325 }
2326}
2327
2328
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002329void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2330 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2331 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2332 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2333 if (!proto)
2334 return;
2335 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002336 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002337 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002338 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002339 FdStr += "(";
2340 unsigned numArgs = proto->getNumArgs();
2341 for (unsigned i = 0; i < numArgs; i++) {
2342 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002343 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002344 if (i+1 < numArgs)
2345 FdStr += ", ";
2346 }
2347 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002348 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002349 CurFunctionDeclToDeclareForBlock = 0;
2350}
2351
Steve Naroffc0a123c2008-03-11 17:37:02 +00002352// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002353void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002354 if (SuperContructorFunctionDecl)
2355 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002356 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002357 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002358 QualType argT = Context->getObjCIdType();
2359 assert(!argT.isNull() && "Can't find 'id' type");
2360 ArgTys.push_back(argT);
2361 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002362 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2363 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002364 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002365 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002366 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002367 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002368 SC_Extern,
2369 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002370}
2371
Steve Naroff09b266e2007-10-30 23:14:51 +00002372// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002373void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002375 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'id' type");
2378 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002379 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002380 assert(!argT.isNull() && "Can't find 'SEL' type");
2381 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002382 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2383 &ArgTys[0], ArgTys.size(),
2384 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002385 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002386 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002387 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002388 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002389 SC_Extern,
2390 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002391}
2392
Steve Naroff874e2322007-11-15 10:28:18 +00002393// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002394void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002395 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002396 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002397 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002398 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002399 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002400 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2401 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2402 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002404 assert(!argT.isNull() && "Can't find 'SEL' type");
2405 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002406 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2407 &ArgTys[0], ArgTys.size(),
2408 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002409 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002410 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002411 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002412 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002413 SC_Extern,
2414 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002415}
2416
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002417// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002418void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002420 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002427 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002428 &ArgTys[0], ArgTys.size(),
2429 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002430 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002431 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002432 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002433 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002434 SC_Extern,
2435 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002436}
2437
Mike Stump1eb44332009-09-09 15:08:12 +00002438// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002439// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002440void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002441 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002443 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002444 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002445 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002446 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002447 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2448 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2449 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002450 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002451 assert(!argT.isNull() && "Can't find 'SEL' type");
2452 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002453 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002454 &ArgTys[0], ArgTys.size(),
2455 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002456 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002457 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002458 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002459 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002460 SC_Extern,
2461 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002462}
2463
Steve Naroff1284db82008-05-08 22:02:18 +00002464// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002465void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002467 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002469 assert(!argT.isNull() && "Can't find 'id' type");
2470 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002472 assert(!argT.isNull() && "Can't find 'SEL' type");
2473 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002474 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2475 &ArgTys[0], ArgTys.size(),
2476 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002477 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002478 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002479 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002480 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002481 SC_Extern,
2482 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002483}
2484
Steve Naroff09b266e2007-10-30 23:14:51 +00002485// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002486void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002487 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002488 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002489 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002490 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2491 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002492 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002493 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002494 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002495 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002496 SC_Extern,
2497 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002498}
2499
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002500// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2501void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2502 IdentifierInfo *getSuperClassIdent =
2503 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002504 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002505 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002506 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2507 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002508 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002509 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002510 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002511 getSuperClassIdent,
2512 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002513 SC_Extern,
2514 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002515 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002516}
2517
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002518// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002519void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002520 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002521 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002522 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002523 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2524 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002525 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002526 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002527 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002528 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002529 SC_Extern,
2530 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002531}
2532
Steve Naroffb29b4272008-04-14 22:03:09 +00002533Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002534 QualType strType = getConstantStringStructType();
2535
2536 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002537
2538 std::string tmpName = InFileName;
2539 unsigned i;
2540 for (i=0; i < tmpName.length(); i++) {
2541 char c = tmpName.at(i);
2542 // replace any non alphanumeric characters with '_'.
2543 if (!isalpha(c) && (c < '0' || c > '9'))
2544 tmpName[i] = '_';
2545 }
2546 S += tmpName;
2547 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002548 S += utostr(NumObjCStringLiterals++);
2549
Steve Naroffba92b2e2008-03-27 22:29:16 +00002550 Preamble += "static __NSConstantStringImpl " + S;
2551 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2552 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002553 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002554 std::string prettyBufS;
2555 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002556 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2557 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002558 Preamble += prettyBuf.str();
2559 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002560 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002561
2562 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002563 SourceLocation(), &Context->Idents.get(S),
2564 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002565 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002566 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002567 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002568 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002569 VK_RValue, OK_Ordinary,
2570 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002571 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002572 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002573 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002574 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002575 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002576 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002577}
2578
Steve Naroff874e2322007-11-15 10:28:18 +00002579// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002580QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002581 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002582 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002583 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002584 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002585 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Steve Naroff874e2322007-11-15 10:28:18 +00002587 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002588 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002589 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002590 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002591
Steve Naroff874e2322007-11-15 10:28:18 +00002592 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002593 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002594 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002595 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002596 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002597 FieldTypes[i], 0,
2598 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002599 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002600 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002601 }
Mike Stump1eb44332009-09-09 15:08:12 +00002602
Douglas Gregor838db382010-02-11 01:19:42 +00002603 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002604 }
2605 return Context->getTagDeclType(SuperStructDecl);
2606}
2607
Steve Naroffb29b4272008-04-14 22:03:09 +00002608QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002609 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002610 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002611 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002612 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002613 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002614
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002615 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002616 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002617 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002618 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002620 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002621 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002622 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002623
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002624 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002625 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002626 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2627 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002628 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002629 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002630 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002632 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002633 ICIS_NoInit));
Douglas Gregor44b43212008-12-11 16:49:14 +00002634 }
2635
Douglas Gregor838db382010-02-11 01:19:42 +00002636 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002637 }
2638 return Context->getTagDeclType(ConstantStringDecl);
2639}
2640
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00002641CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2642 QualType msgSendType,
2643 QualType returnType,
2644 SmallVectorImpl<QualType> &ArgTypes,
2645 SmallVectorImpl<Expr*> &MsgExprs,
2646 ObjCMethodDecl *Method) {
2647 // Create a reference to the objc_msgSend_stret() declaration.
2648 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2649 false, msgSendType,
2650 VK_LValue, SourceLocation());
2651 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2652 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2653 Context->getPointerType(Context->VoidTy),
2654 CK_BitCast, STDRE);
2655 // Now do the "normal" pointer to function cast.
2656 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2657 Method ? Method->isVariadic() : false);
2658 castType = Context->getPointerType(castType);
2659 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2660 cast);
2661
2662 // Don't forget the parens to enforce the proper binding.
2663 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2664
2665 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2666 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2667 MsgExprs.size(),
2668 FT->getResultType(), VK_RValue,
2669 SourceLocation());
2670 return STCE;
2671
2672}
2673
2674
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002675Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2676 SourceLocation StartLoc,
2677 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002678 if (!SelGetUidFunctionDecl)
2679 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002680 if (!MsgSendFunctionDecl)
2681 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002682 if (!MsgSendSuperFunctionDecl)
2683 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002684 if (!MsgSendStretFunctionDecl)
2685 SynthMsgSendStretFunctionDecl();
2686 if (!MsgSendSuperStretFunctionDecl)
2687 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002688 if (!MsgSendFpretFunctionDecl)
2689 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002690 if (!GetClassFunctionDecl)
2691 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002692 if (!GetSuperClassFunctionDecl)
2693 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002694 if (!GetMetaClassFunctionDecl)
2695 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Steve Naroff874e2322007-11-15 10:28:18 +00002697 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002698 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2699 // May need to use objc_msgSend_stret() as well.
2700 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002701 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2702 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002703 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002704 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002705 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002706 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002707 }
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Steve Naroff934f2762007-10-24 22:48:43 +00002709 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002710 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002711 switch (Exp->getReceiverKind()) {
2712 case ObjCMessageExpr::SuperClass: {
2713 MsgSendFlavor = MsgSendSuperFunctionDecl;
2714 if (MsgSendStretFlavor)
2715 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2716 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Douglas Gregor04badcf2010-04-21 00:45:42 +00002718 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Chris Lattner5f9e2722011-07-23 10:55:15 +00002720 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002721
Douglas Gregor04badcf2010-04-21 00:45:42 +00002722 // set the receiver to self, the first argument to all methods.
2723 InitExprs.push_back(
2724 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002725 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002727 false,
John McCallf89e55a2010-11-18 06:31:45 +00002728 Context->getObjCIdType(),
2729 VK_RValue,
2730 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002731 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002734 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002735 QualType argType = Context->getPointerType(Context->CharTy);
2736 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002737 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002738 StringLiteral::Ascii, false,
2739 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002740 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2741 &ClsExprs[0],
2742 ClsExprs.size(),
2743 StartLoc,
2744 EndLoc);
2745 // (Class)objc_getClass("CurrentClass")
2746 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2747 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002748 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002749 ClsExprs.clear();
2750 ClsExprs.push_back(ArgExpr);
2751 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2752 &ClsExprs[0], ClsExprs.size(),
2753 StartLoc, EndLoc);
2754
2755 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2756 // To turn off a warning, type-cast to 'id'
2757 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2758 NoTypeInfoCStyleCastExpr(Context,
2759 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002760 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 // struct objc_super
2762 QualType superType = getSuperStructType();
2763 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002764
Francois Pichet62ec1f22011-09-17 17:15:52 +00002765 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 SynthSuperContructorFunctionDecl();
2767 // Simulate a contructor call...
2768 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002769 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002770 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2772 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002773 superType, VK_LValue,
2774 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 // The code for super is a little tricky to prevent collision with
2776 // the structure definition in the header. The rewriter has it's own
2777 // internal definition (__rw_objc_super) that is uses. This is why
2778 // we need the cast below. For example:
2779 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2780 //
John McCall2de56d12010-08-25 11:45:40 +00002781 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002782 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002783 VK_RValue, OK_Ordinary,
2784 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002785 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2786 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002787 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002788 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002789 // (struct objc_super) { <exprs from above> }
2790 InitListExpr *ILE =
2791 new (Context) InitListExpr(*Context, SourceLocation(),
2792 &InitExprs[0], InitExprs.size(),
2793 SourceLocation());
2794 TypeSourceInfo *superTInfo
2795 = Context->getTrivialTypeSourceInfo(superType);
2796 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002797 superType, VK_LValue,
2798 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002799 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002800 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002801 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002802 VK_RValue, OK_Ordinary,
2803 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002804 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 MsgExprs.push_back(SuperRep);
2806 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002807 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808
2809 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002810 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 QualType argType = Context->getPointerType(Context->CharTy);
2812 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002813 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 IdentifierInfo *clsName = Class->getIdentifier();
2815 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002816 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002817 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002818 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2820 &ClsExprs[0],
2821 ClsExprs.size(),
2822 StartLoc, EndLoc);
2823 MsgExprs.push_back(Cls);
2824 break;
2825 }
2826
2827 case ObjCMessageExpr::SuperInstance:{
2828 MsgSendFlavor = MsgSendSuperFunctionDecl;
2829 if (MsgSendStretFlavor)
2830 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2831 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2832 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002833 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834
2835 InitExprs.push_back(
2836 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002837 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002838 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002839 false,
John McCallf89e55a2010-11-18 06:31:45 +00002840 Context->getObjCIdType(),
2841 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 ); // set the 'receiver'.
2843
2844 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002845 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002846 QualType argType = Context->getPointerType(Context->CharTy);
2847 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002848 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002849 StringLiteral::Ascii, false, argType,
2850 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2852 &ClsExprs[0],
2853 ClsExprs.size(),
2854 StartLoc, EndLoc);
2855 // (Class)objc_getClass("CurrentClass")
2856 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2857 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002858 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002859 ClsExprs.clear();
2860 ClsExprs.push_back(ArgExpr);
2861 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2862 &ClsExprs[0], ClsExprs.size(),
2863 StartLoc, EndLoc);
2864
2865 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2866 // To turn off a warning, type-cast to 'id'
2867 InitExprs.push_back(
2868 // set 'super class', using class_getSuperclass().
2869 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002870 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002871 // struct objc_super
2872 QualType superType = getSuperStructType();
2873 Expr *SuperRep;
2874
Francois Pichet62ec1f22011-09-17 17:15:52 +00002875 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002876 SynthSuperContructorFunctionDecl();
2877 // Simulate a contructor call...
2878 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002879 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002880 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2882 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002883 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002884 // The code for super is a little tricky to prevent collision with
2885 // the structure definition in the header. The rewriter has it's own
2886 // internal definition (__rw_objc_super) that is uses. This is why
2887 // we need the cast below. For example:
2888 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2889 //
John McCall2de56d12010-08-25 11:45:40 +00002890 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002891 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002892 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002893 SourceLocation());
2894 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2895 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002896 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002897 } else {
2898 // (struct objc_super) { <exprs from above> }
2899 InitListExpr *ILE =
2900 new (Context) InitListExpr(*Context, SourceLocation(),
2901 &InitExprs[0], InitExprs.size(),
2902 SourceLocation());
2903 TypeSourceInfo *superTInfo
2904 = Context->getTrivialTypeSourceInfo(superType);
2905 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002906 superType, VK_RValue, ILE,
2907 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002908 }
2909 MsgExprs.push_back(SuperRep);
2910 break;
2911 }
2912
2913 case ObjCMessageExpr::Instance: {
2914 // Remove all type-casts because it may contain objc-style types; e.g.
2915 // Foo<Proto> *.
2916 Expr *recExpr = Exp->getInstanceReceiver();
2917 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2918 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002919 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2920 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2921 ? CK_BlockPointerToObjCPointerCast
2922 : CK_CPointerToObjCPointerCast;
2923
Douglas Gregor04badcf2010-04-21 00:45:42 +00002924 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002925 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002926 MsgExprs.push_back(recExpr);
2927 break;
2928 }
2929 }
2930
Steve Naroffbeaf2992007-11-03 11:27:19 +00002931 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002932 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002933 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002934 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002935 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002936 StringLiteral::Ascii, false,
2937 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002938 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002939 &SelExprs[0], SelExprs.size(),
2940 StartLoc,
2941 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002942 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002943
Steve Naroff934f2762007-10-24 22:48:43 +00002944 // Now push any user supplied arguments.
2945 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002946 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002947 // Make all implicit casts explicit...ICE comes in handy:-)
2948 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2949 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002950 QualType type = ICE->getType();
2951 if (needToScanForQualifiers(type))
2952 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002953 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002954 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002955 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002956 CastKind CK;
2957 if (SubExpr->getType()->isIntegralType(*Context) &&
2958 type->isBooleanType()) {
2959 CK = CK_IntegralToBoolean;
2960 } else if (type->isObjCObjectPointerType()) {
2961 if (SubExpr->getType()->isBlockPointerType()) {
2962 CK = CK_BlockPointerToObjCPointerCast;
2963 } else if (SubExpr->getType()->isPointerType()) {
2964 CK = CK_CPointerToObjCPointerCast;
2965 } else {
2966 CK = CK_BitCast;
2967 }
2968 } else {
2969 CK = CK_BitCast;
2970 }
2971
2972 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002973 }
2974 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002975 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002976 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002977 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002978 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002979 CastKind CK;
2980 if (userExpr->getType()->isIntegralType(*Context)) {
2981 CK = CK_IntegralToPointer;
2982 } else if (userExpr->getType()->isBlockPointerType()) {
2983 CK = CK_BlockPointerToObjCPointerCast;
2984 } else if (userExpr->getType()->isPointerType()) {
2985 CK = CK_CPointerToObjCPointerCast;
2986 } else {
2987 CK = CK_BitCast;
2988 }
John McCall9d125032010-01-15 18:39:57 +00002989 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002990 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002993 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002994 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2995 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002996 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002997 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002998 }
Steve Naroffab972d32007-11-04 22:37:50 +00002999 // Generate the funky cast.
3000 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003001 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003002 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Steve Naroffab972d32007-11-04 22:37:50 +00003004 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003005 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3006 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3007 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003008 ArgTypes.push_back(Context->getObjCIdType());
3009 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003010 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003011 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003012 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3013 E = OMD->param_end(); PI != E; ++PI) {
3014 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003015 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003016 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003017 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003018 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003019 ArgTypes.push_back(t);
3020 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003021 returnType = Exp->getType();
3022 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003023 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003024 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003025 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003026 }
3027 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003028 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003029
Steve Naroffab972d32007-11-04 22:37:50 +00003030 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003031 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003032 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003033
Mike Stump1eb44332009-09-09 15:08:12 +00003034 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003035 // If we don't do this cast, we get the following bizarre warning/note:
3036 // xx.m:13: warning: function called through a non-compatible type
3037 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003038 cast = NoTypeInfoCStyleCastExpr(Context,
3039 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003040 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Steve Naroffab972d32007-11-04 22:37:50 +00003042 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003043 QualType castType =
3044 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3045 // If we don't have a method decl, force a variadic cast.
3046 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003047 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003048 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003049 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003050
3051 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003052 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003053
John McCall183700f2009-09-21 23:43:11 +00003054 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003055 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003056 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003057 FT->getResultType(), VK_RValue,
3058 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003059 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003060 if (MsgSendStretFlavor) {
3061 // We have the method which returns a struct/union. Must also generate
3062 // call to objc_msgSend_stret and hang both varieties on a conditional
3063 // expression which dictate which one to envoke depending on size of
3064 // method's return type.
Fariborz Jahanian9fc5b002012-06-28 21:20:35 +00003065
3066 CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3067 msgSendType, returnType,
3068 ArgTypes, MsgExprs,
3069 Exp->getMethodDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00003070
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003071 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003072 UnaryExprOrTypeTraitExpr *sizeofExpr =
3073 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3074 Context->getTrivialTypeSourceInfo(returnType),
3075 Context->getSizeType(), SourceLocation(),
3076 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003077 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3078 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3079 // For X86 it is more complicated and some kind of target specific routine
3080 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003081 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003082 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003083 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3084 llvm::APInt(IntSize, 8),
3085 Context->IntTy,
3086 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003087 BinaryOperator *lessThanExpr =
3088 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3089 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003090 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003091 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003092 new (Context) ConditionalOperator(lessThanExpr,
3093 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003094 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003095 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003096 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3097 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003098 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003099 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003100 return ReplacingStmt;
3101}
3102
Steve Naroffb29b4272008-04-14 22:03:09 +00003103Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003104 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3105 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003106
Steve Naroff934f2762007-10-24 22:48:43 +00003107 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003108 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003111 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003112}
3113
Steve Naroff621edce2009-04-29 16:37:50 +00003114// typedef struct objc_object Protocol;
3115QualType RewriteObjC::getProtocolType() {
3116 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003117 TypeSourceInfo *TInfo
3118 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003119 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003120 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003121 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003122 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003123 }
3124 return Context->getTypeDeclType(ProtocolTypeDecl);
3125}
3126
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003127/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003128/// a synthesized/forward data reference (to the protocol's metadata).
3129/// The forward references (and metadata) are generated in
3130/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003131Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003132 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3133 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003134 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003135 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003136 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003137 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3138 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003139 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003140 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003141 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003142 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003143 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003144 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003145 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003146 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003147 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003148 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003150}
3151
Mike Stump1eb44332009-09-09 15:08:12 +00003152bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003153 const char *endBuf) {
3154 while (startBuf < endBuf) {
3155 if (*startBuf == '#') {
3156 // Skip whitespace.
3157 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3158 ;
3159 if (!strncmp(startBuf, "if", strlen("if")) ||
3160 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3161 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3162 !strncmp(startBuf, "define", strlen("define")) ||
3163 !strncmp(startBuf, "undef", strlen("undef")) ||
3164 !strncmp(startBuf, "else", strlen("else")) ||
3165 !strncmp(startBuf, "elif", strlen("elif")) ||
3166 !strncmp(startBuf, "endif", strlen("endif")) ||
3167 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3168 !strncmp(startBuf, "include", strlen("include")) ||
3169 !strncmp(startBuf, "import", strlen("import")) ||
3170 !strncmp(startBuf, "include_next", strlen("include_next")))
3171 return true;
3172 }
3173 startBuf++;
3174 }
3175 return false;
3176}
3177
Fariborz Jahanian58457172011-12-05 18:43:13 +00003178/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003179/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003180void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003181 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003182 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003183 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003184 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003185 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003186 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003187 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003188 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003189 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003190 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003191 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Steve Narofffea763e82007-11-14 19:25:57 +00003193 const char *startBuf = SM->getCharacterData(LocStart);
3194 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003196 // If no ivars and no root or if its root, directly or indirectly,
3197 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003198 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003199 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003200 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003201 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003202 return;
3203 }
Mike Stump1eb44332009-09-09 15:08:12 +00003204
3205 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003206 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003207 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003208 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003209 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003210 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003211
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003212 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003213 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003214 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003215 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003216 // If the buffer contains preprocessor directives, we do more fine-grained
3217 // rewrites. This is intended to fix code that looks like (which occurs in
3218 // NSURL.h, for example):
3219 //
3220 // #ifdef XYZ
3221 // @interface Foo : NSObject
3222 // #else
3223 // @interface FooBar : NSObject
3224 // #endif
3225 // {
3226 // int i;
3227 // }
3228 // @end
3229 //
3230 // This clause is segregated to avoid breaking the common case.
3231 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003232 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003233 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003234 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003235 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003236
Chris Lattnercafeb352009-02-20 18:18:36 +00003237 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003238 // advance to the end of the referenced protocols.
3239 while (endHeader < cursor && *endHeader != '>') endHeader++;
3240 endHeader++;
3241 }
3242 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003243 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003244 } else {
3245 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003246 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003247 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003248 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003249 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003250 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003251 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003252 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003253 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003254
Steve Narofffea763e82007-11-14 19:25:57 +00003255 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003256 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003257 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003258 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003259 }
3260 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003261
Steve Narofffea763e82007-11-14 19:25:57 +00003262 // Now comment out any visibility specifiers.
3263 while (cursor < endBuf) {
3264 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003265 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003266 // Skip whitespace.
3267 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3268 /*scan*/;
3269
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003270 // FIXME: presence of @public, etc. inside comment results in
3271 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003272 if (!strncmp(cursor, "public", strlen("public")) ||
3273 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003274 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003275 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003276 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003277 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003278 // FIXME: If there are cases where '<' is used in ivar declaration part
3279 // of user code, then scan the ivar list and use needToScanForQualifiers
3280 // for type checking.
3281 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003282 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003283 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003284 cursor = strchr(cursor, '>');
3285 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003286 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003287 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003288 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003289 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003290 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003291 }
Steve Narofffea763e82007-11-14 19:25:57 +00003292 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003293 }
Steve Narofffea763e82007-11-14 19:25:57 +00003294 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003295 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003296 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003297 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003298 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003299 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003300 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003301 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003302 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003303 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003304 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003305 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003306 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003307 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003308}
3309
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003310//===----------------------------------------------------------------------===//
3311// Meta Data Emission
3312//===----------------------------------------------------------------------===//
3313
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003314
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003315/// RewriteImplementations - This routine rewrites all method implementations
3316/// and emits meta-data.
3317
Steve Narofface66252008-11-13 20:07:04 +00003318void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003319 int ClsDefCount = ClassImplementation.size();
3320 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003322 // Rewrite implemented methods
3323 for (int i = 0; i < ClsDefCount; i++)
3324 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003325
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003326 for (int i = 0; i < CatDefCount; i++)
3327 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003328}
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003330void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3331 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003332 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003333 assert(BlockByRefDeclNo.count(VD) &&
3334 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003335 if (def)
3336 ResultStr += "struct ";
3337 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003338 "_" + utostr(BlockByRefDeclNo[VD]) ;
3339}
3340
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003341static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3342 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3343 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3344 return false;
3345}
3346
Steve Naroff54055232008-10-27 17:20:55 +00003347std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003348 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003349 std::string Tag) {
3350 const FunctionType *AFT = CE->getFunctionType();
3351 QualType RT = AFT->getResultType();
3352 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003353 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003354 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003355
Steve Naroff54055232008-10-27 17:20:55 +00003356 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Douglas Gregor72564e72009-02-26 23:50:07 +00003358 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003359 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003360 // block (to reference imported block decl refs).
3361 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003362 } else if (BD->param_empty()) {
3363 S += "(" + StructRef + " *__cself)";
3364 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003365 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003366 assert(FT && "SynthesizeBlockFunc: No function proto");
3367 S += '(';
3368 // first add the implicit argument.
3369 S += StructRef + " *__cself, ";
3370 std::string ParamStr;
3371 for (BlockDecl::param_iterator AI = BD->param_begin(),
3372 E = BD->param_end(); AI != E; ++AI) {
3373 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003375 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003376 (void)convertBlockPointerToFunctionPointer(QT);
3377 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003378 S += ParamStr;
3379 }
3380 if (FT->isVariadic()) {
3381 if (!BD->param_empty()) S += ", ";
3382 S += "...";
3383 }
3384 S += ')';
3385 }
3386 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003387
Steve Naroff54055232008-10-27 17:20:55 +00003388 // Create local declarations to avoid rewriting all closure decl ref exprs.
3389 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003390 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003391 E = BlockByRefDecls.end(); I != E; ++I) {
3392 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003393 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003394 std::string TypeString;
3395 RewriteByRefString(TypeString, Name, (*I));
3396 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003397 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003398 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003399 }
Steve Naroff54055232008-10-27 17:20:55 +00003400 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003401 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003402 E = BlockByCopyDecls.end(); I != E; ++I) {
3403 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003404 // Handle nested closure invocation. For example:
3405 //
3406 // void (^myImportedClosure)(void);
3407 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003408 //
Steve Naroff54055232008-10-27 17:20:55 +00003409 // void (^anotherClosure)(void);
3410 // anotherClosure = ^(void) {
3411 // myImportedClosure(); // import and invoke the closure
3412 // };
3413 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003414 if (isTopLevelBlockPointerType((*I)->getType())) {
3415 RewriteBlockPointerTypeVariable(S, (*I));
3416 S += " = (";
3417 RewriteBlockPointerType(S, (*I)->getType());
3418 S += ")";
3419 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3420 }
3421 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003422 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003423 QualType QT = (*I)->getType();
3424 if (HasLocalVariableExternalStorage(*I))
3425 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003426 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003427 S += Name + " = __cself->" +
3428 (*I)->getNameAsString() + "; // bound by copy\n";
3429 }
Steve Naroff54055232008-10-27 17:20:55 +00003430 }
3431 std::string RewrittenStr = RewrittenBlockExprs[CE];
3432 const char *cstr = RewrittenStr.c_str();
3433 while (*cstr++ != '{') ;
3434 S += cstr;
3435 S += "\n";
3436 return S;
3437}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003438
Steve Naroff54055232008-10-27 17:20:55 +00003439std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003440 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003441 std::string Tag) {
3442 std::string StructRef = "struct " + Tag;
3443 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Steve Naroff54055232008-10-27 17:20:55 +00003445 S += funcName;
3446 S += "_block_copy_" + utostr(i);
3447 S += "(" + StructRef;
3448 S += "*dst, " + StructRef;
3449 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003450 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003451 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003452 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003453 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003454 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003455 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003456 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003457 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003458 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003459 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003460 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003461 else
3462 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003463 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003464 S += "}\n";
3465
Steve Naroff54055232008-10-27 17:20:55 +00003466 S += "\nstatic void __";
3467 S += funcName;
3468 S += "_block_dispose_" + utostr(i);
3469 S += "(" + StructRef;
3470 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003471 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003472 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003473 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003474 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003475 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003476 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003477 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003478 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003479 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003480 else
3481 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003482 }
Mike Stump1eb44332009-09-09 15:08:12 +00003483 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003484 return S;
3485}
3486
Steve Naroff01aec112009-12-06 21:14:13 +00003487std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3488 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003489 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003490 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003491
Steve Naroff54055232008-10-27 17:20:55 +00003492 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003493 S += " struct " + Desc;
3494 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003495
Steve Naroff01aec112009-12-06 21:14:13 +00003496 Constructor += "(void *fp, "; // Invoke function pointer.
3497 Constructor += "struct " + Desc; // Descriptor pointer.
3498 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Steve Naroff54055232008-10-27 17:20:55 +00003500 if (BlockDeclRefs.size()) {
3501 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003502 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003503 E = BlockByCopyDecls.end(); I != E; ++I) {
3504 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003505 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003506 std::string ArgName = "_" + FieldName;
3507 // Handle nested closure invocation. For example:
3508 //
3509 // void (^myImportedBlock)(void);
3510 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003511 //
Steve Naroff54055232008-10-27 17:20:55 +00003512 // void (^anotherBlock)(void);
3513 // anotherBlock = ^(void) {
3514 // myImportedBlock(); // import and invoke the closure
3515 // };
3516 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003517 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003518 S += "struct __block_impl *";
3519 Constructor += ", void *" + ArgName;
3520 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003521 QualType QT = (*I)->getType();
3522 if (HasLocalVariableExternalStorage(*I))
3523 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003524 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3525 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003526 Constructor += ", " + ArgName;
3527 }
3528 S += FieldName + ";\n";
3529 }
3530 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003531 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003532 E = BlockByRefDecls.end(); I != E; ++I) {
3533 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003534 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003535 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003536 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003537 std::string TypeString;
3538 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003539 TypeString += " *";
3540 FieldName = TypeString + FieldName;
3541 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003542 Constructor += ", " + ArgName;
3543 }
3544 S += FieldName + "; // by ref\n";
3545 }
3546 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003547 Constructor += ", int flags=0)";
3548 // Initialize all "by copy" arguments.
3549 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003550 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003551 E = BlockByCopyDecls.end(); I != E; ++I) {
3552 std::string Name = (*I)->getNameAsString();
3553 if (firsTime) {
3554 Constructor += " : ";
3555 firsTime = false;
3556 }
3557 else
3558 Constructor += ", ";
3559 if (isTopLevelBlockPointerType((*I)->getType()))
3560 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3561 else
3562 Constructor += Name + "(_" + Name + ")";
3563 }
3564 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003565 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003566 E = BlockByRefDecls.end(); I != E; ++I) {
3567 std::string Name = (*I)->getNameAsString();
3568 if (firsTime) {
3569 Constructor += " : ";
3570 firsTime = false;
3571 }
3572 else
3573 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003574 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003575 }
3576
3577 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003578 if (GlobalVarDecl)
3579 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3580 else
3581 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003582 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003583
Steve Naroff01aec112009-12-06 21:14:13 +00003584 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003585 } else {
3586 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003587 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003588 if (GlobalVarDecl)
3589 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3590 else
3591 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003592 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3593 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003594 }
3595 Constructor += " ";
3596 Constructor += "}\n";
3597 S += Constructor;
3598 S += "};\n";
3599 return S;
3600}
3601
Steve Naroff01aec112009-12-06 21:14:13 +00003602std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3603 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003604 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003605 unsigned hasCopy) {
3606 std::string S = "\nstatic struct " + DescTag;
3607
3608 S += " {\n unsigned long reserved;\n";
3609 S += " unsigned long Block_size;\n";
3610 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003611 S += " void (*copy)(struct ";
3612 S += ImplTag; S += "*, struct ";
3613 S += ImplTag; S += "*);\n";
3614
3615 S += " void (*dispose)(struct ";
3616 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003617 }
3618 S += "} ";
3619
3620 S += DescTag + "_DATA = { 0, sizeof(struct ";
3621 S += ImplTag + ")";
3622 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003623 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3624 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003625 }
3626 S += "};\n";
3627 return S;
3628}
3629
Steve Naroff54055232008-10-27 17:20:55 +00003630void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003631 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003632 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003633 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003634 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003635 bool RewriteSC = (GlobalVarDecl &&
3636 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003637 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003638 GlobalVarDecl->getType().getCVRQualifiers());
3639 if (RewriteSC) {
3640 std::string SC(" void __");
3641 SC += GlobalVarDecl->getNameAsString();
3642 SC += "() {}";
3643 InsertText(FunLocStart, SC);
3644 }
3645
Steve Naroff54055232008-10-27 17:20:55 +00003646 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003647 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3648 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003649 // Need to copy-in the inner copied-in variables not actually used in this
3650 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003651 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003652 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003653 ValueDecl *VD = Exp->getDecl();
3654 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003655 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003656 BlockByCopyDeclsPtrSet.insert(VD);
3657 BlockByCopyDecls.push_back(VD);
3658 }
John McCallf4b88a42012-03-10 09:33:50 +00003659 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003660 BlockByRefDeclsPtrSet.insert(VD);
3661 BlockByRefDecls.push_back(VD);
3662 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003663 // imported objects in the inner blocks not used in the outer
3664 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003665 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003666 VD->getType()->isObjCObjectPointerType() ||
3667 VD->getType()->isBlockPointerType())
3668 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003669 }
Steve Naroff54055232008-10-27 17:20:55 +00003670
Daniel Dunbar4087f272010-08-17 22:39:59 +00003671 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3672 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Steve Naroff01aec112009-12-06 21:14:13 +00003674 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003675
Benjamin Kramerd999b372010-02-14 14:14:16 +00003676 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003677
Steve Naroff01aec112009-12-06 21:14:13 +00003678 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003679
Benjamin Kramerd999b372010-02-14 14:14:16 +00003680 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003681
3682 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003683 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003684 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003685 }
Steve Naroff01aec112009-12-06 21:14:13 +00003686 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3687 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003688 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Steve Naroff54055232008-10-27 17:20:55 +00003690 BlockDeclRefs.clear();
3691 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003692 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003693 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003694 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003695 ImportedBlockDecls.clear();
3696 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003697 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003698 // Must insert any 'const/volatile/static here. Since it has been
3699 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003700 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003701 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003702 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003703 if (GlobalVarDecl->getType().isConstQualified())
3704 SC += "const ";
3705 if (GlobalVarDecl->getType().isVolatileQualified())
3706 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003707 if (GlobalVarDecl->getType().isRestrictQualified())
3708 SC += "restrict ";
3709 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003710 }
3711
Steve Naroff54055232008-10-27 17:20:55 +00003712 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003713 InnerDeclRefsCount.clear();
3714 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003715 RewrittenBlockExprs.clear();
3716}
3717
3718void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3719 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003720 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Steve Naroff54055232008-10-27 17:20:55 +00003722 SynthesizeBlockLiterals(FunLocStart, FuncName);
3723}
3724
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003725static void BuildUniqueMethodName(std::string &Name,
3726 ObjCMethodDecl *MD) {
3727 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003728 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003729 Name += "__" + MD->getSelector().getAsString();
3730 // Convert colons to underscores.
3731 std::string::size_type loc = 0;
3732 while ((loc = Name.find(":", loc)) != std::string::npos)
3733 Name.replace(loc, 1, "_");
3734}
3735
Steve Naroff54055232008-10-27 17:20:55 +00003736void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003737 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3738 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003739 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003740 std::string FuncName;
3741 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003742 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003743}
3744
3745void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003746 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003747 if (*CI) {
3748 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3749 GetBlockDeclRefExprs(CBE->getBody());
3750 else
3751 GetBlockDeclRefExprs(*CI);
3752 }
3753 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003754 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3755 if (DRE->refersToEnclosingLocal()) {
3756 // FIXME: Handle enums.
3757 if (!isa<FunctionDecl>(DRE->getDecl()))
3758 BlockDeclRefs.push_back(DRE);
3759 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3760 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003761 }
John McCallf4b88a42012-03-10 09:33:50 +00003762 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003763
Steve Naroff54055232008-10-27 17:20:55 +00003764 return;
3765}
3766
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003767void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003768 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003769 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003770 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003771 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003772 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3773 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003774 GetInnerBlockDeclRefExprs(CBE->getBody(),
3775 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003776 InnerContexts);
3777 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003778 else
3779 GetInnerBlockDeclRefExprs(*CI,
3780 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003781 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003782
3783 }
3784 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3786 if (DRE->refersToEnclosingLocal()) {
3787 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3788 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3789 InnerBlockDeclRefs.push_back(DRE);
3790 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3791 if (Var->isFunctionOrMethodVarDecl())
3792 ImportedLocalExternalDecls.insert(Var);
3793 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003794 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003795
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003796 return;
3797}
3798
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003799/// convertFunctionTypeOfBlocks - This routine converts a function type
3800/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003801/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003802/// all block pointers to function pointers.
3803QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3804 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3805 // FTP will be null for closures that don't take arguments.
3806 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003807 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003808 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003809 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003810
3811 if (FTP) {
3812 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3813 E = FTP->arg_type_end(); I && (I != E); ++I) {
3814 QualType t = *I;
3815 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003816 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003817 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003818 ArgTypes.push_back(t);
3819 }
3820 }
3821 QualType FuncType;
3822 // FIXME. Does this work if block takes no argument but has a return type
3823 // which is of block type?
3824 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003825 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003826 else FuncType = QualType(FT, 0);
3827 return FuncType;
3828}
3829
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003830Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003831 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003832 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003833
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003834 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003835 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003836 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003837 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003838 }
3839 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3840 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3841 }
3842 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3843 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3844 else if (const ConditionalOperator *CEXPR =
3845 dyn_cast<ConditionalOperator>(BlockExp)) {
3846 Expr *LHSExp = CEXPR->getLHS();
3847 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3848 Expr *RHSExp = CEXPR->getRHS();
3849 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3850 Expr *CONDExp = CEXPR->getCond();
3851 ConditionalOperator *CondExpr =
3852 new (Context) ConditionalOperator(CONDExp,
3853 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003854 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003855 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003856 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003857 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3858 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003859 } else if (const PseudoObjectExpr *POE
3860 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3861 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003862 } else {
3863 assert(1 && "RewriteBlockClass: Bad type");
3864 }
3865 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003866 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003867 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003868 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003869 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003871 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003872 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003873 &Context->Idents.get("__block_impl"));
3874 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003875
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003876 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003877 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003879 // Push the block argument type.
3880 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003881 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003882 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003883 E = FTP->arg_type_end(); I && (I != E); ++I) {
3884 QualType t = *I;
3885 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003886 if (!convertBlockPointerToFunctionPointer(t))
3887 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003888 ArgTypes.push_back(t);
3889 }
Steve Naroff54055232008-10-27 17:20:55 +00003890 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003891 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003892 QualType PtrToFuncCastType
3893 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003895 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003896
John McCall9d125032010-01-15 18:39:57 +00003897 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003898 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003899 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003900 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003901 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3902 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003903 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003904
Douglas Gregor44b43212008-12-11 16:49:14 +00003905 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003906 SourceLocation(),
3907 &Context->Idents.get("FuncPtr"),
3908 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003909 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003910 ICIS_NoInit);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003911 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003912 FD->getType(), VK_LValue,
3913 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003914
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003915
John McCall9d125032010-01-15 18:39:57 +00003916 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003917 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003918 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Chris Lattner5f9e2722011-07-23 10:55:15 +00003920 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003921 // Add the implicit argument.
3922 BlkExprs.push_back(BlkCast);
3923 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003924 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003925 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003926 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003927 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003928 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3929 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003930 Exp->getType(), VK_RValue,
3931 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003932 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003933}
3934
Steve Naroff621edce2009-04-29 16:37:50 +00003935// We need to return the rewritten expression to handle cases where the
3936// BlockDeclRefExpr is embedded in another expression being rewritten.
3937// For example:
3938//
3939// int main() {
3940// __block Foo *f;
3941// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003942//
Steve Naroff621edce2009-04-29 16:37:50 +00003943// void (^myblock)() = ^() {
3944// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3945// i = 77;
3946// };
3947//}
John McCallf4b88a42012-03-10 09:33:50 +00003948Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003949 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003950 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003951 ValueDecl *VD = DeclRefExp->getDecl();
3952 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003953
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003954 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003955 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003956 &Context->Idents.get("__forwarding"),
3957 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003958 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003959 ICIS_NoInit);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003960 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3961 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003962 FD->getType(), VK_LValue,
3963 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003964
Chris Lattner5f9e2722011-07-23 10:55:15 +00003965 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003966 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003967 &Context->Idents.get(Name),
3968 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003969 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003970 ICIS_NoInit);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003971 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003972 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003973
3974
3975
Steve Naroffdf8570d2009-02-02 17:19:26 +00003976 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003977 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3978 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003979 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003980 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003981 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003982}
3983
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003984// Rewrites the imported local variable V with external storage
3985// (static, extern, etc.) as *V
3986//
3987Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3988 ValueDecl *VD = DRE->getDecl();
3989 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3990 if (!ImportedLocalExternalDecls.count(Var))
3991 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003992 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3993 VK_LValue, OK_Ordinary,
3994 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003995 // Need parens to enforce precedence.
3996 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3997 Exp);
3998 ReplaceStmt(DRE, PE);
3999 return PE;
4000}
4001
Steve Naroffb2f9e512008-11-03 23:29:32 +00004002void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4003 SourceLocation LocStart = CE->getLParenLoc();
4004 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004005
4006 // Need to avoid trying to rewrite synthesized casts.
4007 if (LocStart.isInvalid())
4008 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004009 // Need to avoid trying to rewrite casts contained in macros.
4010 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4011 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Steve Naroff54055232008-10-27 17:20:55 +00004013 const char *startBuf = SM->getCharacterData(LocStart);
4014 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004015 QualType QT = CE->getType();
4016 const Type* TypePtr = QT->getAs<Type>();
4017 if (isa<TypeOfExprType>(TypePtr)) {
4018 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4019 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4020 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004021 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004022 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004023 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004024 return;
4025 }
Steve Naroff54055232008-10-27 17:20:55 +00004026 // advance the location to startArgList.
4027 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Steve Naroff54055232008-10-27 17:20:55 +00004029 while (*argPtr++ && (argPtr < endBuf)) {
4030 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004031 case '^':
4032 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004033 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004034 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004035 break;
Steve Naroff54055232008-10-27 17:20:55 +00004036 }
4037 }
4038 return;
4039}
4040
4041void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4042 SourceLocation DeclLoc = FD->getLocation();
4043 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Steve Naroff54055232008-10-27 17:20:55 +00004045 // We have 1 or more arguments that have closure pointers.
4046 const char *startBuf = SM->getCharacterData(DeclLoc);
4047 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Steve Naroff54055232008-10-27 17:20:55 +00004049 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Steve Naroff54055232008-10-27 17:20:55 +00004051 parenCount++;
4052 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004053 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004054 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Steve Naroff54055232008-10-27 17:20:55 +00004056 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004057
Steve Naroff54055232008-10-27 17:20:55 +00004058 while (*argPtr++ && parenCount) {
4059 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004060 case '^':
4061 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004062 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004063 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004064 break;
4065 case '(':
4066 parenCount++;
4067 break;
4068 case ')':
4069 parenCount--;
4070 break;
Steve Naroff54055232008-10-27 17:20:55 +00004071 }
4072 }
4073 return;
4074}
4075
4076bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004077 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004078 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004079 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004080 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004081 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004082 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004083 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004084 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004085 }
4086 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004087 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004088 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004089 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004090 return true;
4091 }
4092 return false;
4093}
4094
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004095bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4096 const FunctionProtoType *FTP;
4097 const PointerType *PT = QT->getAs<PointerType>();
4098 if (PT) {
4099 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4100 } else {
4101 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4102 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4103 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4104 }
4105 if (FTP) {
4106 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004107 E = FTP->arg_type_end(); I != E; ++I) {
4108 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004109 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004110 if ((*I)->isObjCObjectPointerType() &&
4111 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4112 return true;
4113 }
4114
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004115 }
4116 return false;
4117}
4118
Ted Kremenek8189cde2009-02-07 01:47:29 +00004119void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4120 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004121 const char *argPtr = strchr(Name, '(');
4122 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Steve Naroff54055232008-10-27 17:20:55 +00004124 LParen = argPtr; // output the start.
4125 argPtr++; // skip past the left paren.
4126 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004127
Steve Naroff54055232008-10-27 17:20:55 +00004128 while (*argPtr && parenCount) {
4129 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004130 case '(': parenCount++; break;
4131 case ')': parenCount--; break;
4132 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004133 }
4134 if (parenCount) argPtr++;
4135 }
4136 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4137 RParen = argPtr; // output the end
4138}
4139
4140void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4141 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4142 RewriteBlockPointerFunctionArgs(FD);
4143 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004144 }
Steve Naroff54055232008-10-27 17:20:55 +00004145 // Handle Variables and Typedefs.
4146 SourceLocation DeclLoc = ND->getLocation();
4147 QualType DeclT;
4148 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4149 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004150 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004151 DeclT = TDD->getUnderlyingType();
4152 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4153 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004154 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004155 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004156
Steve Naroff54055232008-10-27 17:20:55 +00004157 const char *startBuf = SM->getCharacterData(DeclLoc);
4158 const char *endBuf = startBuf;
4159 // scan backward (from the decl location) for the end of the previous decl.
4160 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4161 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004162 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004163 std::string buf;
4164 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004165 // *startBuf != '^' if we are dealing with a pointer to function that
4166 // may take block argument types (which will be handled below).
4167 if (*startBuf == '^') {
4168 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004169 buf = '*';
4170 startBuf++;
4171 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004172 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004173 while (*startBuf != ')') {
4174 buf += *startBuf;
4175 startBuf++;
4176 OrigLength++;
4177 }
4178 buf += ')';
4179 OrigLength++;
4180
4181 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4182 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004183 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004184 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004185 DeclLoc = ND->getLocation();
4186 startBuf = SM->getCharacterData(DeclLoc);
4187 const char *argListBegin, *argListEnd;
4188 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4189 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004190 if (*argListBegin == '^')
4191 buf += '*';
4192 else if (*argListBegin == '<') {
4193 buf += "/*";
4194 buf += *argListBegin++;
4195 OrigLength++;;
4196 while (*argListBegin != '>') {
4197 buf += *argListBegin++;
4198 OrigLength++;
4199 }
4200 buf += *argListBegin;
4201 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004202 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004203 else
4204 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004205 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004206 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004207 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004208 buf += ')';
4209 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004210 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004211 ReplaceText(Start, OrigLength, buf);
4212
Steve Naroff54055232008-10-27 17:20:55 +00004213 return;
4214}
4215
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004216
4217/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4218/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4219/// struct Block_byref_id_object *src) {
4220/// _Block_object_assign (&_dest->object, _src->object,
4221/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4222/// [|BLOCK_FIELD_IS_WEAK]) // object
4223/// _Block_object_assign(&_dest->object, _src->object,
4224/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4225/// [|BLOCK_FIELD_IS_WEAK]) // block
4226/// }
4227/// And:
4228/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4229/// _Block_object_dispose(_src->object,
4230/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4231/// [|BLOCK_FIELD_IS_WEAK]) // object
4232/// _Block_object_dispose(_src->object,
4233/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4234/// [|BLOCK_FIELD_IS_WEAK]) // block
4235/// }
4236
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004237std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4238 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004239 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004240 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004241 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004242 CopyDestroyCache.insert(flag);
4243 S = "static void __Block_byref_id_object_copy_";
4244 S += utostr(flag);
4245 S += "(void *dst, void *src) {\n";
4246
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004247 // offset into the object pointer is computed as:
4248 // void * + void* + int + int + void* + void *
4249 unsigned IntSize =
4250 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4251 unsigned VoidPtrSize =
4252 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4253
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004254 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004255 S += " _Block_object_assign((char*)dst + ";
4256 S += utostr(offset);
4257 S += ", *(void * *) ((char*)src + ";
4258 S += utostr(offset);
4259 S += "), ";
4260 S += utostr(flag);
4261 S += ");\n}\n";
4262
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004263 S += "static void __Block_byref_id_object_dispose_";
4264 S += utostr(flag);
4265 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004266 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4267 S += utostr(offset);
4268 S += "), ";
4269 S += utostr(flag);
4270 S += ");\n}\n";
4271 return S;
4272}
4273
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004274/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4275/// the declaration into:
4276/// struct __Block_byref_ND {
4277/// void *__isa; // NULL for everything except __weak pointers
4278/// struct __Block_byref_ND *__forwarding;
4279/// int32_t __flags;
4280/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004281/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4282/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004283/// typex ND;
4284/// };
4285///
4286/// It then replaces declaration of ND variable with:
4287/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4288/// __size=sizeof(struct __Block_byref_ND),
4289/// ND=initializer-if-any};
4290///
4291///
4292void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004293 // Insert declaration for the function in which block literal is
4294 // used.
4295 if (CurFunctionDeclToDeclareForBlock)
4296 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004297 int flag = 0;
4298 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004299 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004300 if (DeclLoc.isInvalid())
4301 // If type location is missing, it is because of missing type (a warning).
4302 // Use variable's location which is good for this case.
4303 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004304 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004305 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004306 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004307 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004308 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004309 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004310 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004311 ByrefType += " {\n";
4312 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004313 RewriteByRefString(ByrefType, Name, ND);
4314 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004315 ByrefType += " int __flags;\n";
4316 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004317 // Add void *__Block_byref_id_object_copy;
4318 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004319 QualType Ty = ND->getType();
4320 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4321 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004322 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4323 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004324 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004325
4326 QualType T = Ty;
4327 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004328 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004329
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004330 ByrefType += " " + Name + ";\n";
4331 ByrefType += "};\n";
4332 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004333 SourceLocation FunLocStart;
4334 if (CurFunctionDef)
4335 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4336 else {
4337 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4338 FunLocStart = CurMethodDef->getLocStart();
4339 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004340 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004341 if (Ty.isObjCGCWeak()) {
4342 flag |= BLOCK_FIELD_IS_WEAK;
4343 isa = 1;
4344 }
4345
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004346 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004347 flag = BLOCK_BYREF_CALLER;
4348 QualType Ty = ND->getType();
4349 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4350 if (Ty->isBlockPointerType())
4351 flag |= BLOCK_FIELD_IS_BLOCK;
4352 else
4353 flag |= BLOCK_FIELD_IS_OBJECT;
4354 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004355 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004356 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004357 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004358
4359 // struct __Block_byref_ND ND =
4360 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4361 // initializer-if-any};
4362 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004363 unsigned flags = 0;
4364 if (HasCopyAndDispose)
4365 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004366 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004367 ByrefType.clear();
4368 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004369 std::string ForwardingCastType("(");
4370 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004371 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004372 ByrefType += " " + Name + " = {(void*)";
4373 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004374 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004375 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004376 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004377 ByrefType += "sizeof(";
4378 RewriteByRefString(ByrefType, Name, ND);
4379 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004380 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004381 ByrefType += ", __Block_byref_id_object_copy_";
4382 ByrefType += utostr(flag);
4383 ByrefType += ", __Block_byref_id_object_dispose_";
4384 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004385 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004386 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004387 unsigned nameSize = Name.size();
4388 // for block or function pointer declaration. Name is aleady
4389 // part of the declaration.
4390 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4391 nameSize = 1;
4392 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004393 }
4394 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004395 SourceLocation startLoc;
4396 Expr *E = ND->getInit();
4397 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4398 startLoc = ECE->getLParenLoc();
4399 else
4400 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004401 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004402 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004403 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004404 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004405 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004406 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004407 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004408 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004409 ByrefType += "sizeof(";
4410 RewriteByRefString(ByrefType, Name, ND);
4411 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004412 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004413 ByrefType += "__Block_byref_id_object_copy_";
4414 ByrefType += utostr(flag);
4415 ByrefType += ", __Block_byref_id_object_dispose_";
4416 ByrefType += utostr(flag);
4417 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004418 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004419 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004420
4421 // Complete the newly synthesized compound expression by inserting a right
4422 // curly brace before the end of the declaration.
4423 // FIXME: This approach avoids rewriting the initializer expression. It
4424 // also assumes there is only one declarator. For example, the following
4425 // isn't currently supported by this routine (in general):
4426 //
4427 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4428 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004429 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4430 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004431 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4432 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004433 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004434
Benjamin Kramerd999b372010-02-14 14:14:16 +00004435 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004436 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004437 return;
4438}
4439
Mike Stump1eb44332009-09-09 15:08:12 +00004440void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004441 // Add initializers for any closure decl refs.
4442 GetBlockDeclRefExprs(Exp->getBody());
4443 if (BlockDeclRefs.size()) {
4444 // Unique all "by copy" declarations.
4445 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004446 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004447 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4448 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4449 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4450 }
4451 }
Steve Naroff54055232008-10-27 17:20:55 +00004452 // Unique all "by ref" declarations.
4453 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004454 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004455 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4456 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4457 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4458 }
Steve Naroff54055232008-10-27 17:20:55 +00004459 }
4460 // Find any imported blocks...they will need special attention.
4461 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004462 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004463 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004464 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004465 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004466 }
4467}
4468
Chris Lattner5f9e2722011-07-23 10:55:15 +00004469FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004470 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004471 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004472 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4473 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004474 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004475}
4476
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004477Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004478 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004479 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004480 Blocks.push_back(Exp);
4481
4482 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004483
4484 // Add inner imported variables now used in current block.
4485 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004486 if (!InnerBlockDeclRefs.empty()) {
4487 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004488 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004489 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004490 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004491 // We need to save the copied-in variables in nested
4492 // blocks because it is needed at the end for some of the API generations.
4493 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004494 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4495 BlockDeclRefs.push_back(Exp);
4496 BlockByCopyDeclsPtrSet.insert(VD);
4497 BlockByCopyDecls.push_back(VD);
4498 }
John McCallf4b88a42012-03-10 09:33:50 +00004499 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004500 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4501 BlockDeclRefs.push_back(Exp);
4502 BlockByRefDeclsPtrSet.insert(VD);
4503 BlockByRefDecls.push_back(VD);
4504 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004505 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004506 // Find any imported blocks...they will need special attention.
4507 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004508 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004509 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4510 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4511 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004512 }
4513 InnerDeclRefsCount.push_back(countOfInnerDecls);
4514
Steve Narofffa15fd92008-10-28 20:29:00 +00004515 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004516
Steve Narofffa15fd92008-10-28 20:29:00 +00004517 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004518 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004519 else if (CurMethodDef)
4520 BuildUniqueMethodName(FuncName, CurMethodDef);
4521 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004522 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004523
Steve Narofffa15fd92008-10-28 20:29:00 +00004524 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Steve Narofffa15fd92008-10-28 20:29:00 +00004526 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4527 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Steve Narofffa15fd92008-10-28 20:29:00 +00004529 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004530 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4531 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004532
4533 FunctionDecl *FD;
4534 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Narofffa15fd92008-10-28 20:29:00 +00004536 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004537 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004538 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004539 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004540
Chris Lattner5f9e2722011-07-23 10:55:15 +00004541 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004542
Steve Narofffdc03722008-10-29 21:23:59 +00004543 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004544 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004545 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4546 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004547 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004548 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004549 InitExprs.push_back(castExpr);
4550
Steve Naroff01aec112009-12-06 21:14:13 +00004551 // Initialize the block descriptor.
4552 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004553
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004554 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4555 SourceLocation(), SourceLocation(),
4556 &Context->Idents.get(DescData.c_str()),
4557 Context->VoidPtrTy, 0,
4558 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004559 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004560 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004561 Context->VoidPtrTy,
4562 VK_LValue,
4563 SourceLocation()),
4564 UO_AddrOf,
4565 Context->getPointerType(Context->VoidPtrTy),
4566 VK_RValue, OK_Ordinary,
4567 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004568 InitExprs.push_back(DescRefExpr);
4569
Steve Narofffa15fd92008-10-28 20:29:00 +00004570 // Add initializers for any closure decl refs.
4571 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004572 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004573 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004574 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004575 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004576 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004577 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004578 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004579 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004580 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004581 if (HasLocalVariableExternalStorage(*I)) {
4582 QualType QT = (*I)->getType();
4583 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004584 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4585 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004586 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004587 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004588 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004589 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004590 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004591 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004592 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004593 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004594 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004595 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004596 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004597 if (HasLocalVariableExternalStorage(*I)) {
4598 QualType QT = (*I)->getType();
4599 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004600 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4601 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004602 }
4603
Steve Narofffa15fd92008-10-28 20:29:00 +00004604 }
Mike Stump1eb44332009-09-09 15:08:12 +00004605 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004606 }
4607 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004608 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004609 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004610 ValueDecl *ND = (*I);
4611 std::string Name(ND->getNameAsString());
4612 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004613 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004614 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4615 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004616 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004617 SourceLocation(), SourceLocation(),
4618 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004619 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4620 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4621
Daniel Dunbar4087f272010-08-17 22:39:59 +00004622 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004623 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004624 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004625 bool isNestedCapturedVar = false;
4626 if (block)
4627 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4628 ce = block->capture_end(); ci != ce; ++ci) {
4629 const VarDecl *variable = ci->getVariable();
4630 if (variable == ND && ci->isNested()) {
4631 assert (ci->isByRef() &&
4632 "SynthBlockInitExpr - captured block variable is not byref");
4633 isNestedCapturedVar = true;
4634 break;
4635 }
4636 }
4637 // captured nested byref variable has its address passed. Do not take
4638 // its address again.
4639 if (!isNestedCapturedVar)
4640 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004641 Context->getPointerType(Exp->getType()),
4642 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004643 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004644 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004645 }
4646 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004647 if (ImportedBlockDecls.size()) {
4648 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4649 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004650 unsigned IntSize =
4651 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004652 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4653 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004654 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004655 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004656 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004657 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004658 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004659 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004660 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004661 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004662 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004663 BlockDeclRefs.clear();
4664 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004665 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004666 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004667 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004668 ImportedBlockDecls.clear();
4669 return NewRep;
4670}
4671
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004672bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4673 if (const ObjCForCollectionStmt * CS =
4674 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4675 return CS->getElement() == DS;
4676 return false;
4677}
4678
Steve Narofffa15fd92008-10-28 20:29:00 +00004679//===----------------------------------------------------------------------===//
4680// Function Body / Expression rewriting
4681//===----------------------------------------------------------------------===//
4682
4683Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004684 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004685 isa<DoStmt>(S) || isa<ForStmt>(S))
4686 Stmts.push_back(S);
4687 else if (isa<ObjCForCollectionStmt>(S)) {
4688 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004689 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004690 }
Mike Stump1eb44332009-09-09 15:08:12 +00004691
John McCall4b9c2d22011-11-06 09:01:30 +00004692 // Pseudo-object operations and ivar references need special
4693 // treatment because we're going to recursively rewrite them.
4694 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4695 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4696 return RewritePropertyOrImplicitSetter(PseudoOp);
4697 } else {
4698 return RewritePropertyOrImplicitGetter(PseudoOp);
4699 }
4700 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4701 return RewriteObjCIvarRefExpr(IvarRefExpr);
4702 }
4703
Steve Narofffa15fd92008-10-28 20:29:00 +00004704 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Steve Narofffa15fd92008-10-28 20:29:00 +00004706 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004707 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004708 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004709 Stmt *childStmt = (*CI);
4710 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004711 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004712 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004713 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004714 }
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004717 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004718 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4719 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004720 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004721 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004722 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004723 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004724 Stmt *SaveCurrentBody = CurrentBody;
4725 CurrentBody = BE->getBody();
4726 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004727 // block literal on rhs of a property-dot-sytax assignment
4728 // must be replaced by its synthesize ast so getRewrittenText
4729 // works as expected. In this case, what actually ends up on RHS
4730 // is the blockTranscribed which is the helper function for the
4731 // block literal; as in: self.c = ^() {[ace ARR];};
4732 bool saveDisableReplaceStmt = DisableReplaceStmt;
4733 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004734 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004735 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004736 CurrentBody = SaveCurrentBody;
4737 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004738 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004740 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004741 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004743 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4744
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004746 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 return blockTranscribed;
4748 }
4749 // Handle specific things.
4750 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4751 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Steve Narofffa15fd92008-10-28 20:29:00 +00004753 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4754 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4757 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004760#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004761 // Before we rewrite it, put the original message expression in a comment.
4762 SourceLocation startLoc = MessExpr->getLocStart();
4763 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Steve Narofffa15fd92008-10-28 20:29:00 +00004765 const char *startBuf = SM->getCharacterData(startLoc);
4766 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004767
Steve Narofffa15fd92008-10-28 20:29:00 +00004768 std::string messString;
4769 messString += "// ";
4770 messString.append(startBuf, endBuf-startBuf+1);
4771 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004772
4773 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 // InsertText(clang::SourceLocation, char const*, unsigned int).
4775 // InsertText(startLoc, messString.c_str(), messString.size());
4776 // Tried this, but it didn't work either...
4777 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004778#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 return RewriteMessageExpr(MessExpr);
4780 }
Mike Stump1eb44332009-09-09 15:08:12 +00004781
Steve Narofffa15fd92008-10-28 20:29:00 +00004782 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4783 return RewriteObjCTryStmt(StmtTry);
4784
4785 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4786 return RewriteObjCSynchronizedStmt(StmtTry);
4787
4788 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4789 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004790
Steve Narofffa15fd92008-10-28 20:29:00 +00004791 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4792 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004793
4794 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004795 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004796 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004797 OrigStmtRange.getEnd());
4798 if (BreakStmt *StmtBreakStmt =
4799 dyn_cast<BreakStmt>(S))
4800 return RewriteBreakStmt(StmtBreakStmt);
4801 if (ContinueStmt *StmtContinueStmt =
4802 dyn_cast<ContinueStmt>(S))
4803 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004804
4805 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004806 // and cast exprs.
4807 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4808 // FIXME: What we're doing here is modifying the type-specifier that
4809 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004810 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004811 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4812 // the context of an ObjCForCollectionStmt. For example:
4813 // NSArray *someArray;
4814 // for (id <FooProtocol> index in someArray) ;
4815 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4816 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004817 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004818 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Steve Narofffa15fd92008-10-28 20:29:00 +00004820 // Blocks rewrite rules.
4821 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4822 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004823 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004824 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004825 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004826 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004827 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004828 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004829 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004830 if (VD->hasAttr<BlocksAttr>()) {
4831 static unsigned uniqueByrefDeclCount = 0;
4832 assert(!BlockByRefDeclNo.count(ND) &&
4833 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4834 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004835 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004836 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004837 else
4838 RewriteTypeOfDecl(VD);
4839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004840 }
Richard Smith162e1c12011-04-15 14:24:37 +00004841 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004842 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004843 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004844 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004845 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4846 }
4847 }
4848 }
Mike Stump1eb44332009-09-09 15:08:12 +00004849
Steve Narofffa15fd92008-10-28 20:29:00 +00004850 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4851 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004852
4853 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004854 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4855 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004856 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4857 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004858 && "Statement stack mismatch");
4859 Stmts.pop_back();
4860 }
4861 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004862 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4863 ValueDecl *VD = DRE->getDecl();
4864 if (VD->hasAttr<BlocksAttr>())
4865 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004866 if (HasLocalVariableExternalStorage(VD))
4867 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004868 }
4869
Steve Narofffa15fd92008-10-28 20:29:00 +00004870 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004871 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004872 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004873 ReplaceStmt(S, BlockCall);
4874 return BlockCall;
4875 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004876 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004877 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004878 RewriteCastExpr(CE);
4879 }
4880#if 0
4881 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004882 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4883 ICE->getSubExpr(),
4884 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004885 // Get the new text.
4886 std::string SStr;
4887 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004888 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004889 const std::string &Str = Buf.str();
4890
4891 printf("CAST = %s\n", &Str[0]);
4892 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4893 delete S;
4894 return Replacement;
4895 }
4896#endif
4897 // Return this stmt unmodified.
4898 return S;
4899}
4900
Steve Naroff3d7e7862009-12-05 15:55:59 +00004901void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4902 for (RecordDecl::field_iterator i = RD->field_begin(),
4903 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00004904 FieldDecl *FD = *i;
Steve Naroff3d7e7862009-12-05 15:55:59 +00004905 if (isTopLevelBlockPointerType(FD->getType()))
4906 RewriteBlockPointerDecl(FD);
4907 if (FD->getType()->isObjCQualifiedIdType() ||
4908 FD->getType()->isObjCQualifiedInterfaceType())
4909 RewriteObjCQualifiedInterfaceTypes(FD);
4910 }
4911}
4912
Steve Narofffa15fd92008-10-28 20:29:00 +00004913/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4914/// main file of the input.
4915void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004916 switch (D->getKind()) {
4917 case Decl::Function: {
4918 FunctionDecl *FD = cast<FunctionDecl>(D);
4919 if (FD->isOverloadedOperator())
4920 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004922 // Since function prototypes don't have ParmDecl's, we check the function
4923 // prototype. This enables us to rewrite function declarations and
4924 // definitions using the same code.
4925 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004926
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004927 if (!FD->isThisDeclarationADefinition())
4928 break;
4929
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004930 // FIXME: If this should support Obj-C++, support CXXTryStmt
4931 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4932 CurFunctionDef = FD;
4933 CurFunctionDeclToDeclareForBlock = FD;
4934 CurrentBody = Body;
4935 Body =
4936 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4937 FD->setBody(Body);
4938 CurrentBody = 0;
4939 if (PropParentMap) {
4940 delete PropParentMap;
4941 PropParentMap = 0;
4942 }
4943 // This synthesizes and inserts the block "impl" struct, invoke function,
4944 // and any copy/dispose helper functions.
4945 InsertBlockLiteralsWithinFunction(FD);
4946 CurFunctionDef = 0;
4947 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004948 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004949 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004950 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004951 case Decl::ObjCMethod: {
4952 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4953 if (CompoundStmt *Body = MD->getCompoundBody()) {
4954 CurMethodDef = MD;
4955 CurrentBody = Body;
4956 Body =
4957 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4958 MD->setBody(Body);
4959 CurrentBody = 0;
4960 if (PropParentMap) {
4961 delete PropParentMap;
4962 PropParentMap = 0;
4963 }
4964 InsertBlockLiteralsWithinMethod(MD);
4965 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004966 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004967 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004968 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004969 case Decl::ObjCImplementation: {
4970 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4971 ClassImplementation.push_back(CI);
4972 break;
4973 }
4974 case Decl::ObjCCategoryImpl: {
4975 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4976 CategoryImplementation.push_back(CI);
4977 break;
4978 }
4979 case Decl::Var: {
4980 VarDecl *VD = cast<VarDecl>(D);
4981 RewriteObjCQualifiedInterfaceTypes(VD);
4982 if (isTopLevelBlockPointerType(VD->getType()))
4983 RewriteBlockPointerDecl(VD);
4984 else if (VD->getType()->isFunctionPointerType()) {
4985 CheckFunctionPointerDecl(VD->getType(), VD);
4986 if (VD->getInit()) {
4987 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4988 RewriteCastExpr(CE);
4989 }
4990 }
4991 } else if (VD->getType()->isRecordType()) {
4992 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4993 if (RD->isCompleteDefinition())
4994 RewriteRecordBody(RD);
4995 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004996 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004997 GlobalVarDecl = VD;
4998 CurrentBody = VD->getInit();
4999 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5000 CurrentBody = 0;
5001 if (PropParentMap) {
5002 delete PropParentMap;
5003 PropParentMap = 0;
5004 }
5005 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5006 GlobalVarDecl = 0;
5007
5008 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005009 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005010 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005011 }
5012 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005013 break;
5014 }
5015 case Decl::TypeAlias:
5016 case Decl::Typedef: {
5017 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5018 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5019 RewriteBlockPointerDecl(TD);
5020 else if (TD->getUnderlyingType()->isFunctionPointerType())
5021 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5022 }
5023 break;
5024 }
5025 case Decl::CXXRecord:
5026 case Decl::Record: {
5027 RecordDecl *RD = cast<RecordDecl>(D);
5028 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005029 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005030 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005031 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005032 default:
5033 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005034 }
5035 // Nothing yet.
5036}
5037
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005038void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005039 if (Diags.hasErrorOccurred())
5040 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005041
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005043
Steve Naroff621edce2009-04-29 16:37:50 +00005044 // Here's a great place to add any extra declarations that may be needed.
5045 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005046 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005047 E = ProtocolExprDecls.end(); I != E; ++I)
5048 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5049
Benjamin Kramerd999b372010-02-14 14:14:16 +00005050 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005051 if (ClassImplementation.size() || CategoryImplementation.size())
5052 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005053
Steve Narofffa15fd92008-10-28 20:29:00 +00005054 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5055 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005056 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005057 Rewrite.getRewriteBufferFor(MainFileID)) {
5058 //printf("Changed:\n");
5059 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5060 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005061 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005062 }
Steve Narofface66252008-11-13 20:07:04 +00005063
Steve Naroff621edce2009-04-29 16:37:50 +00005064 if (ClassImplementation.size() || CategoryImplementation.size() ||
5065 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005066 // Rewrite Objective-c meta data*
5067 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005068 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005069 // Emit metadata.
5070 *OutFile << ResultStr;
5071 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005072 OutFile->flush();
5073}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005074
5075void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5076 InitializeCommon(context);
5077
5078 // declaring objc_selector outside the parameter list removes a silly
5079 // scope related warning...
5080 if (IsHeader)
5081 Preamble = "#pragma once\n";
5082 Preamble += "struct objc_selector; struct objc_class;\n";
5083 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5084 Preamble += "struct objc_object *superClass; ";
5085 if (LangOpts.MicrosoftExt) {
5086 // Add a constructor for creating temporary objects.
5087 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5088 ": ";
5089 Preamble += "object(o), superClass(s) {} ";
5090 }
5091 Preamble += "};\n";
5092 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5093 Preamble += "typedef struct objc_object Protocol;\n";
5094 Preamble += "#define _REWRITER_typedef_Protocol\n";
5095 Preamble += "#endif\n";
5096 if (LangOpts.MicrosoftExt) {
5097 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5098 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5099 } else
5100 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5102 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5104 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5106 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5107 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5108 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5109 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5110 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5111 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5112 Preamble += "(const char *);\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5114 Preamble += "(struct objc_class *);\n";
5115 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5116 Preamble += "(const char *);\n";
5117 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5118 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5119 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5120 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5121 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5122 Preamble += "(struct objc_class *, struct objc_object *);\n";
5123 // @synchronized hooks.
5124 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5125 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5126 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5127 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5128 Preamble += "struct __objcFastEnumerationState {\n\t";
5129 Preamble += "unsigned long state;\n\t";
5130 Preamble += "void **itemsPtr;\n\t";
5131 Preamble += "unsigned long *mutationsPtr;\n\t";
5132 Preamble += "unsigned long extra[5];\n};\n";
5133 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5134 Preamble += "#define __FASTENUMERATIONSTATE\n";
5135 Preamble += "#endif\n";
5136 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5137 Preamble += "struct __NSConstantStringImpl {\n";
5138 Preamble += " int *isa;\n";
5139 Preamble += " int flags;\n";
5140 Preamble += " char *str;\n";
5141 Preamble += " long length;\n";
5142 Preamble += "};\n";
5143 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5144 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5145 Preamble += "#else\n";
5146 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5147 Preamble += "#endif\n";
5148 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5149 Preamble += "#endif\n";
5150 // Blocks preamble.
5151 Preamble += "#ifndef BLOCK_IMPL\n";
5152 Preamble += "#define BLOCK_IMPL\n";
5153 Preamble += "struct __block_impl {\n";
5154 Preamble += " void *isa;\n";
5155 Preamble += " int Flags;\n";
5156 Preamble += " int Reserved;\n";
5157 Preamble += " void *FuncPtr;\n";
5158 Preamble += "};\n";
5159 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5160 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5161 Preamble += "extern \"C\" __declspec(dllexport) "
5162 "void _Block_object_assign(void *, const void *, const int);\n";
5163 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5164 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5165 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5166 Preamble += "#else\n";
5167 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5168 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5169 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5170 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5171 Preamble += "#endif\n";
5172 Preamble += "#endif\n";
5173 if (LangOpts.MicrosoftExt) {
5174 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5175 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5176 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5177 Preamble += "#define __attribute__(X)\n";
5178 Preamble += "#endif\n";
5179 Preamble += "#define __weak\n";
5180 }
5181 else {
5182 Preamble += "#define __block\n";
5183 Preamble += "#define __weak\n";
5184 }
5185 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5186 // as this avoids warning in any 64bit/32bit compilation model.
5187 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5188}
5189
5190/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5191/// ivar offset.
5192void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5193 std::string &Result) {
5194 if (ivar->isBitField()) {
5195 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5196 // place all bitfields at offset 0.
5197 Result += "0";
5198 } else {
5199 Result += "__OFFSETOFIVAR__(struct ";
5200 Result += ivar->getContainingInterface()->getNameAsString();
5201 if (LangOpts.MicrosoftExt)
5202 Result += "_IMPL";
5203 Result += ", ";
5204 Result += ivar->getNameAsString();
5205 Result += ")";
5206 }
5207}
5208
5209/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5210void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5211 ObjCProtocolDecl *PDecl, StringRef prefix,
5212 StringRef ClassName, std::string &Result) {
5213 static bool objc_protocol_methods = false;
5214
5215 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005216 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005217 /* struct protocol_methods {
5218 SEL _cmd;
5219 char *method_types;
5220 }
5221 */
5222 Result += "\nstruct _protocol_methods {\n";
5223 Result += "\tstruct objc_selector *_cmd;\n";
5224 Result += "\tchar *method_types;\n";
5225 Result += "};\n";
5226
5227 objc_protocol_methods = true;
5228 }
5229 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005230 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005231 return;
5232
Douglas Gregor61cc2962012-01-02 02:00:30 +00005233 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5234 PDecl = Def;
5235
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005236 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5237 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5238 PDecl->instmeth_end());
5239 /* struct _objc_protocol_method_list {
5240 int protocol_method_count;
5241 struct protocol_methods protocols[];
5242 }
5243 */
5244 Result += "\nstatic struct {\n";
5245 Result += "\tint protocol_method_count;\n";
5246 Result += "\tstruct _protocol_methods protocol_methods[";
5247 Result += utostr(NumMethods);
5248 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5249 Result += PDecl->getNameAsString();
5250 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5251 "{\n\t" + utostr(NumMethods) + "\n";
5252
5253 // Output instance methods declared in this protocol.
5254 for (ObjCProtocolDecl::instmeth_iterator
5255 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5256 I != E; ++I) {
5257 if (I == PDecl->instmeth_begin())
5258 Result += "\t ,{{(struct objc_selector *)\"";
5259 else
5260 Result += "\t ,{(struct objc_selector *)\"";
5261 Result += (*I)->getSelector().getAsString();
5262 std::string MethodTypeString;
5263 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5264 Result += "\", \"";
5265 Result += MethodTypeString;
5266 Result += "\"}\n";
5267 }
5268 Result += "\t }\n};\n";
5269 }
5270
5271 // Output class methods declared in this protocol.
5272 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5273 PDecl->classmeth_end());
5274 if (NumMethods > 0) {
5275 /* struct _objc_protocol_method_list {
5276 int protocol_method_count;
5277 struct protocol_methods protocols[];
5278 }
5279 */
5280 Result += "\nstatic struct {\n";
5281 Result += "\tint protocol_method_count;\n";
5282 Result += "\tstruct _protocol_methods protocol_methods[";
5283 Result += utostr(NumMethods);
5284 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5285 Result += PDecl->getNameAsString();
5286 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5287 "{\n\t";
5288 Result += utostr(NumMethods);
5289 Result += "\n";
5290
5291 // Output instance methods declared in this protocol.
5292 for (ObjCProtocolDecl::classmeth_iterator
5293 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5294 I != E; ++I) {
5295 if (I == PDecl->classmeth_begin())
5296 Result += "\t ,{{(struct objc_selector *)\"";
5297 else
5298 Result += "\t ,{(struct objc_selector *)\"";
5299 Result += (*I)->getSelector().getAsString();
5300 std::string MethodTypeString;
5301 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5302 Result += "\", \"";
5303 Result += MethodTypeString;
5304 Result += "\"}\n";
5305 }
5306 Result += "\t }\n};\n";
5307 }
5308
5309 // Output:
5310 /* struct _objc_protocol {
5311 // Objective-C 1.0 extensions
5312 struct _objc_protocol_extension *isa;
5313 char *protocol_name;
5314 struct _objc_protocol **protocol_list;
5315 struct _objc_protocol_method_list *instance_methods;
5316 struct _objc_protocol_method_list *class_methods;
5317 };
5318 */
5319 static bool objc_protocol = false;
5320 if (!objc_protocol) {
5321 Result += "\nstruct _objc_protocol {\n";
5322 Result += "\tstruct _objc_protocol_extension *isa;\n";
5323 Result += "\tchar *protocol_name;\n";
5324 Result += "\tstruct _objc_protocol **protocol_list;\n";
5325 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5326 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5327 Result += "};\n";
5328
5329 objc_protocol = true;
5330 }
5331
5332 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5333 Result += PDecl->getNameAsString();
5334 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5335 "{\n\t0, \"";
5336 Result += PDecl->getNameAsString();
5337 Result += "\", 0, ";
5338 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5339 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5340 Result += PDecl->getNameAsString();
5341 Result += ", ";
5342 }
5343 else
5344 Result += "0, ";
5345 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5346 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5347 Result += PDecl->getNameAsString();
5348 Result += "\n";
5349 }
5350 else
5351 Result += "0\n";
5352 Result += "};\n";
5353
5354 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005355 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005356 llvm_unreachable("protocol already synthesized");
5357
5358}
5359
5360void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5361 const ObjCList<ObjCProtocolDecl> &Protocols,
5362 StringRef prefix, StringRef ClassName,
5363 std::string &Result) {
5364 if (Protocols.empty()) return;
5365
5366 for (unsigned i = 0; i != Protocols.size(); i++)
5367 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5368
5369 // Output the top lovel protocol meta-data for the class.
5370 /* struct _objc_protocol_list {
5371 struct _objc_protocol_list *next;
5372 int protocol_count;
5373 struct _objc_protocol *class_protocols[];
5374 }
5375 */
5376 Result += "\nstatic struct {\n";
5377 Result += "\tstruct _objc_protocol_list *next;\n";
5378 Result += "\tint protocol_count;\n";
5379 Result += "\tstruct _objc_protocol *class_protocols[";
5380 Result += utostr(Protocols.size());
5381 Result += "];\n} _OBJC_";
5382 Result += prefix;
5383 Result += "_PROTOCOLS_";
5384 Result += ClassName;
5385 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5386 "{\n\t0, ";
5387 Result += utostr(Protocols.size());
5388 Result += "\n";
5389
5390 Result += "\t,{&_OBJC_PROTOCOL_";
5391 Result += Protocols[0]->getNameAsString();
5392 Result += " \n";
5393
5394 for (unsigned i = 1; i != Protocols.size(); i++) {
5395 Result += "\t ,&_OBJC_PROTOCOL_";
5396 Result += Protocols[i]->getNameAsString();
5397 Result += "\n";
5398 }
5399 Result += "\t }\n};\n";
5400}
5401
5402void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5403 std::string &Result) {
5404 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5405
5406 // Explicitly declared @interface's are already synthesized.
5407 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005408 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005409 // produce correct synthesis as yet.
5410 RewriteObjCInternalStruct(CDecl, Result);
5411 }
5412
5413 // Build _objc_ivar_list metadata for classes ivars if needed
5414 unsigned NumIvars = !IDecl->ivar_empty()
5415 ? IDecl->ivar_size()
5416 : (CDecl ? CDecl->ivar_size() : 0);
5417 if (NumIvars > 0) {
5418 static bool objc_ivar = false;
5419 if (!objc_ivar) {
5420 /* struct _objc_ivar {
5421 char *ivar_name;
5422 char *ivar_type;
5423 int ivar_offset;
5424 };
5425 */
5426 Result += "\nstruct _objc_ivar {\n";
5427 Result += "\tchar *ivar_name;\n";
5428 Result += "\tchar *ivar_type;\n";
5429 Result += "\tint ivar_offset;\n";
5430 Result += "};\n";
5431
5432 objc_ivar = true;
5433 }
5434
5435 /* struct {
5436 int ivar_count;
5437 struct _objc_ivar ivar_list[nIvars];
5438 };
5439 */
5440 Result += "\nstatic struct {\n";
5441 Result += "\tint ivar_count;\n";
5442 Result += "\tstruct _objc_ivar ivar_list[";
5443 Result += utostr(NumIvars);
5444 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5445 Result += IDecl->getNameAsString();
5446 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5447 "{\n\t";
5448 Result += utostr(NumIvars);
5449 Result += "\n";
5450
5451 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5452 SmallVector<ObjCIvarDecl *, 8> IVars;
5453 if (!IDecl->ivar_empty()) {
5454 for (ObjCInterfaceDecl::ivar_iterator
5455 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5456 IV != IVEnd; ++IV)
David Blaikie581deb32012-06-06 20:45:41 +00005457 IVars.push_back(*IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005458 IVI = IDecl->ivar_begin();
5459 IVE = IDecl->ivar_end();
5460 } else {
5461 IVI = CDecl->ivar_begin();
5462 IVE = CDecl->ivar_end();
5463 }
5464 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005465 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005466 Result += "\", \"";
5467 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005468 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005469 QuoteDoublequotes(TmpString, StrEncoding);
5470 Result += StrEncoding;
5471 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005472 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005473 Result += "}\n";
5474 for (++IVI; IVI != IVE; ++IVI) {
5475 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005476 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005477 Result += "\", \"";
5478 std::string TmpString, StrEncoding;
David Blaikie581deb32012-06-06 20:45:41 +00005479 Context->getObjCEncodingForType(IVI->getType(), TmpString, *IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005480 QuoteDoublequotes(TmpString, StrEncoding);
5481 Result += StrEncoding;
5482 Result += "\", ";
David Blaikie581deb32012-06-06 20:45:41 +00005483 RewriteIvarOffsetComputation(*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005484 Result += "}\n";
5485 }
5486
5487 Result += "\t }\n};\n";
5488 }
5489
5490 // Build _objc_method_list for class's instance methods if needed
5491 SmallVector<ObjCMethodDecl *, 32>
5492 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5493
5494 // If any of our property implementations have associated getters or
5495 // setters, produce metadata for them as well.
5496 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5497 PropEnd = IDecl->propimpl_end();
5498 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005499 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005500 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005501 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005502 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005503 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005504 if (!PD)
5505 continue;
5506 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5507 if (!Getter->isDefined())
5508 InstanceMethods.push_back(Getter);
5509 if (PD->isReadOnly())
5510 continue;
5511 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5512 if (!Setter->isDefined())
5513 InstanceMethods.push_back(Setter);
5514 }
5515 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5516 true, "", IDecl->getName(), Result);
5517
5518 // Build _objc_method_list for class's class methods if needed
5519 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5520 false, "", IDecl->getName(), Result);
5521
5522 // Protocols referenced in class declaration?
5523 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5524 "CLASS", CDecl->getName(), Result);
5525
5526 // Declaration of class/meta-class metadata
5527 /* struct _objc_class {
5528 struct _objc_class *isa; // or const char *root_class_name when metadata
5529 const char *super_class_name;
5530 char *name;
5531 long version;
5532 long info;
5533 long instance_size;
5534 struct _objc_ivar_list *ivars;
5535 struct _objc_method_list *methods;
5536 struct objc_cache *cache;
5537 struct objc_protocol_list *protocols;
5538 const char *ivar_layout;
5539 struct _objc_class_ext *ext;
5540 };
5541 */
5542 static bool objc_class = false;
5543 if (!objc_class) {
5544 Result += "\nstruct _objc_class {\n";
5545 Result += "\tstruct _objc_class *isa;\n";
5546 Result += "\tconst char *super_class_name;\n";
5547 Result += "\tchar *name;\n";
5548 Result += "\tlong version;\n";
5549 Result += "\tlong info;\n";
5550 Result += "\tlong instance_size;\n";
5551 Result += "\tstruct _objc_ivar_list *ivars;\n";
5552 Result += "\tstruct _objc_method_list *methods;\n";
5553 Result += "\tstruct objc_cache *cache;\n";
5554 Result += "\tstruct _objc_protocol_list *protocols;\n";
5555 Result += "\tconst char *ivar_layout;\n";
5556 Result += "\tstruct _objc_class_ext *ext;\n";
5557 Result += "};\n";
5558 objc_class = true;
5559 }
5560
5561 // Meta-class metadata generation.
5562 ObjCInterfaceDecl *RootClass = 0;
5563 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5564 while (SuperClass) {
5565 RootClass = SuperClass;
5566 SuperClass = SuperClass->getSuperClass();
5567 }
5568 SuperClass = CDecl->getSuperClass();
5569
5570 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5571 Result += CDecl->getNameAsString();
5572 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5573 "{\n\t(struct _objc_class *)\"";
5574 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5575 Result += "\"";
5576
5577 if (SuperClass) {
5578 Result += ", \"";
5579 Result += SuperClass->getNameAsString();
5580 Result += "\", \"";
5581 Result += CDecl->getNameAsString();
5582 Result += "\"";
5583 }
5584 else {
5585 Result += ", 0, \"";
5586 Result += CDecl->getNameAsString();
5587 Result += "\"";
5588 }
5589 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5590 // 'info' field is initialized to CLS_META(2) for metaclass
5591 Result += ", 0,2, sizeof(struct _objc_class), 0";
5592 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5593 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5594 Result += IDecl->getNameAsString();
5595 Result += "\n";
5596 }
5597 else
5598 Result += ", 0\n";
5599 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5600 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5601 Result += CDecl->getNameAsString();
5602 Result += ",0,0\n";
5603 }
5604 else
5605 Result += "\t,0,0,0,0\n";
5606 Result += "};\n";
5607
5608 // class metadata generation.
5609 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5610 Result += CDecl->getNameAsString();
5611 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5612 "{\n\t&_OBJC_METACLASS_";
5613 Result += CDecl->getNameAsString();
5614 if (SuperClass) {
5615 Result += ", \"";
5616 Result += SuperClass->getNameAsString();
5617 Result += "\", \"";
5618 Result += CDecl->getNameAsString();
5619 Result += "\"";
5620 }
5621 else {
5622 Result += ", 0, \"";
5623 Result += CDecl->getNameAsString();
5624 Result += "\"";
5625 }
5626 // 'info' field is initialized to CLS_CLASS(1) for class
5627 Result += ", 0,1";
5628 if (!ObjCSynthesizedStructs.count(CDecl))
5629 Result += ",0";
5630 else {
5631 // class has size. Must synthesize its size.
5632 Result += ",sizeof(struct ";
5633 Result += CDecl->getNameAsString();
5634 if (LangOpts.MicrosoftExt)
5635 Result += "_IMPL";
5636 Result += ")";
5637 }
5638 if (NumIvars > 0) {
5639 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5640 Result += CDecl->getNameAsString();
5641 Result += "\n\t";
5642 }
5643 else
5644 Result += ",0";
5645 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5646 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5647 Result += CDecl->getNameAsString();
5648 Result += ", 0\n\t";
5649 }
5650 else
5651 Result += ",0,0";
5652 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5653 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5654 Result += CDecl->getNameAsString();
5655 Result += ", 0,0\n";
5656 }
5657 else
5658 Result += ",0,0,0\n";
5659 Result += "};\n";
5660}
5661
5662void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5663 int ClsDefCount = ClassImplementation.size();
5664 int CatDefCount = CategoryImplementation.size();
5665
5666 // For each implemented class, write out all its meta data.
5667 for (int i = 0; i < ClsDefCount; i++)
5668 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5669
5670 // For each implemented category, write out all its meta data.
5671 for (int i = 0; i < CatDefCount; i++)
5672 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5673
5674 // Write objc_symtab metadata
5675 /*
5676 struct _objc_symtab
5677 {
5678 long sel_ref_cnt;
5679 SEL *refs;
5680 short cls_def_cnt;
5681 short cat_def_cnt;
5682 void *defs[cls_def_cnt + cat_def_cnt];
5683 };
5684 */
5685
5686 Result += "\nstruct _objc_symtab {\n";
5687 Result += "\tlong sel_ref_cnt;\n";
5688 Result += "\tSEL *refs;\n";
5689 Result += "\tshort cls_def_cnt;\n";
5690 Result += "\tshort cat_def_cnt;\n";
5691 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5692 Result += "};\n\n";
5693
5694 Result += "static struct _objc_symtab "
5695 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5696 Result += "\t0, 0, " + utostr(ClsDefCount)
5697 + ", " + utostr(CatDefCount) + "\n";
5698 for (int i = 0; i < ClsDefCount; i++) {
5699 Result += "\t,&_OBJC_CLASS_";
5700 Result += ClassImplementation[i]->getNameAsString();
5701 Result += "\n";
5702 }
5703
5704 for (int i = 0; i < CatDefCount; i++) {
5705 Result += "\t,&_OBJC_CATEGORY_";
5706 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5707 Result += "_";
5708 Result += CategoryImplementation[i]->getNameAsString();
5709 Result += "\n";
5710 }
5711
5712 Result += "};\n\n";
5713
5714 // Write objc_module metadata
5715
5716 /*
5717 struct _objc_module {
5718 long version;
5719 long size;
5720 const char *name;
5721 struct _objc_symtab *symtab;
5722 }
5723 */
5724
5725 Result += "\nstruct _objc_module {\n";
5726 Result += "\tlong version;\n";
5727 Result += "\tlong size;\n";
5728 Result += "\tconst char *name;\n";
5729 Result += "\tstruct _objc_symtab *symtab;\n";
5730 Result += "};\n\n";
5731 Result += "static struct _objc_module "
5732 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5733 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5734 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5735 Result += "};\n\n";
5736
5737 if (LangOpts.MicrosoftExt) {
5738 if (ProtocolExprDecls.size()) {
5739 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5740 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5741 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5742 E = ProtocolExprDecls.end(); I != E; ++I) {
5743 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5744 Result += (*I)->getNameAsString();
5745 Result += " = &_OBJC_PROTOCOL_";
5746 Result += (*I)->getNameAsString();
5747 Result += ";\n";
5748 }
5749 Result += "#pragma data_seg(pop)\n\n";
5750 }
5751 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5752 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5753 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5754 Result += "&_OBJC_MODULES;\n";
5755 Result += "#pragma data_seg(pop)\n\n";
5756 }
5757}
5758
5759/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5760/// implementation.
5761void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5762 std::string &Result) {
5763 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5764 // Find category declaration for this implementation.
5765 ObjCCategoryDecl *CDecl;
5766 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5767 CDecl = CDecl->getNextClassCategory())
5768 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5769 break;
5770
5771 std::string FullCategoryName = ClassDecl->getNameAsString();
5772 FullCategoryName += '_';
5773 FullCategoryName += IDecl->getNameAsString();
5774
5775 // Build _objc_method_list for class's instance methods if needed
5776 SmallVector<ObjCMethodDecl *, 32>
5777 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5778
5779 // If any of our property implementations have associated getters or
5780 // setters, produce metadata for them as well.
5781 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5782 PropEnd = IDecl->propimpl_end();
5783 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005784 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005785 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005786 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005787 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005788 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005789 if (!PD)
5790 continue;
5791 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5792 InstanceMethods.push_back(Getter);
5793 if (PD->isReadOnly())
5794 continue;
5795 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5796 InstanceMethods.push_back(Setter);
5797 }
5798 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5799 true, "CATEGORY_", FullCategoryName.c_str(),
5800 Result);
5801
5802 // Build _objc_method_list for class's class methods if needed
5803 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5804 false, "CATEGORY_", FullCategoryName.c_str(),
5805 Result);
5806
5807 // Protocols referenced in class declaration?
5808 // Null CDecl is case of a category implementation with no category interface
5809 if (CDecl)
5810 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5811 FullCategoryName, Result);
5812 /* struct _objc_category {
5813 char *category_name;
5814 char *class_name;
5815 struct _objc_method_list *instance_methods;
5816 struct _objc_method_list *class_methods;
5817 struct _objc_protocol_list *protocols;
5818 // Objective-C 1.0 extensions
5819 uint32_t size; // sizeof (struct _objc_category)
5820 struct _objc_property_list *instance_properties; // category's own
5821 // @property decl.
5822 };
5823 */
5824
5825 static bool objc_category = false;
5826 if (!objc_category) {
5827 Result += "\nstruct _objc_category {\n";
5828 Result += "\tchar *category_name;\n";
5829 Result += "\tchar *class_name;\n";
5830 Result += "\tstruct _objc_method_list *instance_methods;\n";
5831 Result += "\tstruct _objc_method_list *class_methods;\n";
5832 Result += "\tstruct _objc_protocol_list *protocols;\n";
5833 Result += "\tunsigned int size;\n";
5834 Result += "\tstruct _objc_property_list *instance_properties;\n";
5835 Result += "};\n";
5836 objc_category = true;
5837 }
5838 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5839 Result += FullCategoryName;
5840 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5841 Result += IDecl->getNameAsString();
5842 Result += "\"\n\t, \"";
5843 Result += ClassDecl->getNameAsString();
5844 Result += "\"\n";
5845
5846 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5847 Result += "\t, (struct _objc_method_list *)"
5848 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5849 Result += FullCategoryName;
5850 Result += "\n";
5851 }
5852 else
5853 Result += "\t, 0\n";
5854 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5855 Result += "\t, (struct _objc_method_list *)"
5856 "&_OBJC_CATEGORY_CLASS_METHODS_";
5857 Result += FullCategoryName;
5858 Result += "\n";
5859 }
5860 else
5861 Result += "\t, 0\n";
5862
5863 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5864 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5865 Result += FullCategoryName;
5866 Result += "\n";
5867 }
5868 else
5869 Result += "\t, 0\n";
5870 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5871}
5872
5873// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5874/// class methods.
5875template<typename MethodIterator>
5876void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5877 MethodIterator MethodEnd,
5878 bool IsInstanceMethod,
5879 StringRef prefix,
5880 StringRef ClassName,
5881 std::string &Result) {
5882 if (MethodBegin == MethodEnd) return;
5883
5884 if (!objc_impl_method) {
5885 /* struct _objc_method {
5886 SEL _cmd;
5887 char *method_types;
5888 void *_imp;
5889 }
5890 */
5891 Result += "\nstruct _objc_method {\n";
5892 Result += "\tSEL _cmd;\n";
5893 Result += "\tchar *method_types;\n";
5894 Result += "\tvoid *_imp;\n";
5895 Result += "};\n";
5896
5897 objc_impl_method = true;
5898 }
5899
5900 // Build _objc_method_list for class's methods if needed
5901
5902 /* struct {
5903 struct _objc_method_list *next_method;
5904 int method_count;
5905 struct _objc_method method_list[];
5906 }
5907 */
5908 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5909 Result += "\nstatic struct {\n";
5910 Result += "\tstruct _objc_method_list *next_method;\n";
5911 Result += "\tint method_count;\n";
5912 Result += "\tstruct _objc_method method_list[";
5913 Result += utostr(NumMethods);
5914 Result += "];\n} _OBJC_";
5915 Result += prefix;
5916 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5917 Result += "_METHODS_";
5918 Result += ClassName;
5919 Result += " __attribute__ ((used, section (\"__OBJC, __";
5920 Result += IsInstanceMethod ? "inst" : "cls";
5921 Result += "_meth\")))= ";
5922 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5923
5924 Result += "\t,{{(SEL)\"";
5925 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5926 std::string MethodTypeString;
5927 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5928 Result += "\", \"";
5929 Result += MethodTypeString;
5930 Result += "\", (void *)";
5931 Result += MethodInternalNames[*MethodBegin];
5932 Result += "}\n";
5933 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5934 Result += "\t ,{(SEL)\"";
5935 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5936 std::string MethodTypeString;
5937 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5938 Result += "\", \"";
5939 Result += MethodTypeString;
5940 Result += "\", (void *)";
5941 Result += MethodInternalNames[*MethodBegin];
5942 Result += "}\n";
5943 }
5944 Result += "\t }\n};\n";
5945}
5946
5947Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5948 SourceRange OldRange = IV->getSourceRange();
5949 Expr *BaseExpr = IV->getBase();
5950
5951 // Rewrite the base, but without actually doing replaces.
5952 {
5953 DisableReplaceStmtScope S(*this);
5954 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5955 IV->setBase(BaseExpr);
5956 }
5957
5958 ObjCIvarDecl *D = IV->getDecl();
5959
5960 Expr *Replacement = IV;
5961 if (CurMethodDef) {
5962 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5963 const ObjCInterfaceType *iFaceDecl =
5964 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5965 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5966 // lookup which class implements the instance variable.
5967 ObjCInterfaceDecl *clsDeclared = 0;
5968 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5969 clsDeclared);
5970 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5971
5972 // Synthesize an explicit cast to gain access to the ivar.
5973 std::string RecName = clsDeclared->getIdentifier()->getName();
5974 RecName += "_IMPL";
5975 IdentifierInfo *II = &Context->Idents.get(RecName);
5976 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5977 SourceLocation(), SourceLocation(),
5978 II);
5979 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5980 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5981 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5982 CK_BitCast,
5983 IV->getBase());
5984 // Don't forget the parens to enforce the proper binding.
5985 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5986 OldRange.getEnd(),
5987 castExpr);
5988 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005989 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005990 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5991 IV->getLocation(),
5992 D->getType(),
5993 VK_LValue, OK_Ordinary);
5994 Replacement = ME;
5995 } else {
5996 IV->setBase(PE);
5997 }
5998 }
5999 } else { // we are outside a method.
6000 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6001
6002 // Explicit ivar refs need to have a cast inserted.
6003 // FIXME: consider sharing some of this code with the code above.
6004 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6005 const ObjCInterfaceType *iFaceDecl =
6006 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6007 // lookup which class implements the instance variable.
6008 ObjCInterfaceDecl *clsDeclared = 0;
6009 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6010 clsDeclared);
6011 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6012
6013 // Synthesize an explicit cast to gain access to the ivar.
6014 std::string RecName = clsDeclared->getIdentifier()->getName();
6015 RecName += "_IMPL";
6016 IdentifierInfo *II = &Context->Idents.get(RecName);
6017 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6018 SourceLocation(), SourceLocation(),
6019 II);
6020 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6021 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6022 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6023 CK_BitCast,
6024 IV->getBase());
6025 // Don't forget the parens to enforce the proper binding.
6026 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6027 IV->getBase()->getLocEnd(), castExpr);
6028 // Cannot delete IV->getBase(), since PE points to it.
6029 // Replace the old base with the cast. This is important when doing
6030 // embedded rewrites. For example, [newInv->_container addObject:0].
6031 IV->setBase(PE);
6032 }
6033 }
6034
6035 ReplaceStmtWithRange(IV, Replacement, OldRange);
6036 return Replacement;
6037}