blob: 5cf1b11ad9a821da4b93d0ec85c955f85b3d37e9 [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;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockDeclRefExpr *, 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);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000323 Stmt *RewriteBlockDeclRefExpr(Expr *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
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Fariborz Jahanian58457172011-12-05 18:43:13 +0000359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000378 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000380 std::string SynthesizeBlockImpl(BlockExpr *CE,
381 std::string Tag, std::string Desc);
382 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000385 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000386 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000387 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000389 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Fariborz Jahanian58457172011-12-05 18:43:13 +0000393 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000394 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000395 void WarnAboutReturnGotoStmts(Stmt *S);
396 void HasReturnStmts(Stmt *S, bool &hasReturns);
397 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000402 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000403 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000404 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000405 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000406 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 // We avoid calling Type::isBlockPointerType(), since it operates on the
409 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000410 bool isTopLevelBlockPointerType(QualType T) {
411 return isa<BlockPointerType>(T);
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000414 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415 /// to a function pointer type and upon success, returns true; false
416 /// otherwise.
417 bool convertBlockPointerToFunctionPointer(QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
419 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420 T = Context->getPointerType(BPT->getPointeeType());
421 return true;
422 }
423 return false;
424 }
425
Fariborz Jahanian58457172011-12-05 18:43:13 +0000426 bool needToScanForQualifiers(QualType T);
427 QualType getSuperStructType();
428 QualType getConstantStringStructType();
429 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000432 void convertToUnqualifiedObjCType(QualType &T) {
433 if (T->isObjCQualifiedIdType())
434 T = Context->getObjCIdType();
435 else if (T->isObjCQualifiedClassType())
436 T = Context->getObjCClassType();
437 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000438 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439 if (const ObjCObjectPointerType * OBJPT =
440 T->getAsObjCInterfacePointerType()) {
441 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442 T = QualType(IFaceT, 0);
443 T = Context->getPointerType(T);
444 }
445 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000446 }
447
Steve Naroff54055232008-10-27 17:20:55 +0000448 // FIXME: This predicate seems like it would be useful to add to ASTContext.
449 bool isObjCType(QualType T) {
450 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Steve Naroff54055232008-10-27 17:20:55 +0000453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff54055232008-10-27 17:20:55 +0000455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
457 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Ted Kremenek6217b802009-07-29 21:53:49 +0000459 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000461 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000462 return true;
463 }
464 return false;
465 }
466 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000467 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000468 void GetExtentOfArgList(const char *Name, const char *&LParen,
469 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000470
Steve Naroff621edce2009-04-29 16:37:50 +0000471 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000472 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000473 if (From[i] == '"')
474 To += "\\\"";
475 else
476 To += From[i];
477 }
478 }
John McCalle23cf432010-12-14 08:05:40 +0000479
480 QualType getSimpleFunctionType(QualType result,
481 const QualType *args,
482 unsigned numArgs,
483 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
488 return Context->getFunctionType(result, args, numArgs, fpi);
489 }
John McCall9d125032010-01-15 18:39:57 +0000490
Fariborz Jahanian58457172011-12-05 18:43:13 +0000491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
496 SourceLocation(), SourceLocation());
497 }
498 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000499
500 class RewriteObjCFragileABI : public RewriteObjC {
501 public:
502
503 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
504 DiagnosticsEngine &D, const LangOptions &LOpts,
505 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
506 D, LOpts,
507 silenceMacroWarn) {}
508
509 ~RewriteObjCFragileABI() {}
510 virtual void Initialize(ASTContext &context);
511
512 // Rewriting metadata
513 template<typename MethodIterator>
514 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
515 MethodIterator MethodEnd,
516 bool IsInstanceMethod,
517 StringRef prefix,
518 StringRef ClassName,
519 std::string &Result);
520 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
521 StringRef prefix,
522 StringRef ClassName,
523 std::string &Result);
524 virtual void RewriteObjCProtocolListMetaData(
525 const ObjCList<ObjCProtocolDecl> &Prots,
526 StringRef prefix, StringRef ClassName, std::string &Result);
527 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
528 std::string &Result);
529 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
530 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
531 std::string &Result);
532
533 // Rewriting ivar
534 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
535 std::string &Result);
536 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
537 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000538}
539
Mike Stump1eb44332009-09-09 15:08:12 +0000540void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
541 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000542 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000543 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000545 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000546 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000547 // All the args are checked/rewritten. Don't call twice!
548 RewriteBlockPointerDecl(D);
549 break;
550 }
551 }
552}
553
554void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000556 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000557 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000558}
559
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000560static bool IsHeaderFile(const std::string &Filename) {
561 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000563 if (DotPos == std::string::npos) {
564 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000565 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000568 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
569 // C header: .h
570 // C++ header: .hh or .H;
571 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000572}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000573
Chris Lattner5f9e2722011-07-23 10:55:15 +0000574RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000575 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000576 bool silenceMacroWarn)
577 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
578 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000579 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000580 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000581 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000582 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
583 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000584 "rewriter doesn't support user-specified control flow semantics "
585 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000586}
587
Eli Friedmanbce831b2009-05-18 22:29:17 +0000588ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000590 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000591 const LangOptions &LOpts,
592 bool SilenceRewriteMacroWarning) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000593 if (true /*!LOpts.ObjCNonFragileABI*/)
594 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
595 else {
596 assert(false && "objective-C rewriter for nonfragile ABI = NYI");
597 return 0;
598 }
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
Chris Lattner2c78b872009-04-14 23:22:57 +0000638 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
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)
975 RewriteProperty(*I);
976
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)
1009 RewriteProperty(*I);
1010
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 (*)(...)".
1145 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001146 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001147 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001148 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001149 ResultStr += Name;
1150 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001151 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001152 if (OMD->isVariadic())
1153 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001154 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Steve Naroff76e429d2008-07-16 14:40:40 +00001156 if (FPRetType) {
1157 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Steve Naroff76e429d2008-07-16 14:40:40 +00001159 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001160 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001161 ResultStr += "(";
1162 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1163 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001164 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001165 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001166 ResultStr += ParamStr;
1167 }
1168 if (FT->isVariadic()) {
1169 if (FT->getNumArgs()) ResultStr += ", ";
1170 ResultStr += "...";
1171 }
1172 ResultStr += ")";
1173 } else {
1174 ResultStr += "()";
1175 }
1176 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001178void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1180 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001182 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001184 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001185 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1186 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001187 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001188 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001189 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001190 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001191 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001192 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001193
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194 const char *startBuf = SM->getCharacterData(LocStart);
1195 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001196 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001197 }
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001200 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1201 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001202 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001203 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001204 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001205 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001206 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001207 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001209 const char *startBuf = SM->getCharacterData(LocStart);
1210 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001211 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001212 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001213 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001215 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001216 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001217 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001218 }
1219
Benjamin Kramerd999b372010-02-14 14:14:16 +00001220 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001221}
1222
Steve Naroffb29b4272008-04-14 22:03:09 +00001223void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001224 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001225 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001226 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001227 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001228 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001229 ResultStr += "\n";
1230 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001231 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001232 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001233 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001234 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001235 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001236 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001237 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001238 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001239 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
1241 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001242 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001243 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001244 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001245 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001246 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001247 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001248 for (ObjCInterfaceDecl::classmeth_iterator
1249 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001250 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001251 RewriteMethodDeclaration(*I);
1252
Steve Naroff2feac5e2007-10-30 03:43:13 +00001253 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001254 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1255 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001256}
1257
John McCall4b9c2d22011-11-06 09:01:30 +00001258Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1259 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001260
John McCall4b9c2d22011-11-06 09:01:30 +00001261 // We just magically know some things about the structure of this
1262 // expression.
1263 ObjCMessageExpr *OldMsg =
1264 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1265 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001266
John McCall4b9c2d22011-11-06 09:01:30 +00001267 // Because the rewriter doesn't allow us to rewrite rewritten code,
1268 // we need to suppress rewriting the sub-statements.
1269 Expr *Base, *RHS;
1270 {
1271 DisableReplaceStmtScope S(*this);
1272
1273 // Rebuild the base expression if we have one.
1274 Base = 0;
1275 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1276 Base = OldMsg->getInstanceReceiver();
1277 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1278 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1279 }
1280
1281 // Rebuild the RHS.
1282 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1283 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1284 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1285 }
1286
1287 // TODO: avoid this copy.
1288 SmallVector<SourceLocation, 1> SelLocs;
1289 OldMsg->getSelectorLocs(SelLocs);
1290
1291 ObjCMessageExpr *NewMsg;
1292 switch (OldMsg->getReceiverKind()) {
1293 case ObjCMessageExpr::Class:
1294 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1295 OldMsg->getValueKind(),
1296 OldMsg->getLeftLoc(),
1297 OldMsg->getClassReceiverTypeInfo(),
1298 OldMsg->getSelector(),
1299 SelLocs,
1300 OldMsg->getMethodDecl(),
1301 RHS,
1302 OldMsg->getRightLoc());
1303 break;
1304
1305 case ObjCMessageExpr::Instance:
1306 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1307 OldMsg->getValueKind(),
1308 OldMsg->getLeftLoc(),
1309 Base,
1310 OldMsg->getSelector(),
1311 SelLocs,
1312 OldMsg->getMethodDecl(),
1313 RHS,
1314 OldMsg->getRightLoc());
1315 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,
1329 OldMsg->getRightLoc());
1330 break;
1331 }
1332
1333 Stmt *Replacement = SynthMessageExpr(NewMsg);
1334 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1335 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001336}
1337
John McCall4b9c2d22011-11-06 09:01:30 +00001338Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1339 SourceRange OldRange = PseudoOp->getSourceRange();
1340
1341 // We just magically know some things about the structure of this
1342 // expression.
1343 ObjCMessageExpr *OldMsg =
1344 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1345
1346 // Because the rewriter doesn't allow us to rewrite rewritten code,
1347 // we need to suppress rewriting the sub-statements.
1348 Expr *Base = 0;
1349 {
1350 DisableReplaceStmtScope S(*this);
1351
1352 // Rebuild the base expression if we have one.
1353 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1354 Base = OldMsg->getInstanceReceiver();
1355 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1356 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001357 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001358 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001359
John McCall4b9c2d22011-11-06 09:01:30 +00001360 // Intentionally empty.
1361 SmallVector<SourceLocation, 1> SelLocs;
1362 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001363
John McCall4b9c2d22011-11-06 09:01:30 +00001364 ObjCMessageExpr *NewMsg;
1365 switch (OldMsg->getReceiverKind()) {
1366 case ObjCMessageExpr::Class:
1367 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1368 OldMsg->getValueKind(),
1369 OldMsg->getLeftLoc(),
1370 OldMsg->getClassReceiverTypeInfo(),
1371 OldMsg->getSelector(),
1372 SelLocs,
1373 OldMsg->getMethodDecl(),
1374 Args,
1375 OldMsg->getRightLoc());
1376 break;
1377
1378 case ObjCMessageExpr::Instance:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 Base,
1383 OldMsg->getSelector(),
1384 SelLocs,
1385 OldMsg->getMethodDecl(),
1386 Args,
1387 OldMsg->getRightLoc());
1388 break;
1389
1390 case ObjCMessageExpr::SuperClass:
1391 case ObjCMessageExpr::SuperInstance:
1392 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1393 OldMsg->getValueKind(),
1394 OldMsg->getLeftLoc(),
1395 OldMsg->getSuperLoc(),
1396 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1397 OldMsg->getSuperType(),
1398 OldMsg->getSelector(),
1399 SelLocs,
1400 OldMsg->getMethodDecl(),
1401 Args,
1402 OldMsg->getRightLoc());
1403 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001404 }
John McCall4b9c2d22011-11-06 09:01:30 +00001405
1406 Stmt *Replacement = SynthMessageExpr(NewMsg);
1407 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1408 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001409}
1410
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001411/// SynthCountByEnumWithState - To print:
1412/// ((unsigned int (*)
1413/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001414/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001416/// "countByEnumeratingWithState:objects:count:"),
1417/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001418/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001419///
Steve Naroffb29b4272008-04-14 22:03:09 +00001420void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001421 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1422 "id *, unsigned int))(void *)objc_msgSend)";
1423 buf += "\n\t\t";
1424 buf += "((id)l_collection,\n\t\t";
1425 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1426 buf += "\n\t\t";
1427 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001428 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001429}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001430
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001431/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1432/// statement to exit to its outer synthesized loop.
1433///
Steve Naroffb29b4272008-04-14 22:03:09 +00001434Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001435 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1436 return S;
1437 // replace break with goto __break_label
1438 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001440 SourceLocation startLoc = S->getLocStart();
1441 buf = "goto __break_label_";
1442 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001443 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001444
1445 return 0;
1446}
1447
1448/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1449/// statement to continue with its inner synthesized loop.
1450///
Steve Naroffb29b4272008-04-14 22:03:09 +00001451Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001452 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1453 return S;
1454 // replace continue with goto __continue_label
1455 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001456
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001457 SourceLocation startLoc = S->getLocStart();
1458 buf = "goto __continue_label_";
1459 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001460 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001462 return 0;
1463}
1464
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001465/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001466/// It rewrites:
1467/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001469/// Into:
1470/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001471/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001473/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001474/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001475/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001476/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001477/// if (limit) {
1478/// unsigned long startMutations = *enumState.mutationsPtr;
1479/// do {
1480/// unsigned long counter = 0;
1481/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001482/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001483/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001484/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001485/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001486/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001487/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001488/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001489/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001490/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001492/// }
1493/// else
1494/// elem = nil;
1495/// }
1496///
Steve Naroffb29b4272008-04-14 22:03:09 +00001497Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001498 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001499 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001500 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001501 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001502 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001503 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001507 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001508 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001509 std::string buf;
1510 buf = "\n{\n\t";
1511 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1512 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001513 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001514 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001515 if (ElementType->isObjCQualifiedIdType() ||
1516 ElementType->isObjCQualifiedInterfaceType())
1517 // Simply use 'id' for all qualified types.
1518 elementTypeAsString = "id";
1519 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001520 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001521 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001522 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001523 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 buf += elementName;
1525 buf += ";\n\t";
1526 }
Chris Lattner06767512008-04-08 05:52:18 +00001527 else {
1528 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001529 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001530 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1531 if (VD->getType()->isObjCQualifiedIdType() ||
1532 VD->getType()->isObjCQualifiedInterfaceType())
1533 // Simply use 'id' for all qualified types.
1534 elementTypeAsString = "id";
1535 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001536 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001537 }
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001539 // struct __objcFastEnumerationState enumState = { 0 };
1540 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001541 // id __rw_items[16];
1542 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 // id l_collection = (id)
1544 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001545 // Find start location of 'collection' the hard way!
1546 const char *startCollectionBuf = startBuf;
1547 startCollectionBuf += 3; // skip 'for'
1548 startCollectionBuf = strchr(startCollectionBuf, '(');
1549 startCollectionBuf++; // skip '('
1550 // find 'in' and skip it.
1551 while (*startCollectionBuf != ' ' ||
1552 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1553 (*(startCollectionBuf+3) != ' ' &&
1554 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1555 startCollectionBuf++;
1556 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001557
1558 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001559 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001560 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001561 SourceLocation rightParenLoc = S->getRParenLoc();
1562 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001563 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001567 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001569 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 // ((unsigned int (*)
1571 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001572 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001574 // "countByEnumeratingWithState:objects:count:"),
1575 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001576 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577 buf += "unsigned long limit =\n\t\t";
1578 SynthCountByEnumWithState(buf);
1579 buf += ";\n\t";
1580 /// if (limit) {
1581 /// unsigned long startMutations = *enumState.mutationsPtr;
1582 /// do {
1583 /// unsigned long counter = 0;
1584 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001585 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001587 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001588 buf += "if (limit) {\n\t";
1589 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1590 buf += "do {\n\t\t";
1591 buf += "unsigned long counter = 0;\n\t\t";
1592 buf += "do {\n\t\t\t";
1593 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1594 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1595 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001596 buf += " = (";
1597 buf += elementTypeAsString;
1598 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001600 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001602 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001604 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001605 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001606 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001607 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001608 /// }
1609 /// else
1610 /// elem = nil;
1611 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001612 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 buf = ";\n\t";
1614 buf += "__continue_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
1616 buf += ": ;";
1617 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001618 buf += "} while (counter < limit);\n\t";
1619 buf += "} while (limit = ";
1620 SynthCountByEnumWithState(buf);
1621 buf += ");\n\t";
1622 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001623 buf += " = ((";
1624 buf += elementTypeAsString;
1625 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001626 buf += "__break_label_";
1627 buf += utostr(ObjCBcLabelNo.back());
1628 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 buf += "}\n\t";
1630 buf += "else\n\t\t";
1631 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001632 buf += " = ((";
1633 buf += elementTypeAsString;
1634 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001635 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001636
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001637 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001638 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001639 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001640 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001641 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001642 } else {
1643 /* Need to treat single statements specially. For example:
1644 *
1645 * for (A *a in b) if (stuff()) break;
1646 * for (A *a in b) xxxyy;
1647 *
1648 * The following code simply scans ahead to the semi to find the actual end.
1649 */
1650 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1651 const char *semiBuf = strchr(stmtBuf, ';');
1652 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001653 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001654 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001655 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001656 Stmts.pop_back();
1657 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001658 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001659}
1660
Mike Stump1eb44332009-09-09 15:08:12 +00001661/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001662/// This routine rewrites @synchronized(expr) stmt;
1663/// into:
1664/// objc_sync_enter(expr);
1665/// @try stmt @finally { objc_sync_exit(expr); }
1666///
Steve Naroffb29b4272008-04-14 22:03:09 +00001667Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001668 // Get the start location and compute the semi location.
1669 SourceLocation startLoc = S->getLocStart();
1670 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001671
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001672 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001673
1674 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001675 buf = "objc_sync_enter((id)";
1676 const char *lparenBuf = startBuf;
1677 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001678 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1680 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001681 // been rewritten! (which implies the SourceLocation's are invalid).
1682 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001683 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001684 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001685 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001686 buf = ");\n";
1687 // declare a new scope with two variables, _stack and _rethrow.
1688 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1689 buf += "int buf[18/*32-bit i386*/];\n";
1690 buf += "char *pointers[4];} _stack;\n";
1691 buf += "id volatile _rethrow = 0;\n";
1692 buf += "objc_exception_try_enter(&_stack);\n";
1693 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001694 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001695 startLoc = S->getSynchBody()->getLocEnd();
1696 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Steve Naroffc7089f12008-08-19 13:04:19 +00001698 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001699 SourceLocation lastCurlyLoc = startLoc;
1700 buf = "}\nelse {\n";
1701 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001702 buf += "}\n";
1703 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001704 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001705
1706 std::string syncBuf;
1707 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001708
1709 Expr *syncExpr = S->getSynchExpr();
1710 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1711 ? CK_BitCast :
1712 syncExpr->getType()->isBlockPointerType()
1713 ? CK_BlockPointerToObjCPointerCast
1714 : CK_CPointerToObjCPointerCast;
1715 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1716 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001717 std::string syncExprBufS;
1718 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001719 syncExpr->printPretty(syncExprBuf, *Context, 0,
1720 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001721 syncBuf += syncExprBuf.str();
1722 syncBuf += ");";
1723
1724 buf += syncBuf;
1725 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001726 buf += "}\n";
1727 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Benjamin Kramerd999b372010-02-14 14:14:16 +00001729 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001730
1731 bool hasReturns = false;
1732 HasReturnStmts(S->getSynchBody(), hasReturns);
1733 if (hasReturns)
1734 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1735
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001736 return 0;
1737}
1738
Steve Naroffb85e77a2009-12-05 21:43:12 +00001739void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1740{
Steve Naroff8c565152008-12-05 17:03:39 +00001741 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001742 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001743 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001744 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001745
Steve Naroffb85e77a2009-12-05 21:43:12 +00001746 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001747 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001748 TryFinallyContainsReturnDiag);
1749 }
1750 return;
1751}
1752
Steve Naroffb85e77a2009-12-05 21:43:12 +00001753void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1754{
1755 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001756 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001757 if (*CI)
1758 HasReturnStmts(*CI, hasReturns);
1759
1760 if (isa<ReturnStmt>(S))
1761 hasReturns = true;
1762 return;
1763}
1764
1765void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1766 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001767 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001768 if (*CI) {
1769 RewriteTryReturnStmts(*CI);
1770 }
1771 if (isa<ReturnStmt>(S)) {
1772 SourceLocation startLoc = S->getLocStart();
1773 const char *startBuf = SM->getCharacterData(startLoc);
1774
1775 const char *semiBuf = strchr(startBuf, ';');
1776 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001777 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001778
1779 std::string buf;
1780 buf = "{ objc_exception_try_exit(&_stack); return";
1781
Benjamin Kramerd999b372010-02-14 14:14:16 +00001782 ReplaceText(startLoc, 6, buf);
1783 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001784 }
1785 return;
1786}
1787
1788void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1789 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001790 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001791 if (*CI) {
1792 RewriteSyncReturnStmts(*CI, syncExitBuf);
1793 }
1794 if (isa<ReturnStmt>(S)) {
1795 SourceLocation startLoc = S->getLocStart();
1796 const char *startBuf = SM->getCharacterData(startLoc);
1797
1798 const char *semiBuf = strchr(startBuf, ';');
1799 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001800 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001801
1802 std::string buf;
1803 buf = "{ objc_exception_try_exit(&_stack);";
1804 buf += syncExitBuf;
1805 buf += " return";
1806
Benjamin Kramerd999b372010-02-14 14:14:16 +00001807 ReplaceText(startLoc, 6, buf);
1808 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001809 }
1810 return;
1811}
1812
Steve Naroffb29b4272008-04-14 22:03:09 +00001813Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001814 // Get the start location and compute the semi location.
1815 SourceLocation startLoc = S->getLocStart();
1816 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001817
Steve Naroff75730982007-11-07 04:08:17 +00001818 assert((*startBuf == '@') && "bogus @try location");
1819
1820 std::string buf;
1821 // declare a new scope with two variables, _stack and _rethrow.
1822 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1823 buf += "int buf[18/*32-bit i386*/];\n";
1824 buf += "char *pointers[4];} _stack;\n";
1825 buf += "id volatile _rethrow = 0;\n";
1826 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001827 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001828
Benjamin Kramerd999b372010-02-14 14:14:16 +00001829 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Steve Naroff75730982007-11-07 04:08:17 +00001831 startLoc = S->getTryBody()->getLocEnd();
1832 startBuf = SM->getCharacterData(startLoc);
1833
1834 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001835
Steve Naroff75730982007-11-07 04:08:17 +00001836 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001837 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001838 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001839 buf = " /* @catch begin */ else {\n";
1840 buf += " id _caught = objc_exception_extract(&_stack);\n";
1841 buf += " objc_exception_try_enter (&_stack);\n";
1842 buf += " if (_setjmp(_stack.buf))\n";
1843 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1844 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Benjamin Kramerd999b372010-02-14 14:14:16 +00001846 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001847 } else { /* no catch list */
1848 buf = "}\nelse {\n";
1849 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1850 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001851 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001852 }
Steve Naroff75730982007-11-07 04:08:17 +00001853 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001854 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1855 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001856 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001857
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001858 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001859 buf = "if ("; // we are generating code for the first catch clause
1860 else
1861 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001862 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001863 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Steve Naroff75730982007-11-07 04:08:17 +00001865 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Steve Naroff75730982007-11-07 04:08:17 +00001867 const char *lParenLoc = strchr(startBuf, '(');
1868
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001869 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001870 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001871 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001872 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1873 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001874 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001875 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001876 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Steve Naroffe12e6922008-02-01 20:02:07 +00001878 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001879 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001880 } else if (catchDecl) {
1881 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001882 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001883 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001884 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001885 } else if (const ObjCObjectPointerType *Ptr =
1886 t->getAs<ObjCObjectPointerType>()) {
1887 // Should be a pointer to a class.
1888 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1889 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001890 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001891 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001892 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001893 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001894 }
1895 }
1896 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001897 lastCatchBody = Catch->getCatchBody();
1898 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001899 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1900 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1901 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1902 assert((*rParenBuf == ')') && "bogus @catch paren location");
1903 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001904
Mike Stump1eb44332009-09-09 15:08:12 +00001905 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001906 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001907 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001908 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001909 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001910 }
Steve Naroff75730982007-11-07 04:08:17 +00001911 }
1912 // Complete the catch list...
1913 if (lastCatchBody) {
1914 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001915 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1916 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Steve Naroff378f47a2008-09-11 15:29:03 +00001918 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001919 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001920 buf = "} /* last catch end */\n";
1921 buf += "else {\n";
1922 buf += " _rethrow = _caught;\n";
1923 buf += " objc_exception_try_exit(&_stack);\n";
1924 buf += "} } /* @catch end */\n";
1925 if (!S->getFinallyStmt())
1926 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001927 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Steve Naroff75730982007-11-07 04:08:17 +00001929 // Set lastCurlyLoc
1930 lastCurlyLoc = lastCatchBody->getLocEnd();
1931 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001933 startLoc = finalStmt->getLocStart();
1934 startBuf = SM->getCharacterData(startLoc);
1935 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Benjamin Kramerd999b372010-02-14 14:14:16 +00001937 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Steve Naroff75730982007-11-07 04:08:17 +00001939 Stmt *body = finalStmt->getFinallyBody();
1940 SourceLocation startLoc = body->getLocStart();
1941 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001942 assert(*SM->getCharacterData(startLoc) == '{' &&
1943 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001944 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001945 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001947 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001948 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001949 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001950 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Steve Naroff75730982007-11-07 04:08:17 +00001952 // Set lastCurlyLoc
1953 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroff8c565152008-12-05 17:03:39 +00001955 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001956 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001957 } else { /* no finally clause - make sure we synthesize an implicit one */
1958 buf = "{ /* implicit finally clause */\n";
1959 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1960 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1961 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001962 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001963
1964 // Now check for any return/continue/go statements within the @try.
1965 // The implicit finally clause won't called if the @try contains any
1966 // jump statements.
1967 bool hasReturns = false;
1968 HasReturnStmts(S->getTryBody(), hasReturns);
1969 if (hasReturns)
1970 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001971 }
1972 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001973 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001974 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001975 return 0;
1976}
1977
Mike Stump1eb44332009-09-09 15:08:12 +00001978// This can't be done with ReplaceStmt(S, ThrowExpr), since
1979// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001980// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001981Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001982 // Get the start location and compute the semi location.
1983 SourceLocation startLoc = S->getLocStart();
1984 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Steve Naroff2bd03922007-11-07 15:32:26 +00001986 assert((*startBuf == '@') && "bogus @throw location");
1987
1988 std::string buf;
1989 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001990 if (S->getThrowExpr())
1991 buf = "objc_exception_throw(";
1992 else // add an implicit argument
1993 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001995 // handle "@ throw" correctly.
1996 const char *wBuf = strchr(startBuf, 'w');
1997 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001998 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Steve Naroff2bd03922007-11-07 15:32:26 +00002000 const char *semiBuf = strchr(startBuf, ';');
2001 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002002 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002003 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002004 return 0;
2005}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002006
Steve Naroffb29b4272008-04-14 22:03:09 +00002007Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002008 // Create a new string expression.
2009 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002010 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002011 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002012 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002013 StringLiteral::Ascii, false,
2014 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002015 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002016
Chris Lattner07506182007-11-30 22:53:43 +00002017 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002018 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002019 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002020}
2021
Steve Naroffb29b4272008-04-14 22:03:09 +00002022Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002023 if (!SelGetUidFunctionDecl)
2024 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002025 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2026 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002027 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002028 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002029 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002030 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002031 StringLiteral::Ascii, false,
2032 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002033 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2034 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002035 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002036 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002037 return SelExp;
2038}
2039
Steve Naroffb29b4272008-04-14 22:03:09 +00002040CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002041 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2042 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002043 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002044 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Steve Naroffebf2b562007-10-23 23:50:29 +00002046 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002047 DeclRefExpr *DRE =
2048 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Steve Naroffebf2b562007-10-23 23:50:29 +00002050 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002051 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002052 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002053 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002054 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002055
John McCall183700f2009-09-21 23:43:11 +00002056 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002058 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002059 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002060 FT->getCallResultType(*Context),
2061 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002062 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002063}
2064
Steve Naroffd5255f52007-11-01 13:24:47 +00002065static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2066 const char *&startRef, const char *&endRef) {
2067 while (startBuf < endBuf) {
2068 if (*startBuf == '<')
2069 startRef = startBuf; // mark the start.
2070 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002071 if (startRef && *startRef == '<') {
2072 endRef = startBuf; // mark the end.
2073 return true;
2074 }
2075 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002076 }
2077 startBuf++;
2078 }
2079 return false;
2080}
2081
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002082static void scanToNextArgument(const char *&argRef) {
2083 int angle = 0;
2084 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2085 if (*argRef == '<')
2086 angle++;
2087 else if (*argRef == '>')
2088 angle--;
2089 argRef++;
2090 }
2091 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2092}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002093
Steve Naroffb29b4272008-04-14 22:03:09 +00002094bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002095 if (T->isObjCQualifiedIdType())
2096 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002097 if (const PointerType *PT = T->getAs<PointerType>()) {
2098 if (PT->getPointeeType()->isObjCQualifiedIdType())
2099 return true;
2100 }
2101 if (T->isObjCObjectPointerType()) {
2102 T = T->getPointeeType();
2103 return T->isObjCQualifiedInterfaceType();
2104 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002105 if (T->isArrayType()) {
2106 QualType ElemTy = Context->getBaseElementType(T);
2107 return needToScanForQualifiers(ElemTy);
2108 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002109 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002110}
2111
Steve Naroff4f95b752008-07-29 18:15:38 +00002112void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2113 QualType Type = E->getType();
2114 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002115 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Steve Naroffcda658e2008-11-19 21:15:47 +00002117 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2118 Loc = ECE->getLParenLoc();
2119 EndLoc = ECE->getRParenLoc();
2120 } else {
2121 Loc = E->getLocStart();
2122 EndLoc = E->getLocEnd();
2123 }
2124 // This will defend against trying to rewrite synthesized expressions.
2125 if (Loc.isInvalid() || EndLoc.isInvalid())
2126 return;
2127
Steve Naroff4f95b752008-07-29 18:15:38 +00002128 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002129 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002130 const char *startRef = 0, *endRef = 0;
2131 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2132 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002133 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2134 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002135 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002136 InsertText(LessLoc, "/*");
2137 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002138 }
2139 }
2140}
2141
Steve Naroffb29b4272008-04-14 22:03:09 +00002142void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002143 SourceLocation Loc;
2144 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002145 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002146 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2147 Loc = VD->getLocation();
2148 Type = VD->getType();
2149 }
2150 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2151 Loc = FD->getLocation();
2152 // Check for ObjC 'id' and class types that have been adorned with protocol
2153 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002154 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002155 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002156 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002157 if (!proto)
2158 return;
2159 Type = proto->getResultType();
2160 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002161 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2162 Loc = FD->getLocation();
2163 Type = FD->getType();
2164 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002165 else
2166 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002168 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002169 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Steve Naroffd5255f52007-11-01 13:24:47 +00002171 const char *endBuf = SM->getCharacterData(Loc);
2172 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002173 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002174 startBuf--; // scan backward (from the decl location) for return type.
2175 const char *startRef = 0, *endRef = 0;
2176 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2177 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002178 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2179 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002180 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002181 InsertText(LessLoc, "/*");
2182 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002183 }
2184 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002185 if (!proto)
2186 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002187 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002188 const char *startBuf = SM->getCharacterData(Loc);
2189 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002190 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2191 if (needToScanForQualifiers(proto->getArgType(i))) {
2192 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Steve Naroffd5255f52007-11-01 13:24:47 +00002194 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002195 // scan forward (from the decl location) for argument types.
2196 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002197 const char *startRef = 0, *endRef = 0;
2198 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2199 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002200 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002201 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002202 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002203 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002204 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002205 InsertText(LessLoc, "/*");
2206 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002207 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002208 startBuf = ++endBuf;
2209 }
2210 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002211 // If the function name is derived from a macro expansion, then the
2212 // argument buffer will not follow the name. Need to speak with Chris.
2213 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002214 startBuf++; // scan forward (from the decl location) for argument types.
2215 startBuf++;
2216 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002217 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002218}
2219
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002220void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2221 QualType QT = ND->getType();
2222 const Type* TypePtr = QT->getAs<Type>();
2223 if (!isa<TypeOfExprType>(TypePtr))
2224 return;
2225 while (isa<TypeOfExprType>(TypePtr)) {
2226 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2227 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2228 TypePtr = QT->getAs<Type>();
2229 }
2230 // FIXME. This will not work for multiple declarators; as in:
2231 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002232 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002233 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2234 const char *startBuf = SM->getCharacterData(DeclLoc);
2235 if (ND->getInit()) {
2236 std::string Name(ND->getNameAsString());
2237 TypeAsString += " " + Name + " = ";
2238 Expr *E = ND->getInit();
2239 SourceLocation startLoc;
2240 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2241 startLoc = ECE->getLParenLoc();
2242 else
2243 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002244 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002245 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002246 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002247 }
2248 else {
2249 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002250 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002251 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002252 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002253 }
2254}
2255
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002256// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002257void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002258 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002259 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002260 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002261 QualType getFuncType =
2262 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002263 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002264 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002265 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002266 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002267 SC_Extern,
2268 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002269}
2270
Steve Naroffb29b4272008-04-14 22:03:09 +00002271void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002272 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002273 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002274 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002275 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002276 return;
2277 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002278 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002279}
2280
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002281void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002282 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002283 const char *argPtr = TypeString.c_str();
2284 if (!strchr(argPtr, '^')) {
2285 Str += TypeString;
2286 return;
2287 }
2288 while (*argPtr) {
2289 Str += (*argPtr == '^' ? '*' : *argPtr);
2290 argPtr++;
2291 }
2292}
2293
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002294// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002295void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2296 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002297 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002298 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002299 const char *argPtr = TypeString.c_str();
2300 int paren = 0;
2301 while (*argPtr) {
2302 switch (*argPtr) {
2303 case '(':
2304 Str += *argPtr;
2305 paren++;
2306 break;
2307 case ')':
2308 Str += *argPtr;
2309 paren--;
2310 break;
2311 case '^':
2312 Str += '*';
2313 if (paren == 1)
2314 Str += VD->getNameAsString();
2315 break;
2316 default:
2317 Str += *argPtr;
2318 break;
2319 }
2320 argPtr++;
2321 }
2322}
2323
2324
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002325void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2326 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2327 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2328 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2329 if (!proto)
2330 return;
2331 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002332 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002333 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002334 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002335 FdStr += "(";
2336 unsigned numArgs = proto->getNumArgs();
2337 for (unsigned i = 0; i < numArgs; i++) {
2338 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002339 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002340 if (i+1 < numArgs)
2341 FdStr += ", ";
2342 }
2343 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002344 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002345 CurFunctionDeclToDeclareForBlock = 0;
2346}
2347
Steve Naroffc0a123c2008-03-11 17:37:02 +00002348// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002349void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002350 if (SuperContructorFunctionDecl)
2351 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002352 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002353 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002354 QualType argT = Context->getObjCIdType();
2355 assert(!argT.isNull() && "Can't find 'id' type");
2356 ArgTys.push_back(argT);
2357 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002358 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2359 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002360 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002361 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002362 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002363 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002364 SC_Extern,
2365 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002366}
2367
Steve Naroff09b266e2007-10-30 23:14:51 +00002368// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002369void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002370 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002371 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002372 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002373 assert(!argT.isNull() && "Can't find 'id' type");
2374 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002375 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002376 assert(!argT.isNull() && "Can't find 'SEL' type");
2377 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002378 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2379 &ArgTys[0], ArgTys.size(),
2380 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002381 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002382 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002383 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002384 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002385 SC_Extern,
2386 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002387}
2388
Steve Naroff874e2322007-11-15 10:28:18 +00002389// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002390void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002391 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002393 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002394 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002395 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002396 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2397 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2398 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002399 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002400 assert(!argT.isNull() && "Can't find 'SEL' type");
2401 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002402 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2403 &ArgTys[0], ArgTys.size(),
2404 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002405 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002406 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002407 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002408 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002409 SC_Extern,
2410 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002411}
2412
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002413// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002414void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002416 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002417 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002418 assert(!argT.isNull() && "Can't find 'id' type");
2419 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002420 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002421 assert(!argT.isNull() && "Can't find 'SEL' type");
2422 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002423 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002424 &ArgTys[0], ArgTys.size(),
2425 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002426 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002427 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002428 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002429 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002430 SC_Extern,
2431 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002432}
2433
Mike Stump1eb44332009-09-09 15:08:12 +00002434// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002435// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002436void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002437 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002438 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002439 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002440 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002441 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002442 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002443 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2444 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2445 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002446 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002447 assert(!argT.isNull() && "Can't find 'SEL' type");
2448 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002449 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002450 &ArgTys[0], ArgTys.size(),
2451 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002452 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002453 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002454 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002455 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002456 SC_Extern,
2457 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002458}
2459
Steve Naroff1284db82008-05-08 22:02:18 +00002460// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002461void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002462 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002463 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002464 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002465 assert(!argT.isNull() && "Can't find 'id' type");
2466 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002467 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002468 assert(!argT.isNull() && "Can't find 'SEL' type");
2469 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002470 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2471 &ArgTys[0], ArgTys.size(),
2472 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002473 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002474 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002475 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002476 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002477 SC_Extern,
2478 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002479}
2480
Steve Naroff09b266e2007-10-30 23:14:51 +00002481// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002482void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002483 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002484 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002485 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002486 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2487 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002488 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002489 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002490 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002491 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002492 SC_Extern,
2493 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002494}
2495
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002496// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2497void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2498 IdentifierInfo *getSuperClassIdent =
2499 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002500 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002501 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002502 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2503 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002504 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002505 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002506 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002507 getSuperClassIdent,
2508 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002509 SC_Extern,
2510 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002511 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002512}
2513
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002514// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002515void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002516 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002517 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002518 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002519 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2520 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002521 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002522 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002523 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002524 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002525 SC_Extern,
2526 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002527}
2528
Steve Naroffb29b4272008-04-14 22:03:09 +00002529Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002530 QualType strType = getConstantStringStructType();
2531
2532 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002533
2534 std::string tmpName = InFileName;
2535 unsigned i;
2536 for (i=0; i < tmpName.length(); i++) {
2537 char c = tmpName.at(i);
2538 // replace any non alphanumeric characters with '_'.
2539 if (!isalpha(c) && (c < '0' || c > '9'))
2540 tmpName[i] = '_';
2541 }
2542 S += tmpName;
2543 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002544 S += utostr(NumObjCStringLiterals++);
2545
Steve Naroffba92b2e2008-03-27 22:29:16 +00002546 Preamble += "static __NSConstantStringImpl " + S;
2547 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2548 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002549 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002550 std::string prettyBufS;
2551 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002552 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2553 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002554 Preamble += prettyBuf.str();
2555 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002556 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002557
2558 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002559 SourceLocation(), &Context->Idents.get(S),
2560 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002561 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2562 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002563 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002564 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002565 VK_RValue, OK_Ordinary,
2566 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002567 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002568 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002569 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002570 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002571 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002572 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002573}
2574
Steve Naroff874e2322007-11-15 10:28:18 +00002575// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002576QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002577 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002578 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002579 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002580 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002581 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Steve Naroff874e2322007-11-15 10:28:18 +00002583 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002584 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002585 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002586 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002587
Steve Naroff874e2322007-11-15 10:28:18 +00002588 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002589 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002590 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002591 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002592 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002593 FieldTypes[i], 0,
2594 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002595 /*Mutable=*/false,
2596 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002597 }
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor838db382010-02-11 01:19:42 +00002599 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002600 }
2601 return Context->getTagDeclType(SuperStructDecl);
2602}
2603
Steve Naroffb29b4272008-04-14 22:03:09 +00002604QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002605 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002606 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002607 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002608 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002609 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002610
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002611 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002612 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002613 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002614 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002615 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002616 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002617 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002618 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002619
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002620 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002621 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002622 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2623 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002624 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002625 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002626 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002627 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002628 /*Mutable=*/true,
2629 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002630 }
2631
Douglas Gregor838db382010-02-11 01:19:42 +00002632 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002633 }
2634 return Context->getTagDeclType(ConstantStringDecl);
2635}
2636
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002637Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2638 SourceLocation StartLoc,
2639 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002640 if (!SelGetUidFunctionDecl)
2641 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002642 if (!MsgSendFunctionDecl)
2643 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002644 if (!MsgSendSuperFunctionDecl)
2645 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002646 if (!MsgSendStretFunctionDecl)
2647 SynthMsgSendStretFunctionDecl();
2648 if (!MsgSendSuperStretFunctionDecl)
2649 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002650 if (!MsgSendFpretFunctionDecl)
2651 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002652 if (!GetClassFunctionDecl)
2653 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002654 if (!GetSuperClassFunctionDecl)
2655 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002656 if (!GetMetaClassFunctionDecl)
2657 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Steve Naroff874e2322007-11-15 10:28:18 +00002659 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002660 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2661 // May need to use objc_msgSend_stret() as well.
2662 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002663 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2664 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002665 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002666 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002667 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002668 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002669 }
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Steve Naroff934f2762007-10-24 22:48:43 +00002671 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002672 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002673 switch (Exp->getReceiverKind()) {
2674 case ObjCMessageExpr::SuperClass: {
2675 MsgSendFlavor = MsgSendSuperFunctionDecl;
2676 if (MsgSendStretFlavor)
2677 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2678 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Douglas Gregor04badcf2010-04-21 00:45:42 +00002680 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002681
Chris Lattner5f9e2722011-07-23 10:55:15 +00002682 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002683
Douglas Gregor04badcf2010-04-21 00:45:42 +00002684 // set the receiver to self, the first argument to all methods.
2685 InitExprs.push_back(
2686 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002687 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002688 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002689 Context->getObjCIdType(),
2690 VK_RValue,
2691 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002692 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregor04badcf2010-04-21 00:45:42 +00002694 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002695 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002696 QualType argType = Context->getPointerType(Context->CharTy);
2697 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002698 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002699 StringLiteral::Ascii, false,
2700 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002701 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2702 &ClsExprs[0],
2703 ClsExprs.size(),
2704 StartLoc,
2705 EndLoc);
2706 // (Class)objc_getClass("CurrentClass")
2707 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2708 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002709 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002710 ClsExprs.clear();
2711 ClsExprs.push_back(ArgExpr);
2712 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2713 &ClsExprs[0], ClsExprs.size(),
2714 StartLoc, EndLoc);
2715
2716 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2717 // To turn off a warning, type-cast to 'id'
2718 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2719 NoTypeInfoCStyleCastExpr(Context,
2720 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002721 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002722 // struct objc_super
2723 QualType superType = getSuperStructType();
2724 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002725
Francois Pichet62ec1f22011-09-17 17:15:52 +00002726 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002727 SynthSuperContructorFunctionDecl();
2728 // Simulate a contructor call...
2729 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002730 superType, VK_LValue,
2731 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2733 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002734 superType, VK_LValue,
2735 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736 // The code for super is a little tricky to prevent collision with
2737 // the structure definition in the header. The rewriter has it's own
2738 // internal definition (__rw_objc_super) that is uses. This is why
2739 // we need the cast below. For example:
2740 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2741 //
John McCall2de56d12010-08-25 11:45:40 +00002742 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002743 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002744 VK_RValue, OK_Ordinary,
2745 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002746 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2747 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002748 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002749 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002750 // (struct objc_super) { <exprs from above> }
2751 InitListExpr *ILE =
2752 new (Context) InitListExpr(*Context, SourceLocation(),
2753 &InitExprs[0], InitExprs.size(),
2754 SourceLocation());
2755 TypeSourceInfo *superTInfo
2756 = Context->getTrivialTypeSourceInfo(superType);
2757 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002758 superType, VK_LValue,
2759 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002760 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002761 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002763 VK_RValue, OK_Ordinary,
2764 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002765 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 MsgExprs.push_back(SuperRep);
2767 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002768 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769
2770 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002771 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002772 QualType argType = Context->getPointerType(Context->CharTy);
2773 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002774 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 IdentifierInfo *clsName = Class->getIdentifier();
2776 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002777 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002778 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002779 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2781 &ClsExprs[0],
2782 ClsExprs.size(),
2783 StartLoc, EndLoc);
2784 MsgExprs.push_back(Cls);
2785 break;
2786 }
2787
2788 case ObjCMessageExpr::SuperInstance:{
2789 MsgSendFlavor = MsgSendSuperFunctionDecl;
2790 if (MsgSendStretFlavor)
2791 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2792 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2793 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002794 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795
2796 InitExprs.push_back(
2797 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002798 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002799 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002800 Context->getObjCIdType(),
2801 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002802 ); // set the 'receiver'.
2803
2804 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002805 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002806 QualType argType = Context->getPointerType(Context->CharTy);
2807 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002808 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002809 StringLiteral::Ascii, false, argType,
2810 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002811 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2812 &ClsExprs[0],
2813 ClsExprs.size(),
2814 StartLoc, EndLoc);
2815 // (Class)objc_getClass("CurrentClass")
2816 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2817 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002818 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002819 ClsExprs.clear();
2820 ClsExprs.push_back(ArgExpr);
2821 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2822 &ClsExprs[0], ClsExprs.size(),
2823 StartLoc, EndLoc);
2824
2825 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2826 // To turn off a warning, type-cast to 'id'
2827 InitExprs.push_back(
2828 // set 'super class', using class_getSuperclass().
2829 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002830 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 // struct objc_super
2832 QualType superType = getSuperStructType();
2833 Expr *SuperRep;
2834
Francois Pichet62ec1f22011-09-17 17:15:52 +00002835 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 SynthSuperContructorFunctionDecl();
2837 // Simulate a contructor call...
2838 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002839 superType, VK_LValue,
2840 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002841 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2842 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002843 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 // The code for super is a little tricky to prevent collision with
2845 // the structure definition in the header. The rewriter has it's own
2846 // internal definition (__rw_objc_super) that is uses. This is why
2847 // we need the cast below. For example:
2848 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2849 //
John McCall2de56d12010-08-25 11:45:40 +00002850 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002852 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002853 SourceLocation());
2854 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2855 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002856 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 } else {
2858 // (struct objc_super) { <exprs from above> }
2859 InitListExpr *ILE =
2860 new (Context) InitListExpr(*Context, SourceLocation(),
2861 &InitExprs[0], InitExprs.size(),
2862 SourceLocation());
2863 TypeSourceInfo *superTInfo
2864 = Context->getTrivialTypeSourceInfo(superType);
2865 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002866 superType, VK_RValue, ILE,
2867 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002868 }
2869 MsgExprs.push_back(SuperRep);
2870 break;
2871 }
2872
2873 case ObjCMessageExpr::Instance: {
2874 // Remove all type-casts because it may contain objc-style types; e.g.
2875 // Foo<Proto> *.
2876 Expr *recExpr = Exp->getInstanceReceiver();
2877 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2878 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002879 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2880 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2881 ? CK_BlockPointerToObjCPointerCast
2882 : CK_CPointerToObjCPointerCast;
2883
Douglas Gregor04badcf2010-04-21 00:45:42 +00002884 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002885 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 MsgExprs.push_back(recExpr);
2887 break;
2888 }
2889 }
2890
Steve Naroffbeaf2992007-11-03 11:27:19 +00002891 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002892 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002893 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002894 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002895 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002896 StringLiteral::Ascii, false,
2897 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002898 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002899 &SelExprs[0], SelExprs.size(),
2900 StartLoc,
2901 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002902 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002903
Steve Naroff934f2762007-10-24 22:48:43 +00002904 // Now push any user supplied arguments.
2905 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002906 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002907 // Make all implicit casts explicit...ICE comes in handy:-)
2908 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2909 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002910 QualType type = ICE->getType();
2911 if (needToScanForQualifiers(type))
2912 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002913 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002914 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002915 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002916 CastKind CK;
2917 if (SubExpr->getType()->isIntegralType(*Context) &&
2918 type->isBooleanType()) {
2919 CK = CK_IntegralToBoolean;
2920 } else if (type->isObjCObjectPointerType()) {
2921 if (SubExpr->getType()->isBlockPointerType()) {
2922 CK = CK_BlockPointerToObjCPointerCast;
2923 } else if (SubExpr->getType()->isPointerType()) {
2924 CK = CK_CPointerToObjCPointerCast;
2925 } else {
2926 CK = CK_BitCast;
2927 }
2928 } else {
2929 CK = CK_BitCast;
2930 }
2931
2932 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002933 }
2934 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002935 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002936 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002937 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002938 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002939 CastKind CK;
2940 if (userExpr->getType()->isIntegralType(*Context)) {
2941 CK = CK_IntegralToPointer;
2942 } else if (userExpr->getType()->isBlockPointerType()) {
2943 CK = CK_BlockPointerToObjCPointerCast;
2944 } else if (userExpr->getType()->isPointerType()) {
2945 CK = CK_CPointerToObjCPointerCast;
2946 } else {
2947 CK = CK_BitCast;
2948 }
John McCall9d125032010-01-15 18:39:57 +00002949 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002950 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002951 }
Mike Stump1eb44332009-09-09 15:08:12 +00002952 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002953 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002954 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2955 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002956 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002957 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002958 }
Steve Naroffab972d32007-11-04 22:37:50 +00002959 // Generate the funky cast.
2960 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002961 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002962 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002963
Steve Naroffab972d32007-11-04 22:37:50 +00002964 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002965 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2966 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2967 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002968 ArgTypes.push_back(Context->getObjCIdType());
2969 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002970 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002971 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002972 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2973 E = OMD->param_end(); PI != E; ++PI) {
2974 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002975 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002976 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002977 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002978 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002979 ArgTypes.push_back(t);
2980 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002981 returnType = Exp->getType();
2982 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002983 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002984 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002985 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002986 }
2987 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002988 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Steve Naroffab972d32007-11-04 22:37:50 +00002990 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002991 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002992 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002993
Mike Stump1eb44332009-09-09 15:08:12 +00002994 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002995 // If we don't do this cast, we get the following bizarre warning/note:
2996 // xx.m:13: warning: function called through a non-compatible type
2997 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002998 cast = NoTypeInfoCStyleCastExpr(Context,
2999 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003000 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003001
Steve Naroffab972d32007-11-04 22:37:50 +00003002 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003003 QualType castType =
3004 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3005 // If we don't have a method decl, force a variadic cast.
3006 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003007 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003008 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003009 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003010
3011 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003012 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003013
John McCall183700f2009-09-21 23:43:11 +00003014 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003015 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003016 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003017 FT->getResultType(), VK_RValue,
3018 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003019 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003020 if (MsgSendStretFlavor) {
3021 // We have the method which returns a struct/union. Must also generate
3022 // call to objc_msgSend_stret and hang both varieties on a conditional
3023 // expression which dictate which one to envoke depending on size of
3024 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003025
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003026 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003027 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003028 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003029 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003030 cast = NoTypeInfoCStyleCastExpr(Context,
3031 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003032 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003033 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003034 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3035 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003036 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003037 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003038 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003041 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003042
John McCall183700f2009-09-21 23:43:11 +00003043 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003044 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003045 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003046 FT->getResultType(), VK_RValue,
3047 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003049 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003050 UnaryExprOrTypeTraitExpr *sizeofExpr =
3051 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3052 Context->getTrivialTypeSourceInfo(returnType),
3053 Context->getSizeType(), SourceLocation(),
3054 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003055 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3056 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3057 // For X86 it is more complicated and some kind of target specific routine
3058 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003059 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003060 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003061 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3062 llvm::APInt(IntSize, 8),
3063 Context->IntTy,
3064 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003065 BinaryOperator *lessThanExpr =
3066 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3067 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003068 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003069 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003070 new (Context) ConditionalOperator(lessThanExpr,
3071 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003072 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003073 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003074 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3075 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003076 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003077 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003078 return ReplacingStmt;
3079}
3080
Steve Naroffb29b4272008-04-14 22:03:09 +00003081Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003082 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3083 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Steve Naroff934f2762007-10-24 22:48:43 +00003085 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003086 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003088 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003089 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003090}
3091
Steve Naroff621edce2009-04-29 16:37:50 +00003092// typedef struct objc_object Protocol;
3093QualType RewriteObjC::getProtocolType() {
3094 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003095 TypeSourceInfo *TInfo
3096 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003097 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003098 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003099 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003100 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003101 }
3102 return Context->getTypeDeclType(ProtocolTypeDecl);
3103}
3104
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003105/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003106/// a synthesized/forward data reference (to the protocol's metadata).
3107/// The forward references (and metadata) are generated in
3108/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003109Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003110 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3111 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003112 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003113 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003114 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003115 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3116 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003117 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003118 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003119 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003120 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003121 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003122 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003123 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003124 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003125 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003126 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003128}
3129
Mike Stump1eb44332009-09-09 15:08:12 +00003130bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003131 const char *endBuf) {
3132 while (startBuf < endBuf) {
3133 if (*startBuf == '#') {
3134 // Skip whitespace.
3135 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3136 ;
3137 if (!strncmp(startBuf, "if", strlen("if")) ||
3138 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3139 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3140 !strncmp(startBuf, "define", strlen("define")) ||
3141 !strncmp(startBuf, "undef", strlen("undef")) ||
3142 !strncmp(startBuf, "else", strlen("else")) ||
3143 !strncmp(startBuf, "elif", strlen("elif")) ||
3144 !strncmp(startBuf, "endif", strlen("endif")) ||
3145 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3146 !strncmp(startBuf, "include", strlen("include")) ||
3147 !strncmp(startBuf, "import", strlen("import")) ||
3148 !strncmp(startBuf, "include_next", strlen("include_next")))
3149 return true;
3150 }
3151 startBuf++;
3152 }
3153 return false;
3154}
3155
Fariborz Jahanian58457172011-12-05 18:43:13 +00003156/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003157/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003158void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003159 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003160 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003161 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003162 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003163 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003164 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003165 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003167 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003168 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003169 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Steve Narofffea763e82007-11-14 19:25:57 +00003171 const char *startBuf = SM->getCharacterData(LocStart);
3172 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003174 // If no ivars and no root or if its root, directly or indirectly,
3175 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003176 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003177 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003178 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003179 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003180 return;
3181 }
Mike Stump1eb44332009-09-09 15:08:12 +00003182
3183 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003184 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003185 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003186 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003187 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003188 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003189
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003190 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003191 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003192 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003193 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003194 // If the buffer contains preprocessor directives, we do more fine-grained
3195 // rewrites. This is intended to fix code that looks like (which occurs in
3196 // NSURL.h, for example):
3197 //
3198 // #ifdef XYZ
3199 // @interface Foo : NSObject
3200 // #else
3201 // @interface FooBar : NSObject
3202 // #endif
3203 // {
3204 // int i;
3205 // }
3206 // @end
3207 //
3208 // This clause is segregated to avoid breaking the common case.
3209 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003210 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003211 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003212 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003213 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003214
Chris Lattnercafeb352009-02-20 18:18:36 +00003215 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003216 // advance to the end of the referenced protocols.
3217 while (endHeader < cursor && *endHeader != '>') endHeader++;
3218 endHeader++;
3219 }
3220 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003221 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003222 } else {
3223 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003224 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003225 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003226 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003227 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003228 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003229 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003230 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003231 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Steve Narofffea763e82007-11-14 19:25:57 +00003233 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003234 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003235 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003236 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003237 }
3238 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003239
Steve Narofffea763e82007-11-14 19:25:57 +00003240 // Now comment out any visibility specifiers.
3241 while (cursor < endBuf) {
3242 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003243 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003244 // Skip whitespace.
3245 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3246 /*scan*/;
3247
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003248 // FIXME: presence of @public, etc. inside comment results in
3249 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003250 if (!strncmp(cursor, "public", strlen("public")) ||
3251 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003252 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003253 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003254 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003255 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003256 // FIXME: If there are cases where '<' is used in ivar declaration part
3257 // of user code, then scan the ivar list and use needToScanForQualifiers
3258 // for type checking.
3259 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003260 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003261 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003262 cursor = strchr(cursor, '>');
3263 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003264 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003265 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003266 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003267 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003268 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003269 }
Steve Narofffea763e82007-11-14 19:25:57 +00003270 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003271 }
Steve Narofffea763e82007-11-14 19:25:57 +00003272 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003273 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003274 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003275 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003276 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003277 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003278 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003280 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003281 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003282 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003283 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003284 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003285 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003286}
3287
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003288//===----------------------------------------------------------------------===//
3289// Meta Data Emission
3290//===----------------------------------------------------------------------===//
3291
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003292
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003293/// RewriteImplementations - This routine rewrites all method implementations
3294/// and emits meta-data.
3295
Steve Narofface66252008-11-13 20:07:04 +00003296void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003297 int ClsDefCount = ClassImplementation.size();
3298 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003300 // Rewrite implemented methods
3301 for (int i = 0; i < ClsDefCount; i++)
3302 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003304 for (int i = 0; i < CatDefCount; i++)
3305 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003306}
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003308void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3309 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003310 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003311 assert(BlockByRefDeclNo.count(VD) &&
3312 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003313 if (def)
3314 ResultStr += "struct ";
3315 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003316 "_" + utostr(BlockByRefDeclNo[VD]) ;
3317}
3318
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003319static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3320 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3321 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3322 return false;
3323}
3324
Steve Naroff54055232008-10-27 17:20:55 +00003325std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003326 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003327 std::string Tag) {
3328 const FunctionType *AFT = CE->getFunctionType();
3329 QualType RT = AFT->getResultType();
3330 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003331 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003332 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003333
Steve Naroff54055232008-10-27 17:20:55 +00003334 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003335
Douglas Gregor72564e72009-02-26 23:50:07 +00003336 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003337 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003338 // block (to reference imported block decl refs).
3339 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003340 } else if (BD->param_empty()) {
3341 S += "(" + StructRef + " *__cself)";
3342 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003343 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003344 assert(FT && "SynthesizeBlockFunc: No function proto");
3345 S += '(';
3346 // first add the implicit argument.
3347 S += StructRef + " *__cself, ";
3348 std::string ParamStr;
3349 for (BlockDecl::param_iterator AI = BD->param_begin(),
3350 E = BD->param_end(); AI != E; ++AI) {
3351 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003352 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003353 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003354 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003355 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003356 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003357 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003358 S += ParamStr;
3359 }
3360 if (FT->isVariadic()) {
3361 if (!BD->param_empty()) S += ", ";
3362 S += "...";
3363 }
3364 S += ')';
3365 }
3366 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Steve Naroff54055232008-10-27 17:20:55 +00003368 // Create local declarations to avoid rewriting all closure decl ref exprs.
3369 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003370 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003371 E = BlockByRefDecls.end(); I != E; ++I) {
3372 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003373 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003374 std::string TypeString;
3375 RewriteByRefString(TypeString, Name, (*I));
3376 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003377 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003378 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003379 }
Steve Naroff54055232008-10-27 17:20:55 +00003380 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003381 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003382 E = BlockByCopyDecls.end(); I != E; ++I) {
3383 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003384 // Handle nested closure invocation. For example:
3385 //
3386 // void (^myImportedClosure)(void);
3387 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003388 //
Steve Naroff54055232008-10-27 17:20:55 +00003389 // void (^anotherClosure)(void);
3390 // anotherClosure = ^(void) {
3391 // myImportedClosure(); // import and invoke the closure
3392 // };
3393 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003394 if (isTopLevelBlockPointerType((*I)->getType())) {
3395 RewriteBlockPointerTypeVariable(S, (*I));
3396 S += " = (";
3397 RewriteBlockPointerType(S, (*I)->getType());
3398 S += ")";
3399 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3400 }
3401 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003402 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003403 QualType QT = (*I)->getType();
3404 if (HasLocalVariableExternalStorage(*I))
3405 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003406 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003407 S += Name + " = __cself->" +
3408 (*I)->getNameAsString() + "; // bound by copy\n";
3409 }
Steve Naroff54055232008-10-27 17:20:55 +00003410 }
3411 std::string RewrittenStr = RewrittenBlockExprs[CE];
3412 const char *cstr = RewrittenStr.c_str();
3413 while (*cstr++ != '{') ;
3414 S += cstr;
3415 S += "\n";
3416 return S;
3417}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003418
Steve Naroff54055232008-10-27 17:20:55 +00003419std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003420 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003421 std::string Tag) {
3422 std::string StructRef = "struct " + Tag;
3423 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Steve Naroff54055232008-10-27 17:20:55 +00003425 S += funcName;
3426 S += "_block_copy_" + utostr(i);
3427 S += "(" + StructRef;
3428 S += "*dst, " + StructRef;
3429 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003430 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003431 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003432 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003433 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003435 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003436 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003437 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003438 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003439 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003440 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003441 else
3442 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003443 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003444 S += "}\n";
3445
Steve Naroff54055232008-10-27 17:20:55 +00003446 S += "\nstatic void __";
3447 S += funcName;
3448 S += "_block_dispose_" + utostr(i);
3449 S += "(" + StructRef;
3450 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003451 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003452 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003453 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003454 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003456 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003457 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003458 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003459 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003460 else
3461 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003462 }
Mike Stump1eb44332009-09-09 15:08:12 +00003463 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003464 return S;
3465}
3466
Steve Naroff01aec112009-12-06 21:14:13 +00003467std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3468 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003469 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003470 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Steve Naroff54055232008-10-27 17:20:55 +00003472 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003473 S += " struct " + Desc;
3474 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Steve Naroff01aec112009-12-06 21:14:13 +00003476 Constructor += "(void *fp, "; // Invoke function pointer.
3477 Constructor += "struct " + Desc; // Descriptor pointer.
3478 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Steve Naroff54055232008-10-27 17:20:55 +00003480 if (BlockDeclRefs.size()) {
3481 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003482 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003483 E = BlockByCopyDecls.end(); I != E; ++I) {
3484 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003485 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003486 std::string ArgName = "_" + FieldName;
3487 // Handle nested closure invocation. For example:
3488 //
3489 // void (^myImportedBlock)(void);
3490 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003491 //
Steve Naroff54055232008-10-27 17:20:55 +00003492 // void (^anotherBlock)(void);
3493 // anotherBlock = ^(void) {
3494 // myImportedBlock(); // import and invoke the closure
3495 // };
3496 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003497 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003498 S += "struct __block_impl *";
3499 Constructor += ", void *" + ArgName;
3500 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003501 QualType QT = (*I)->getType();
3502 if (HasLocalVariableExternalStorage(*I))
3503 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003504 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3505 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003506 Constructor += ", " + ArgName;
3507 }
3508 S += FieldName + ";\n";
3509 }
3510 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003511 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003512 E = BlockByRefDecls.end(); I != E; ++I) {
3513 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003514 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003515 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003516 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003517 std::string TypeString;
3518 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003519 TypeString += " *";
3520 FieldName = TypeString + FieldName;
3521 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003522 Constructor += ", " + ArgName;
3523 }
3524 S += FieldName + "; // by ref\n";
3525 }
3526 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003527 Constructor += ", int flags=0)";
3528 // Initialize all "by copy" arguments.
3529 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003530 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003531 E = BlockByCopyDecls.end(); I != E; ++I) {
3532 std::string Name = (*I)->getNameAsString();
3533 if (firsTime) {
3534 Constructor += " : ";
3535 firsTime = false;
3536 }
3537 else
3538 Constructor += ", ";
3539 if (isTopLevelBlockPointerType((*I)->getType()))
3540 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3541 else
3542 Constructor += Name + "(_" + Name + ")";
3543 }
3544 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003545 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003546 E = BlockByRefDecls.end(); I != E; ++I) {
3547 std::string Name = (*I)->getNameAsString();
3548 if (firsTime) {
3549 Constructor += " : ";
3550 firsTime = false;
3551 }
3552 else
3553 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003554 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003555 }
3556
3557 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003558 if (GlobalVarDecl)
3559 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3560 else
3561 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003562 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Steve Naroff01aec112009-12-06 21:14:13 +00003564 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003565 } else {
3566 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003567 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003568 if (GlobalVarDecl)
3569 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3570 else
3571 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003572 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3573 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003574 }
3575 Constructor += " ";
3576 Constructor += "}\n";
3577 S += Constructor;
3578 S += "};\n";
3579 return S;
3580}
3581
Steve Naroff01aec112009-12-06 21:14:13 +00003582std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3583 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003584 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003585 unsigned hasCopy) {
3586 std::string S = "\nstatic struct " + DescTag;
3587
3588 S += " {\n unsigned long reserved;\n";
3589 S += " unsigned long Block_size;\n";
3590 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003591 S += " void (*copy)(struct ";
3592 S += ImplTag; S += "*, struct ";
3593 S += ImplTag; S += "*);\n";
3594
3595 S += " void (*dispose)(struct ";
3596 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003597 }
3598 S += "} ";
3599
3600 S += DescTag + "_DATA = { 0, sizeof(struct ";
3601 S += ImplTag + ")";
3602 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003603 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3604 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003605 }
3606 S += "};\n";
3607 return S;
3608}
3609
Steve Naroff54055232008-10-27 17:20:55 +00003610void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003611 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003612 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003613 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003614 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003615 bool RewriteSC = (GlobalVarDecl &&
3616 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003617 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003618 GlobalVarDecl->getType().getCVRQualifiers());
3619 if (RewriteSC) {
3620 std::string SC(" void __");
3621 SC += GlobalVarDecl->getNameAsString();
3622 SC += "() {}";
3623 InsertText(FunLocStart, SC);
3624 }
3625
Steve Naroff54055232008-10-27 17:20:55 +00003626 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003627 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3628 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003629 // Need to copy-in the inner copied-in variables not actually used in this
3630 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003631 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3632 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3633 ValueDecl *VD = Exp->getDecl();
3634 BlockDeclRefs.push_back(Exp);
3635 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3636 BlockByCopyDeclsPtrSet.insert(VD);
3637 BlockByCopyDecls.push_back(VD);
3638 }
3639 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3640 BlockByRefDeclsPtrSet.insert(VD);
3641 BlockByRefDecls.push_back(VD);
3642 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003643 // imported objects in the inner blocks not used in the outer
3644 // blocks must be copied/disposed in the outer block as well.
3645 if (Exp->isByRef() ||
3646 VD->getType()->isObjCObjectPointerType() ||
3647 VD->getType()->isBlockPointerType())
3648 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003649 }
Steve Naroff54055232008-10-27 17:20:55 +00003650
Daniel Dunbar4087f272010-08-17 22:39:59 +00003651 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3652 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Steve Naroff01aec112009-12-06 21:14:13 +00003654 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003655
Benjamin Kramerd999b372010-02-14 14:14:16 +00003656 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003657
Steve Naroff01aec112009-12-06 21:14:13 +00003658 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Benjamin Kramerd999b372010-02-14 14:14:16 +00003660 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003661
3662 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003663 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003664 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003665 }
Steve Naroff01aec112009-12-06 21:14:13 +00003666 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3667 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003668 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Steve Naroff54055232008-10-27 17:20:55 +00003670 BlockDeclRefs.clear();
3671 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003672 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003673 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003674 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003675 ImportedBlockDecls.clear();
3676 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003677 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003678 // Must insert any 'const/volatile/static here. Since it has been
3679 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003680 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003681 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003682 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003683 if (GlobalVarDecl->getType().isConstQualified())
3684 SC += "const ";
3685 if (GlobalVarDecl->getType().isVolatileQualified())
3686 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003687 if (GlobalVarDecl->getType().isRestrictQualified())
3688 SC += "restrict ";
3689 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003690 }
3691
Steve Naroff54055232008-10-27 17:20:55 +00003692 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003693 InnerDeclRefsCount.clear();
3694 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003695 RewrittenBlockExprs.clear();
3696}
3697
3698void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3699 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003700 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Steve Naroff54055232008-10-27 17:20:55 +00003702 SynthesizeBlockLiterals(FunLocStart, FuncName);
3703}
3704
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003705static void BuildUniqueMethodName(std::string &Name,
3706 ObjCMethodDecl *MD) {
3707 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003708 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003709 Name += "__" + MD->getSelector().getAsString();
3710 // Convert colons to underscores.
3711 std::string::size_type loc = 0;
3712 while ((loc = Name.find(":", loc)) != std::string::npos)
3713 Name.replace(loc, 1, "_");
3714}
3715
Steve Naroff54055232008-10-27 17:20:55 +00003716void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003717 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3718 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003719 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003720 std::string FuncName;
3721 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003722 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003723}
3724
3725void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003726 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003727 if (*CI) {
3728 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3729 GetBlockDeclRefExprs(CBE->getBody());
3730 else
3731 GetBlockDeclRefExprs(*CI);
3732 }
3733 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003734 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003735 // FIXME: Handle enums.
3736 if (!isa<FunctionDecl>(CDRE->getDecl()))
3737 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003738 }
3739 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3740 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3741 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003742 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3743 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003744 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003745 BlockDeclRefs.push_back(BDRE);
3746 }
3747
Steve Naroff54055232008-10-27 17:20:55 +00003748 return;
3749}
3750
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003751void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003752 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003753 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003754 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003755 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003756 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3757 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003758 GetInnerBlockDeclRefExprs(CBE->getBody(),
3759 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003760 InnerContexts);
3761 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003762 else
3763 GetInnerBlockDeclRefExprs(*CI,
3764 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003765 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003766
3767 }
3768 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003769 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003770 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003771 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003772 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003773 }
3774 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3775 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3776 if (Var->isFunctionOrMethodVarDecl())
3777 ImportedLocalExternalDecls.insert(Var);
3778 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003779
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003780 return;
3781}
3782
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003783/// convertFunctionTypeOfBlocks - This routine converts a function type
3784/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003785/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003786/// all block pointers to function pointers.
3787QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3788 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3789 // FTP will be null for closures that don't take arguments.
3790 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003791 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003792 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003793 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003794
3795 if (FTP) {
3796 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3797 E = FTP->arg_type_end(); I && (I != E); ++I) {
3798 QualType t = *I;
3799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003800 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003801 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003802 ArgTypes.push_back(t);
3803 }
3804 }
3805 QualType FuncType;
3806 // FIXME. Does this work if block takes no argument but has a return type
3807 // which is of block type?
3808 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003809 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003810 else FuncType = QualType(FT, 0);
3811 return FuncType;
3812}
3813
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003814Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003815 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003816 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003818 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003819 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003820 } else if (const BlockDeclRefExpr *CDRE =
3821 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003822 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003823 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003824 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003825 }
3826 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3827 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3828 }
3829 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3830 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3831 else if (const ConditionalOperator *CEXPR =
3832 dyn_cast<ConditionalOperator>(BlockExp)) {
3833 Expr *LHSExp = CEXPR->getLHS();
3834 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3835 Expr *RHSExp = CEXPR->getRHS();
3836 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3837 Expr *CONDExp = CEXPR->getCond();
3838 ConditionalOperator *CondExpr =
3839 new (Context) ConditionalOperator(CONDExp,
3840 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003841 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003842 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003843 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003844 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3845 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003846 } else if (const PseudoObjectExpr *POE
3847 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3848 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003849 } else {
3850 assert(1 && "RewriteBlockClass: Bad type");
3851 }
3852 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003853 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003854 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003855 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003856 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003857
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003858 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003859 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003860 &Context->Idents.get("__block_impl"));
3861 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003862
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003863 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003864 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003866 // Push the block argument type.
3867 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003868 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003869 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003870 E = FTP->arg_type_end(); I && (I != E); ++I) {
3871 QualType t = *I;
3872 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003873 if (!convertBlockPointerToFunctionPointer(t))
3874 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 ArgTypes.push_back(t);
3876 }
Steve Naroff54055232008-10-27 17:20:55 +00003877 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003878 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003879 QualType PtrToFuncCastType
3880 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003881
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003882 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003883
John McCall9d125032010-01-15 18:39:57 +00003884 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003885 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003886 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003887 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003888 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3889 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003890 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003891
Douglas Gregor44b43212008-12-11 16:49:14 +00003892 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003893 SourceLocation(),
3894 &Context->Idents.get("FuncPtr"),
3895 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003896 /*BitWidth=*/0, /*Mutable=*/true,
3897 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003898 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003899 FD->getType(), VK_LValue,
3900 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003902
John McCall9d125032010-01-15 18:39:57 +00003903 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003904 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003905 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Chris Lattner5f9e2722011-07-23 10:55:15 +00003907 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003908 // Add the implicit argument.
3909 BlkExprs.push_back(BlkCast);
3910 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003911 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003912 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003913 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003914 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003915 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3916 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003917 Exp->getType(), VK_RValue,
3918 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003919 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003920}
3921
Steve Naroff621edce2009-04-29 16:37:50 +00003922// We need to return the rewritten expression to handle cases where the
3923// BlockDeclRefExpr is embedded in another expression being rewritten.
3924// For example:
3925//
3926// int main() {
3927// __block Foo *f;
3928// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003929//
Steve Naroff621edce2009-04-29 16:37:50 +00003930// void (^myblock)() = ^() {
3931// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3932// i = 77;
3933// };
3934//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003935Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003936 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003937 // for each DeclRefExp where BYREFVAR is name of the variable.
3938 ValueDecl *VD;
3939 bool isArrow = true;
3940 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3941 VD = BDRE->getDecl();
3942 else {
3943 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3944 isArrow = false;
3945 }
3946
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003947 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003948 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003949 &Context->Idents.get("__forwarding"),
3950 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003951 /*BitWidth=*/0, /*Mutable=*/true,
3952 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003953 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3954 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003955 FD->getType(), VK_LValue,
3956 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003957
Chris Lattner5f9e2722011-07-23 10:55:15 +00003958 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003959 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003960 &Context->Idents.get(Name),
3961 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003962 /*BitWidth=*/0, /*Mutable=*/true,
3963 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003964 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003965 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003966
3967
3968
Steve Naroffdf8570d2009-02-02 17:19:26 +00003969 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003970 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3971 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003972 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003973 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003974 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003975}
3976
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003977// Rewrites the imported local variable V with external storage
3978// (static, extern, etc.) as *V
3979//
3980Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3981 ValueDecl *VD = DRE->getDecl();
3982 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3983 if (!ImportedLocalExternalDecls.count(Var))
3984 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003985 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3986 VK_LValue, OK_Ordinary,
3987 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003988 // Need parens to enforce precedence.
3989 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3990 Exp);
3991 ReplaceStmt(DRE, PE);
3992 return PE;
3993}
3994
Steve Naroffb2f9e512008-11-03 23:29:32 +00003995void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3996 SourceLocation LocStart = CE->getLParenLoc();
3997 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003998
3999 // Need to avoid trying to rewrite synthesized casts.
4000 if (LocStart.isInvalid())
4001 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004002 // Need to avoid trying to rewrite casts contained in macros.
4003 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4004 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Steve Naroff54055232008-10-27 17:20:55 +00004006 const char *startBuf = SM->getCharacterData(LocStart);
4007 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004008 QualType QT = CE->getType();
4009 const Type* TypePtr = QT->getAs<Type>();
4010 if (isa<TypeOfExprType>(TypePtr)) {
4011 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4012 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4013 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004014 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004015 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004016 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004017 return;
4018 }
Steve Naroff54055232008-10-27 17:20:55 +00004019 // advance the location to startArgList.
4020 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004021
Steve Naroff54055232008-10-27 17:20:55 +00004022 while (*argPtr++ && (argPtr < endBuf)) {
4023 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004024 case '^':
4025 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004026 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004027 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004028 break;
Steve Naroff54055232008-10-27 17:20:55 +00004029 }
4030 }
4031 return;
4032}
4033
4034void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4035 SourceLocation DeclLoc = FD->getLocation();
4036 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Steve Naroff54055232008-10-27 17:20:55 +00004038 // We have 1 or more arguments that have closure pointers.
4039 const char *startBuf = SM->getCharacterData(DeclLoc);
4040 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Steve Naroff54055232008-10-27 17:20:55 +00004042 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Steve Naroff54055232008-10-27 17:20:55 +00004044 parenCount++;
4045 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004046 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004047 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Steve Naroff54055232008-10-27 17:20:55 +00004049 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Steve Naroff54055232008-10-27 17:20:55 +00004051 while (*argPtr++ && parenCount) {
4052 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004053 case '^':
4054 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004055 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004056 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004057 break;
4058 case '(':
4059 parenCount++;
4060 break;
4061 case ')':
4062 parenCount--;
4063 break;
Steve Naroff54055232008-10-27 17:20:55 +00004064 }
4065 }
4066 return;
4067}
4068
4069bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004070 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004071 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004072 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004073 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004074 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004075 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004076 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004077 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004078 }
4079 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004080 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004081 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004082 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004083 return true;
4084 }
4085 return false;
4086}
4087
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004088bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4089 const FunctionProtoType *FTP;
4090 const PointerType *PT = QT->getAs<PointerType>();
4091 if (PT) {
4092 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4093 } else {
4094 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4095 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4096 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4097 }
4098 if (FTP) {
4099 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004100 E = FTP->arg_type_end(); I != E; ++I) {
4101 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004102 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004103 if ((*I)->isObjCObjectPointerType() &&
4104 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4105 return true;
4106 }
4107
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004108 }
4109 return false;
4110}
4111
Ted Kremenek8189cde2009-02-07 01:47:29 +00004112void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4113 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004114 const char *argPtr = strchr(Name, '(');
4115 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Steve Naroff54055232008-10-27 17:20:55 +00004117 LParen = argPtr; // output the start.
4118 argPtr++; // skip past the left paren.
4119 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Steve Naroff54055232008-10-27 17:20:55 +00004121 while (*argPtr && parenCount) {
4122 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004123 case '(': parenCount++; break;
4124 case ')': parenCount--; break;
4125 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004126 }
4127 if (parenCount) argPtr++;
4128 }
4129 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4130 RParen = argPtr; // output the end
4131}
4132
4133void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4134 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4135 RewriteBlockPointerFunctionArgs(FD);
4136 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004137 }
Steve Naroff54055232008-10-27 17:20:55 +00004138 // Handle Variables and Typedefs.
4139 SourceLocation DeclLoc = ND->getLocation();
4140 QualType DeclT;
4141 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4142 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004143 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004144 DeclT = TDD->getUnderlyingType();
4145 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4146 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004147 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004148 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004149
Steve Naroff54055232008-10-27 17:20:55 +00004150 const char *startBuf = SM->getCharacterData(DeclLoc);
4151 const char *endBuf = startBuf;
4152 // scan backward (from the decl location) for the end of the previous decl.
4153 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4154 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004155 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004156 std::string buf;
4157 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004158 // *startBuf != '^' if we are dealing with a pointer to function that
4159 // may take block argument types (which will be handled below).
4160 if (*startBuf == '^') {
4161 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004162 buf = '*';
4163 startBuf++;
4164 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004165 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004166 while (*startBuf != ')') {
4167 buf += *startBuf;
4168 startBuf++;
4169 OrigLength++;
4170 }
4171 buf += ')';
4172 OrigLength++;
4173
4174 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4175 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004176 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004177 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004178 DeclLoc = ND->getLocation();
4179 startBuf = SM->getCharacterData(DeclLoc);
4180 const char *argListBegin, *argListEnd;
4181 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4182 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004183 if (*argListBegin == '^')
4184 buf += '*';
4185 else if (*argListBegin == '<') {
4186 buf += "/*";
4187 buf += *argListBegin++;
4188 OrigLength++;;
4189 while (*argListBegin != '>') {
4190 buf += *argListBegin++;
4191 OrigLength++;
4192 }
4193 buf += *argListBegin;
4194 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004195 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004196 else
4197 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004198 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004199 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004200 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004201 buf += ')';
4202 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004203 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004204 ReplaceText(Start, OrigLength, buf);
4205
Steve Naroff54055232008-10-27 17:20:55 +00004206 return;
4207}
4208
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004209
4210/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4211/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4212/// struct Block_byref_id_object *src) {
4213/// _Block_object_assign (&_dest->object, _src->object,
4214/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4215/// [|BLOCK_FIELD_IS_WEAK]) // object
4216/// _Block_object_assign(&_dest->object, _src->object,
4217/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4218/// [|BLOCK_FIELD_IS_WEAK]) // block
4219/// }
4220/// And:
4221/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4222/// _Block_object_dispose(_src->object,
4223/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4224/// [|BLOCK_FIELD_IS_WEAK]) // object
4225/// _Block_object_dispose(_src->object,
4226/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4227/// [|BLOCK_FIELD_IS_WEAK]) // block
4228/// }
4229
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004230std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4231 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004232 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004233 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004234 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004235 CopyDestroyCache.insert(flag);
4236 S = "static void __Block_byref_id_object_copy_";
4237 S += utostr(flag);
4238 S += "(void *dst, void *src) {\n";
4239
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004240 // offset into the object pointer is computed as:
4241 // void * + void* + int + int + void* + void *
4242 unsigned IntSize =
4243 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4244 unsigned VoidPtrSize =
4245 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4246
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004247 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004248 S += " _Block_object_assign((char*)dst + ";
4249 S += utostr(offset);
4250 S += ", *(void * *) ((char*)src + ";
4251 S += utostr(offset);
4252 S += "), ";
4253 S += utostr(flag);
4254 S += ");\n}\n";
4255
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004256 S += "static void __Block_byref_id_object_dispose_";
4257 S += utostr(flag);
4258 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004259 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4260 S += utostr(offset);
4261 S += "), ";
4262 S += utostr(flag);
4263 S += ");\n}\n";
4264 return S;
4265}
4266
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004267/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4268/// the declaration into:
4269/// struct __Block_byref_ND {
4270/// void *__isa; // NULL for everything except __weak pointers
4271/// struct __Block_byref_ND *__forwarding;
4272/// int32_t __flags;
4273/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004274/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4275/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004276/// typex ND;
4277/// };
4278///
4279/// It then replaces declaration of ND variable with:
4280/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4281/// __size=sizeof(struct __Block_byref_ND),
4282/// ND=initializer-if-any};
4283///
4284///
4285void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004286 // Insert declaration for the function in which block literal is
4287 // used.
4288 if (CurFunctionDeclToDeclareForBlock)
4289 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004290 int flag = 0;
4291 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004292 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004293 if (DeclLoc.isInvalid())
4294 // If type location is missing, it is because of missing type (a warning).
4295 // Use variable's location which is good for this case.
4296 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004297 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004298 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004299 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004300 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004301 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004302 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004303 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004304 ByrefType += " {\n";
4305 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004306 RewriteByRefString(ByrefType, Name, ND);
4307 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004308 ByrefType += " int __flags;\n";
4309 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004310 // Add void *__Block_byref_id_object_copy;
4311 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004312 QualType Ty = ND->getType();
4313 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4314 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004315 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4316 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004317 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004318
4319 QualType T = Ty;
4320 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004321 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004322
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004323 ByrefType += " " + Name + ";\n";
4324 ByrefType += "};\n";
4325 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004326 SourceLocation FunLocStart;
4327 if (CurFunctionDef)
4328 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4329 else {
4330 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4331 FunLocStart = CurMethodDef->getLocStart();
4332 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004333 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004334 if (Ty.isObjCGCWeak()) {
4335 flag |= BLOCK_FIELD_IS_WEAK;
4336 isa = 1;
4337 }
4338
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004339 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004340 flag = BLOCK_BYREF_CALLER;
4341 QualType Ty = ND->getType();
4342 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4343 if (Ty->isBlockPointerType())
4344 flag |= BLOCK_FIELD_IS_BLOCK;
4345 else
4346 flag |= BLOCK_FIELD_IS_OBJECT;
4347 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004348 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004349 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004350 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004351
4352 // struct __Block_byref_ND ND =
4353 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4354 // initializer-if-any};
4355 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004356 unsigned flags = 0;
4357 if (HasCopyAndDispose)
4358 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004359 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004360 ByrefType.clear();
4361 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004362 std::string ForwardingCastType("(");
4363 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004364 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004365 ByrefType += " " + Name + " = {(void*)";
4366 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004367 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004368 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004369 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004370 ByrefType += "sizeof(";
4371 RewriteByRefString(ByrefType, Name, ND);
4372 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004373 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004374 ByrefType += ", __Block_byref_id_object_copy_";
4375 ByrefType += utostr(flag);
4376 ByrefType += ", __Block_byref_id_object_dispose_";
4377 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004378 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004379 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004380 unsigned nameSize = Name.size();
4381 // for block or function pointer declaration. Name is aleady
4382 // part of the declaration.
4383 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4384 nameSize = 1;
4385 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004386 }
4387 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004388 SourceLocation startLoc;
4389 Expr *E = ND->getInit();
4390 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4391 startLoc = ECE->getLParenLoc();
4392 else
4393 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004394 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004395 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004396 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004397 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004398 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004399 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004400 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004401 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004402 ByrefType += "sizeof(";
4403 RewriteByRefString(ByrefType, Name, ND);
4404 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004405 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004406 ByrefType += "__Block_byref_id_object_copy_";
4407 ByrefType += utostr(flag);
4408 ByrefType += ", __Block_byref_id_object_dispose_";
4409 ByrefType += utostr(flag);
4410 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004411 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004412 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004413
4414 // Complete the newly synthesized compound expression by inserting a right
4415 // curly brace before the end of the declaration.
4416 // FIXME: This approach avoids rewriting the initializer expression. It
4417 // also assumes there is only one declarator. For example, the following
4418 // isn't currently supported by this routine (in general):
4419 //
4420 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4421 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004422 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4423 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004424 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4425 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004426 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004427
Benjamin Kramerd999b372010-02-14 14:14:16 +00004428 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004429 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004430 return;
4431}
4432
Mike Stump1eb44332009-09-09 15:08:12 +00004433void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004434 // Add initializers for any closure decl refs.
4435 GetBlockDeclRefExprs(Exp->getBody());
4436 if (BlockDeclRefs.size()) {
4437 // Unique all "by copy" declarations.
4438 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004439 if (!BlockDeclRefs[i]->isByRef()) {
4440 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4441 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4442 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4443 }
4444 }
Steve Naroff54055232008-10-27 17:20:55 +00004445 // Unique all "by ref" declarations.
4446 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4447 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004448 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4449 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4450 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4451 }
Steve Naroff54055232008-10-27 17:20:55 +00004452 }
4453 // Find any imported blocks...they will need special attention.
4454 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004455 if (BlockDeclRefs[i]->isByRef() ||
4456 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004457 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004458 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004459 }
4460}
4461
Chris Lattner5f9e2722011-07-23 10:55:15 +00004462FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004463 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004464 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004465 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4466 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004467 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004468}
4469
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004470Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004471 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004472 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004473 Blocks.push_back(Exp);
4474
4475 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004476
4477 // Add inner imported variables now used in current block.
4478 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004479 if (!InnerBlockDeclRefs.empty()) {
4480 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4481 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4482 ValueDecl *VD = Exp->getDecl();
4483 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004484 // We need to save the copied-in variables in nested
4485 // blocks because it is needed at the end for some of the API generations.
4486 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004487 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4488 BlockDeclRefs.push_back(Exp);
4489 BlockByCopyDeclsPtrSet.insert(VD);
4490 BlockByCopyDecls.push_back(VD);
4491 }
4492 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4493 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4494 BlockDeclRefs.push_back(Exp);
4495 BlockByRefDeclsPtrSet.insert(VD);
4496 BlockByRefDecls.push_back(VD);
4497 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004498 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004499 // Find any imported blocks...they will need special attention.
4500 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4501 if (InnerBlockDeclRefs[i]->isByRef() ||
4502 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4503 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4504 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004505 }
4506 InnerDeclRefsCount.push_back(countOfInnerDecls);
4507
Steve Narofffa15fd92008-10-28 20:29:00 +00004508 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004511 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004512 else if (CurMethodDef)
4513 BuildUniqueMethodName(FuncName, CurMethodDef);
4514 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004515 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004516
Steve Narofffa15fd92008-10-28 20:29:00 +00004517 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004518
Steve Narofffa15fd92008-10-28 20:29:00 +00004519 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4520 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004521
Steve Narofffa15fd92008-10-28 20:29:00 +00004522 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004523 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4524 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004525
4526 FunctionDecl *FD;
4527 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004528
Steve Narofffa15fd92008-10-28 20:29:00 +00004529 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004530 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004531 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4532 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Chris Lattner5f9e2722011-07-23 10:55:15 +00004534 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Narofffdc03722008-10-29 21:23:59 +00004536 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004537 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004538 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004539 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004540 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004541 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004542 InitExprs.push_back(castExpr);
4543
Steve Naroff01aec112009-12-06 21:14:13 +00004544 // Initialize the block descriptor.
4545 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004546
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004547 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4548 SourceLocation(), SourceLocation(),
4549 &Context->Idents.get(DescData.c_str()),
4550 Context->VoidPtrTy, 0,
4551 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004552 UnaryOperator *DescRefExpr =
4553 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4554 Context->VoidPtrTy,
4555 VK_LValue,
4556 SourceLocation()),
4557 UO_AddrOf,
4558 Context->getPointerType(Context->VoidPtrTy),
4559 VK_RValue, OK_Ordinary,
4560 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004561 InitExprs.push_back(DescRefExpr);
4562
Steve Narofffa15fd92008-10-28 20:29:00 +00004563 // Add initializers for any closure decl refs.
4564 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004565 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004566 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004567 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004568 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004569 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004570 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004571 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004572 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4573 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004574 if (HasLocalVariableExternalStorage(*I)) {
4575 QualType QT = (*I)->getType();
4576 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004577 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4578 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004579 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004580 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004581 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004582 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4583 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004584 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004585 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004586 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004587 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004588 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4589 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004590 if (HasLocalVariableExternalStorage(*I)) {
4591 QualType QT = (*I)->getType();
4592 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004593 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4594 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004595 }
4596
Steve Narofffa15fd92008-10-28 20:29:00 +00004597 }
Mike Stump1eb44332009-09-09 15:08:12 +00004598 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004599 }
4600 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004601 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004602 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004603 ValueDecl *ND = (*I);
4604 std::string Name(ND->getNameAsString());
4605 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004606 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004607 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4608 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004609 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004610 SourceLocation(), SourceLocation(),
4611 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004612 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4613 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4614
Daniel Dunbar4087f272010-08-17 22:39:59 +00004615 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004616 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4617 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004618 bool isNestedCapturedVar = false;
4619 if (block)
4620 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4621 ce = block->capture_end(); ci != ce; ++ci) {
4622 const VarDecl *variable = ci->getVariable();
4623 if (variable == ND && ci->isNested()) {
4624 assert (ci->isByRef() &&
4625 "SynthBlockInitExpr - captured block variable is not byref");
4626 isNestedCapturedVar = true;
4627 break;
4628 }
4629 }
4630 // captured nested byref variable has its address passed. Do not take
4631 // its address again.
4632 if (!isNestedCapturedVar)
4633 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004634 Context->getPointerType(Exp->getType()),
4635 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004636 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004637 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004638 }
4639 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004640 if (ImportedBlockDecls.size()) {
4641 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4642 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004643 unsigned IntSize =
4644 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004645 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4646 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004647 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004648 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004649 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004650 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004651 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004652 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004653 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004654 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004655 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004656 BlockDeclRefs.clear();
4657 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004658 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004659 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004660 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004661 ImportedBlockDecls.clear();
4662 return NewRep;
4663}
4664
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004665bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4666 if (const ObjCForCollectionStmt * CS =
4667 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4668 return CS->getElement() == DS;
4669 return false;
4670}
4671
Steve Narofffa15fd92008-10-28 20:29:00 +00004672//===----------------------------------------------------------------------===//
4673// Function Body / Expression rewriting
4674//===----------------------------------------------------------------------===//
4675
4676Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004677 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004678 isa<DoStmt>(S) || isa<ForStmt>(S))
4679 Stmts.push_back(S);
4680 else if (isa<ObjCForCollectionStmt>(S)) {
4681 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004682 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004683 }
Mike Stump1eb44332009-09-09 15:08:12 +00004684
John McCall4b9c2d22011-11-06 09:01:30 +00004685 // Pseudo-object operations and ivar references need special
4686 // treatment because we're going to recursively rewrite them.
4687 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4688 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4689 return RewritePropertyOrImplicitSetter(PseudoOp);
4690 } else {
4691 return RewritePropertyOrImplicitGetter(PseudoOp);
4692 }
4693 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4694 return RewriteObjCIvarRefExpr(IvarRefExpr);
4695 }
4696
Steve Narofffa15fd92008-10-28 20:29:00 +00004697 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004698
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004700 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004701 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004702 Stmt *childStmt = (*CI);
4703 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004704 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004705 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004706 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004707 }
Mike Stump1eb44332009-09-09 15:08:12 +00004708
Steve Narofffa15fd92008-10-28 20:29:00 +00004709 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004710 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004711 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4712 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004713 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004714 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004715 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004717 Stmt *SaveCurrentBody = CurrentBody;
4718 CurrentBody = BE->getBody();
4719 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004720 // block literal on rhs of a property-dot-sytax assignment
4721 // must be replaced by its synthesize ast so getRewrittenText
4722 // works as expected. In this case, what actually ends up on RHS
4723 // is the blockTranscribed which is the helper function for the
4724 // block literal; as in: self.c = ^() {[ace ARR];};
4725 bool saveDisableReplaceStmt = DisableReplaceStmt;
4726 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004727 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004728 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004729 CurrentBody = SaveCurrentBody;
4730 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004731 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004732 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004733 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004734 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004736 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4737
Steve Narofffa15fd92008-10-28 20:29:00 +00004738 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004739 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004740 return blockTranscribed;
4741 }
4742 // Handle specific things.
4743 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4744 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004745
Steve Narofffa15fd92008-10-28 20:29:00 +00004746 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4747 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Steve Narofffa15fd92008-10-28 20:29:00 +00004749 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4750 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Steve Narofffa15fd92008-10-28 20:29:00 +00004752 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004753#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 // Before we rewrite it, put the original message expression in a comment.
4755 SourceLocation startLoc = MessExpr->getLocStart();
4756 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Steve Narofffa15fd92008-10-28 20:29:00 +00004758 const char *startBuf = SM->getCharacterData(startLoc);
4759 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Steve Narofffa15fd92008-10-28 20:29:00 +00004761 std::string messString;
4762 messString += "// ";
4763 messString.append(startBuf, endBuf-startBuf+1);
4764 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004765
4766 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004767 // InsertText(clang::SourceLocation, char const*, unsigned int).
4768 // InsertText(startLoc, messString.c_str(), messString.size());
4769 // Tried this, but it didn't work either...
4770 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004771#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004772 return RewriteMessageExpr(MessExpr);
4773 }
Mike Stump1eb44332009-09-09 15:08:12 +00004774
Steve Narofffa15fd92008-10-28 20:29:00 +00004775 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4776 return RewriteObjCTryStmt(StmtTry);
4777
4778 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4779 return RewriteObjCSynchronizedStmt(StmtTry);
4780
4781 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4782 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004783
Steve Narofffa15fd92008-10-28 20:29:00 +00004784 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4785 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004786
4787 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004788 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004789 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004790 OrigStmtRange.getEnd());
4791 if (BreakStmt *StmtBreakStmt =
4792 dyn_cast<BreakStmt>(S))
4793 return RewriteBreakStmt(StmtBreakStmt);
4794 if (ContinueStmt *StmtContinueStmt =
4795 dyn_cast<ContinueStmt>(S))
4796 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004797
4798 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004799 // and cast exprs.
4800 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4801 // FIXME: What we're doing here is modifying the type-specifier that
4802 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004803 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004804 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4805 // the context of an ObjCForCollectionStmt. For example:
4806 // NSArray *someArray;
4807 // for (id <FooProtocol> index in someArray) ;
4808 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4809 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004810 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004811 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004812
Steve Narofffa15fd92008-10-28 20:29:00 +00004813 // Blocks rewrite rules.
4814 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4815 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004816 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004817 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004818 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004819 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004820 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004821 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004822 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004823 if (VD->hasAttr<BlocksAttr>()) {
4824 static unsigned uniqueByrefDeclCount = 0;
4825 assert(!BlockByRefDeclNo.count(ND) &&
4826 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4827 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004828 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004829 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004830 else
4831 RewriteTypeOfDecl(VD);
4832 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004833 }
Richard Smith162e1c12011-04-15 14:24:37 +00004834 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004835 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004836 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004837 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4839 }
4840 }
4841 }
Mike Stump1eb44332009-09-09 15:08:12 +00004842
Steve Narofffa15fd92008-10-28 20:29:00 +00004843 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4844 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004845
4846 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004847 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4848 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004849 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4850 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004851 && "Statement stack mismatch");
4852 Stmts.pop_back();
4853 }
4854 // Handle blocks rewriting.
4855 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4856 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004857 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004858 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004859 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4860 ValueDecl *VD = DRE->getDecl();
4861 if (VD->hasAttr<BlocksAttr>())
4862 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004863 if (HasLocalVariableExternalStorage(VD))
4864 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004865 }
4866
Steve Narofffa15fd92008-10-28 20:29:00 +00004867 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004868 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004869 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004870 ReplaceStmt(S, BlockCall);
4871 return BlockCall;
4872 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004873 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004874 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004875 RewriteCastExpr(CE);
4876 }
4877#if 0
4878 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004879 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4880 ICE->getSubExpr(),
4881 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004882 // Get the new text.
4883 std::string SStr;
4884 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004885 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004886 const std::string &Str = Buf.str();
4887
4888 printf("CAST = %s\n", &Str[0]);
4889 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4890 delete S;
4891 return Replacement;
4892 }
4893#endif
4894 // Return this stmt unmodified.
4895 return S;
4896}
4897
Steve Naroff3d7e7862009-12-05 15:55:59 +00004898void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4899 for (RecordDecl::field_iterator i = RD->field_begin(),
4900 e = RD->field_end(); i != e; ++i) {
4901 FieldDecl *FD = *i;
4902 if (isTopLevelBlockPointerType(FD->getType()))
4903 RewriteBlockPointerDecl(FD);
4904 if (FD->getType()->isObjCQualifiedIdType() ||
4905 FD->getType()->isObjCQualifiedInterfaceType())
4906 RewriteObjCQualifiedInterfaceTypes(FD);
4907 }
4908}
4909
Steve Narofffa15fd92008-10-28 20:29:00 +00004910/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4911/// main file of the input.
4912void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004913 switch (D->getKind()) {
4914 case Decl::Function: {
4915 FunctionDecl *FD = cast<FunctionDecl>(D);
4916 if (FD->isOverloadedOperator())
4917 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004918
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004919 // Since function prototypes don't have ParmDecl's, we check the function
4920 // prototype. This enables us to rewrite function declarations and
4921 // definitions using the same code.
4922 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004923
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004924 // FIXME: If this should support Obj-C++, support CXXTryStmt
4925 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4926 CurFunctionDef = FD;
4927 CurFunctionDeclToDeclareForBlock = FD;
4928 CurrentBody = Body;
4929 Body =
4930 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4931 FD->setBody(Body);
4932 CurrentBody = 0;
4933 if (PropParentMap) {
4934 delete PropParentMap;
4935 PropParentMap = 0;
4936 }
4937 // This synthesizes and inserts the block "impl" struct, invoke function,
4938 // and any copy/dispose helper functions.
4939 InsertBlockLiteralsWithinFunction(FD);
4940 CurFunctionDef = 0;
4941 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004942 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004943 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004944 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004945 case Decl::ObjCMethod: {
4946 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4947 if (CompoundStmt *Body = MD->getCompoundBody()) {
4948 CurMethodDef = MD;
4949 CurrentBody = Body;
4950 Body =
4951 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4952 MD->setBody(Body);
4953 CurrentBody = 0;
4954 if (PropParentMap) {
4955 delete PropParentMap;
4956 PropParentMap = 0;
4957 }
4958 InsertBlockLiteralsWithinMethod(MD);
4959 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004960 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004961 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004962 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004963 case Decl::ObjCImplementation: {
4964 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4965 ClassImplementation.push_back(CI);
4966 break;
4967 }
4968 case Decl::ObjCCategoryImpl: {
4969 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4970 CategoryImplementation.push_back(CI);
4971 break;
4972 }
4973 case Decl::Var: {
4974 VarDecl *VD = cast<VarDecl>(D);
4975 RewriteObjCQualifiedInterfaceTypes(VD);
4976 if (isTopLevelBlockPointerType(VD->getType()))
4977 RewriteBlockPointerDecl(VD);
4978 else if (VD->getType()->isFunctionPointerType()) {
4979 CheckFunctionPointerDecl(VD->getType(), VD);
4980 if (VD->getInit()) {
4981 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4982 RewriteCastExpr(CE);
4983 }
4984 }
4985 } else if (VD->getType()->isRecordType()) {
4986 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4987 if (RD->isCompleteDefinition())
4988 RewriteRecordBody(RD);
4989 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004990 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004991 GlobalVarDecl = VD;
4992 CurrentBody = VD->getInit();
4993 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4994 CurrentBody = 0;
4995 if (PropParentMap) {
4996 delete PropParentMap;
4997 PropParentMap = 0;
4998 }
4999 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5000 GlobalVarDecl = 0;
5001
5002 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005003 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005004 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005005 }
5006 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005007 break;
5008 }
5009 case Decl::TypeAlias:
5010 case Decl::Typedef: {
5011 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5012 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5013 RewriteBlockPointerDecl(TD);
5014 else if (TD->getUnderlyingType()->isFunctionPointerType())
5015 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5016 }
5017 break;
5018 }
5019 case Decl::CXXRecord:
5020 case Decl::Record: {
5021 RecordDecl *RD = cast<RecordDecl>(D);
5022 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005023 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005024 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005025 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005026 default:
5027 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005028 }
5029 // Nothing yet.
5030}
5031
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005032void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005033 if (Diags.hasErrorOccurred())
5034 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005035
Steve Narofffa15fd92008-10-28 20:29:00 +00005036 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005037
Steve Naroff621edce2009-04-29 16:37:50 +00005038 // Here's a great place to add any extra declarations that may be needed.
5039 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005040 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005041 E = ProtocolExprDecls.end(); I != E; ++I)
5042 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5043
Benjamin Kramerd999b372010-02-14 14:14:16 +00005044 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005045 if (ClassImplementation.size() || CategoryImplementation.size())
5046 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005047
Steve Narofffa15fd92008-10-28 20:29:00 +00005048 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5049 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005050 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005051 Rewrite.getRewriteBufferFor(MainFileID)) {
5052 //printf("Changed:\n");
5053 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5054 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005055 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005056 }
Steve Narofface66252008-11-13 20:07:04 +00005057
Steve Naroff621edce2009-04-29 16:37:50 +00005058 if (ClassImplementation.size() || CategoryImplementation.size() ||
5059 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005060 // Rewrite Objective-c meta data*
5061 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005062 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005063 // Emit metadata.
5064 *OutFile << ResultStr;
5065 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005066 OutFile->flush();
5067}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005068
5069void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5070 InitializeCommon(context);
5071
5072 // declaring objc_selector outside the parameter list removes a silly
5073 // scope related warning...
5074 if (IsHeader)
5075 Preamble = "#pragma once\n";
5076 Preamble += "struct objc_selector; struct objc_class;\n";
5077 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5078 Preamble += "struct objc_object *superClass; ";
5079 if (LangOpts.MicrosoftExt) {
5080 // Add a constructor for creating temporary objects.
5081 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5082 ": ";
5083 Preamble += "object(o), superClass(s) {} ";
5084 }
5085 Preamble += "};\n";
5086 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5087 Preamble += "typedef struct objc_object Protocol;\n";
5088 Preamble += "#define _REWRITER_typedef_Protocol\n";
5089 Preamble += "#endif\n";
5090 if (LangOpts.MicrosoftExt) {
5091 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5092 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5093 } else
5094 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5096 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5098 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5100 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5102 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5104 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5106 Preamble += "(const char *);\n";
5107 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5108 Preamble += "(struct objc_class *);\n";
5109 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5110 Preamble += "(const char *);\n";
5111 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5112 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5114 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5115 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5116 Preamble += "(struct objc_class *, struct objc_object *);\n";
5117 // @synchronized hooks.
5118 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5119 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5120 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5121 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5122 Preamble += "struct __objcFastEnumerationState {\n\t";
5123 Preamble += "unsigned long state;\n\t";
5124 Preamble += "void **itemsPtr;\n\t";
5125 Preamble += "unsigned long *mutationsPtr;\n\t";
5126 Preamble += "unsigned long extra[5];\n};\n";
5127 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5128 Preamble += "#define __FASTENUMERATIONSTATE\n";
5129 Preamble += "#endif\n";
5130 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5131 Preamble += "struct __NSConstantStringImpl {\n";
5132 Preamble += " int *isa;\n";
5133 Preamble += " int flags;\n";
5134 Preamble += " char *str;\n";
5135 Preamble += " long length;\n";
5136 Preamble += "};\n";
5137 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5138 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5139 Preamble += "#else\n";
5140 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5141 Preamble += "#endif\n";
5142 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5143 Preamble += "#endif\n";
5144 // Blocks preamble.
5145 Preamble += "#ifndef BLOCK_IMPL\n";
5146 Preamble += "#define BLOCK_IMPL\n";
5147 Preamble += "struct __block_impl {\n";
5148 Preamble += " void *isa;\n";
5149 Preamble += " int Flags;\n";
5150 Preamble += " int Reserved;\n";
5151 Preamble += " void *FuncPtr;\n";
5152 Preamble += "};\n";
5153 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5154 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5155 Preamble += "extern \"C\" __declspec(dllexport) "
5156 "void _Block_object_assign(void *, const void *, const int);\n";
5157 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5158 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5159 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5160 Preamble += "#else\n";
5161 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5163 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5165 Preamble += "#endif\n";
5166 Preamble += "#endif\n";
5167 if (LangOpts.MicrosoftExt) {
5168 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5169 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5170 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5171 Preamble += "#define __attribute__(X)\n";
5172 Preamble += "#endif\n";
5173 Preamble += "#define __weak\n";
5174 }
5175 else {
5176 Preamble += "#define __block\n";
5177 Preamble += "#define __weak\n";
5178 }
5179 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5180 // as this avoids warning in any 64bit/32bit compilation model.
5181 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5182}
5183
5184/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5185/// ivar offset.
5186void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5187 std::string &Result) {
5188 if (ivar->isBitField()) {
5189 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5190 // place all bitfields at offset 0.
5191 Result += "0";
5192 } else {
5193 Result += "__OFFSETOFIVAR__(struct ";
5194 Result += ivar->getContainingInterface()->getNameAsString();
5195 if (LangOpts.MicrosoftExt)
5196 Result += "_IMPL";
5197 Result += ", ";
5198 Result += ivar->getNameAsString();
5199 Result += ")";
5200 }
5201}
5202
5203/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5204void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5205 ObjCProtocolDecl *PDecl, StringRef prefix,
5206 StringRef ClassName, std::string &Result) {
5207 static bool objc_protocol_methods = false;
5208
5209 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005210 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005211 /* struct protocol_methods {
5212 SEL _cmd;
5213 char *method_types;
5214 }
5215 */
5216 Result += "\nstruct _protocol_methods {\n";
5217 Result += "\tstruct objc_selector *_cmd;\n";
5218 Result += "\tchar *method_types;\n";
5219 Result += "};\n";
5220
5221 objc_protocol_methods = true;
5222 }
5223 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005224 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005225 return;
5226
Douglas Gregor61cc2962012-01-02 02:00:30 +00005227 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5228 PDecl = Def;
5229
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005230 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5231 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5232 PDecl->instmeth_end());
5233 /* struct _objc_protocol_method_list {
5234 int protocol_method_count;
5235 struct protocol_methods protocols[];
5236 }
5237 */
5238 Result += "\nstatic struct {\n";
5239 Result += "\tint protocol_method_count;\n";
5240 Result += "\tstruct _protocol_methods protocol_methods[";
5241 Result += utostr(NumMethods);
5242 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5243 Result += PDecl->getNameAsString();
5244 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5245 "{\n\t" + utostr(NumMethods) + "\n";
5246
5247 // Output instance methods declared in this protocol.
5248 for (ObjCProtocolDecl::instmeth_iterator
5249 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5250 I != E; ++I) {
5251 if (I == PDecl->instmeth_begin())
5252 Result += "\t ,{{(struct objc_selector *)\"";
5253 else
5254 Result += "\t ,{(struct objc_selector *)\"";
5255 Result += (*I)->getSelector().getAsString();
5256 std::string MethodTypeString;
5257 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5258 Result += "\", \"";
5259 Result += MethodTypeString;
5260 Result += "\"}\n";
5261 }
5262 Result += "\t }\n};\n";
5263 }
5264
5265 // Output class methods declared in this protocol.
5266 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5267 PDecl->classmeth_end());
5268 if (NumMethods > 0) {
5269 /* struct _objc_protocol_method_list {
5270 int protocol_method_count;
5271 struct protocol_methods protocols[];
5272 }
5273 */
5274 Result += "\nstatic struct {\n";
5275 Result += "\tint protocol_method_count;\n";
5276 Result += "\tstruct _protocol_methods protocol_methods[";
5277 Result += utostr(NumMethods);
5278 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5279 Result += PDecl->getNameAsString();
5280 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5281 "{\n\t";
5282 Result += utostr(NumMethods);
5283 Result += "\n";
5284
5285 // Output instance methods declared in this protocol.
5286 for (ObjCProtocolDecl::classmeth_iterator
5287 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5288 I != E; ++I) {
5289 if (I == PDecl->classmeth_begin())
5290 Result += "\t ,{{(struct objc_selector *)\"";
5291 else
5292 Result += "\t ,{(struct objc_selector *)\"";
5293 Result += (*I)->getSelector().getAsString();
5294 std::string MethodTypeString;
5295 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5296 Result += "\", \"";
5297 Result += MethodTypeString;
5298 Result += "\"}\n";
5299 }
5300 Result += "\t }\n};\n";
5301 }
5302
5303 // Output:
5304 /* struct _objc_protocol {
5305 // Objective-C 1.0 extensions
5306 struct _objc_protocol_extension *isa;
5307 char *protocol_name;
5308 struct _objc_protocol **protocol_list;
5309 struct _objc_protocol_method_list *instance_methods;
5310 struct _objc_protocol_method_list *class_methods;
5311 };
5312 */
5313 static bool objc_protocol = false;
5314 if (!objc_protocol) {
5315 Result += "\nstruct _objc_protocol {\n";
5316 Result += "\tstruct _objc_protocol_extension *isa;\n";
5317 Result += "\tchar *protocol_name;\n";
5318 Result += "\tstruct _objc_protocol **protocol_list;\n";
5319 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5320 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5321 Result += "};\n";
5322
5323 objc_protocol = true;
5324 }
5325
5326 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5327 Result += PDecl->getNameAsString();
5328 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5329 "{\n\t0, \"";
5330 Result += PDecl->getNameAsString();
5331 Result += "\", 0, ";
5332 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5333 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5334 Result += PDecl->getNameAsString();
5335 Result += ", ";
5336 }
5337 else
5338 Result += "0, ";
5339 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5340 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5341 Result += PDecl->getNameAsString();
5342 Result += "\n";
5343 }
5344 else
5345 Result += "0\n";
5346 Result += "};\n";
5347
5348 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005349 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005350 llvm_unreachable("protocol already synthesized");
5351
5352}
5353
5354void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5355 const ObjCList<ObjCProtocolDecl> &Protocols,
5356 StringRef prefix, StringRef ClassName,
5357 std::string &Result) {
5358 if (Protocols.empty()) return;
5359
5360 for (unsigned i = 0; i != Protocols.size(); i++)
5361 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5362
5363 // Output the top lovel protocol meta-data for the class.
5364 /* struct _objc_protocol_list {
5365 struct _objc_protocol_list *next;
5366 int protocol_count;
5367 struct _objc_protocol *class_protocols[];
5368 }
5369 */
5370 Result += "\nstatic struct {\n";
5371 Result += "\tstruct _objc_protocol_list *next;\n";
5372 Result += "\tint protocol_count;\n";
5373 Result += "\tstruct _objc_protocol *class_protocols[";
5374 Result += utostr(Protocols.size());
5375 Result += "];\n} _OBJC_";
5376 Result += prefix;
5377 Result += "_PROTOCOLS_";
5378 Result += ClassName;
5379 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5380 "{\n\t0, ";
5381 Result += utostr(Protocols.size());
5382 Result += "\n";
5383
5384 Result += "\t,{&_OBJC_PROTOCOL_";
5385 Result += Protocols[0]->getNameAsString();
5386 Result += " \n";
5387
5388 for (unsigned i = 1; i != Protocols.size(); i++) {
5389 Result += "\t ,&_OBJC_PROTOCOL_";
5390 Result += Protocols[i]->getNameAsString();
5391 Result += "\n";
5392 }
5393 Result += "\t }\n};\n";
5394}
5395
5396void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5397 std::string &Result) {
5398 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5399
5400 // Explicitly declared @interface's are already synthesized.
5401 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005402 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005403 // produce correct synthesis as yet.
5404 RewriteObjCInternalStruct(CDecl, Result);
5405 }
5406
5407 // Build _objc_ivar_list metadata for classes ivars if needed
5408 unsigned NumIvars = !IDecl->ivar_empty()
5409 ? IDecl->ivar_size()
5410 : (CDecl ? CDecl->ivar_size() : 0);
5411 if (NumIvars > 0) {
5412 static bool objc_ivar = false;
5413 if (!objc_ivar) {
5414 /* struct _objc_ivar {
5415 char *ivar_name;
5416 char *ivar_type;
5417 int ivar_offset;
5418 };
5419 */
5420 Result += "\nstruct _objc_ivar {\n";
5421 Result += "\tchar *ivar_name;\n";
5422 Result += "\tchar *ivar_type;\n";
5423 Result += "\tint ivar_offset;\n";
5424 Result += "};\n";
5425
5426 objc_ivar = true;
5427 }
5428
5429 /* struct {
5430 int ivar_count;
5431 struct _objc_ivar ivar_list[nIvars];
5432 };
5433 */
5434 Result += "\nstatic struct {\n";
5435 Result += "\tint ivar_count;\n";
5436 Result += "\tstruct _objc_ivar ivar_list[";
5437 Result += utostr(NumIvars);
5438 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5439 Result += IDecl->getNameAsString();
5440 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5441 "{\n\t";
5442 Result += utostr(NumIvars);
5443 Result += "\n";
5444
5445 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5446 SmallVector<ObjCIvarDecl *, 8> IVars;
5447 if (!IDecl->ivar_empty()) {
5448 for (ObjCInterfaceDecl::ivar_iterator
5449 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5450 IV != IVEnd; ++IV)
5451 IVars.push_back(*IV);
5452 IVI = IDecl->ivar_begin();
5453 IVE = IDecl->ivar_end();
5454 } else {
5455 IVI = CDecl->ivar_begin();
5456 IVE = CDecl->ivar_end();
5457 }
5458 Result += "\t,{{\"";
5459 Result += (*IVI)->getNameAsString();
5460 Result += "\", \"";
5461 std::string TmpString, StrEncoding;
5462 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5463 QuoteDoublequotes(TmpString, StrEncoding);
5464 Result += StrEncoding;
5465 Result += "\", ";
5466 RewriteIvarOffsetComputation(*IVI, Result);
5467 Result += "}\n";
5468 for (++IVI; IVI != IVE; ++IVI) {
5469 Result += "\t ,{\"";
5470 Result += (*IVI)->getNameAsString();
5471 Result += "\", \"";
5472 std::string TmpString, StrEncoding;
5473 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5474 QuoteDoublequotes(TmpString, StrEncoding);
5475 Result += StrEncoding;
5476 Result += "\", ";
5477 RewriteIvarOffsetComputation((*IVI), Result);
5478 Result += "}\n";
5479 }
5480
5481 Result += "\t }\n};\n";
5482 }
5483
5484 // Build _objc_method_list for class's instance methods if needed
5485 SmallVector<ObjCMethodDecl *, 32>
5486 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5487
5488 // If any of our property implementations have associated getters or
5489 // setters, produce metadata for them as well.
5490 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5491 PropEnd = IDecl->propimpl_end();
5492 Prop != PropEnd; ++Prop) {
5493 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5494 continue;
5495 if (!(*Prop)->getPropertyIvarDecl())
5496 continue;
5497 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5498 if (!PD)
5499 continue;
5500 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5501 if (!Getter->isDefined())
5502 InstanceMethods.push_back(Getter);
5503 if (PD->isReadOnly())
5504 continue;
5505 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5506 if (!Setter->isDefined())
5507 InstanceMethods.push_back(Setter);
5508 }
5509 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5510 true, "", IDecl->getName(), Result);
5511
5512 // Build _objc_method_list for class's class methods if needed
5513 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5514 false, "", IDecl->getName(), Result);
5515
5516 // Protocols referenced in class declaration?
5517 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5518 "CLASS", CDecl->getName(), Result);
5519
5520 // Declaration of class/meta-class metadata
5521 /* struct _objc_class {
5522 struct _objc_class *isa; // or const char *root_class_name when metadata
5523 const char *super_class_name;
5524 char *name;
5525 long version;
5526 long info;
5527 long instance_size;
5528 struct _objc_ivar_list *ivars;
5529 struct _objc_method_list *methods;
5530 struct objc_cache *cache;
5531 struct objc_protocol_list *protocols;
5532 const char *ivar_layout;
5533 struct _objc_class_ext *ext;
5534 };
5535 */
5536 static bool objc_class = false;
5537 if (!objc_class) {
5538 Result += "\nstruct _objc_class {\n";
5539 Result += "\tstruct _objc_class *isa;\n";
5540 Result += "\tconst char *super_class_name;\n";
5541 Result += "\tchar *name;\n";
5542 Result += "\tlong version;\n";
5543 Result += "\tlong info;\n";
5544 Result += "\tlong instance_size;\n";
5545 Result += "\tstruct _objc_ivar_list *ivars;\n";
5546 Result += "\tstruct _objc_method_list *methods;\n";
5547 Result += "\tstruct objc_cache *cache;\n";
5548 Result += "\tstruct _objc_protocol_list *protocols;\n";
5549 Result += "\tconst char *ivar_layout;\n";
5550 Result += "\tstruct _objc_class_ext *ext;\n";
5551 Result += "};\n";
5552 objc_class = true;
5553 }
5554
5555 // Meta-class metadata generation.
5556 ObjCInterfaceDecl *RootClass = 0;
5557 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5558 while (SuperClass) {
5559 RootClass = SuperClass;
5560 SuperClass = SuperClass->getSuperClass();
5561 }
5562 SuperClass = CDecl->getSuperClass();
5563
5564 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5565 Result += CDecl->getNameAsString();
5566 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5567 "{\n\t(struct _objc_class *)\"";
5568 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5569 Result += "\"";
5570
5571 if (SuperClass) {
5572 Result += ", \"";
5573 Result += SuperClass->getNameAsString();
5574 Result += "\", \"";
5575 Result += CDecl->getNameAsString();
5576 Result += "\"";
5577 }
5578 else {
5579 Result += ", 0, \"";
5580 Result += CDecl->getNameAsString();
5581 Result += "\"";
5582 }
5583 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5584 // 'info' field is initialized to CLS_META(2) for metaclass
5585 Result += ", 0,2, sizeof(struct _objc_class), 0";
5586 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5587 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5588 Result += IDecl->getNameAsString();
5589 Result += "\n";
5590 }
5591 else
5592 Result += ", 0\n";
5593 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5594 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5595 Result += CDecl->getNameAsString();
5596 Result += ",0,0\n";
5597 }
5598 else
5599 Result += "\t,0,0,0,0\n";
5600 Result += "};\n";
5601
5602 // class metadata generation.
5603 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5604 Result += CDecl->getNameAsString();
5605 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5606 "{\n\t&_OBJC_METACLASS_";
5607 Result += CDecl->getNameAsString();
5608 if (SuperClass) {
5609 Result += ", \"";
5610 Result += SuperClass->getNameAsString();
5611 Result += "\", \"";
5612 Result += CDecl->getNameAsString();
5613 Result += "\"";
5614 }
5615 else {
5616 Result += ", 0, \"";
5617 Result += CDecl->getNameAsString();
5618 Result += "\"";
5619 }
5620 // 'info' field is initialized to CLS_CLASS(1) for class
5621 Result += ", 0,1";
5622 if (!ObjCSynthesizedStructs.count(CDecl))
5623 Result += ",0";
5624 else {
5625 // class has size. Must synthesize its size.
5626 Result += ",sizeof(struct ";
5627 Result += CDecl->getNameAsString();
5628 if (LangOpts.MicrosoftExt)
5629 Result += "_IMPL";
5630 Result += ")";
5631 }
5632 if (NumIvars > 0) {
5633 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5634 Result += CDecl->getNameAsString();
5635 Result += "\n\t";
5636 }
5637 else
5638 Result += ",0";
5639 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5640 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5641 Result += CDecl->getNameAsString();
5642 Result += ", 0\n\t";
5643 }
5644 else
5645 Result += ",0,0";
5646 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5647 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5648 Result += CDecl->getNameAsString();
5649 Result += ", 0,0\n";
5650 }
5651 else
5652 Result += ",0,0,0\n";
5653 Result += "};\n";
5654}
5655
5656void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5657 int ClsDefCount = ClassImplementation.size();
5658 int CatDefCount = CategoryImplementation.size();
5659
5660 // For each implemented class, write out all its meta data.
5661 for (int i = 0; i < ClsDefCount; i++)
5662 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5663
5664 // For each implemented category, write out all its meta data.
5665 for (int i = 0; i < CatDefCount; i++)
5666 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5667
5668 // Write objc_symtab metadata
5669 /*
5670 struct _objc_symtab
5671 {
5672 long sel_ref_cnt;
5673 SEL *refs;
5674 short cls_def_cnt;
5675 short cat_def_cnt;
5676 void *defs[cls_def_cnt + cat_def_cnt];
5677 };
5678 */
5679
5680 Result += "\nstruct _objc_symtab {\n";
5681 Result += "\tlong sel_ref_cnt;\n";
5682 Result += "\tSEL *refs;\n";
5683 Result += "\tshort cls_def_cnt;\n";
5684 Result += "\tshort cat_def_cnt;\n";
5685 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5686 Result += "};\n\n";
5687
5688 Result += "static struct _objc_symtab "
5689 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5690 Result += "\t0, 0, " + utostr(ClsDefCount)
5691 + ", " + utostr(CatDefCount) + "\n";
5692 for (int i = 0; i < ClsDefCount; i++) {
5693 Result += "\t,&_OBJC_CLASS_";
5694 Result += ClassImplementation[i]->getNameAsString();
5695 Result += "\n";
5696 }
5697
5698 for (int i = 0; i < CatDefCount; i++) {
5699 Result += "\t,&_OBJC_CATEGORY_";
5700 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5701 Result += "_";
5702 Result += CategoryImplementation[i]->getNameAsString();
5703 Result += "\n";
5704 }
5705
5706 Result += "};\n\n";
5707
5708 // Write objc_module metadata
5709
5710 /*
5711 struct _objc_module {
5712 long version;
5713 long size;
5714 const char *name;
5715 struct _objc_symtab *symtab;
5716 }
5717 */
5718
5719 Result += "\nstruct _objc_module {\n";
5720 Result += "\tlong version;\n";
5721 Result += "\tlong size;\n";
5722 Result += "\tconst char *name;\n";
5723 Result += "\tstruct _objc_symtab *symtab;\n";
5724 Result += "};\n\n";
5725 Result += "static struct _objc_module "
5726 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5727 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5728 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5729 Result += "};\n\n";
5730
5731 if (LangOpts.MicrosoftExt) {
5732 if (ProtocolExprDecls.size()) {
5733 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5734 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5735 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5736 E = ProtocolExprDecls.end(); I != E; ++I) {
5737 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5738 Result += (*I)->getNameAsString();
5739 Result += " = &_OBJC_PROTOCOL_";
5740 Result += (*I)->getNameAsString();
5741 Result += ";\n";
5742 }
5743 Result += "#pragma data_seg(pop)\n\n";
5744 }
5745 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5746 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5747 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5748 Result += "&_OBJC_MODULES;\n";
5749 Result += "#pragma data_seg(pop)\n\n";
5750 }
5751}
5752
5753/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5754/// implementation.
5755void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5756 std::string &Result) {
5757 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5758 // Find category declaration for this implementation.
5759 ObjCCategoryDecl *CDecl;
5760 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5761 CDecl = CDecl->getNextClassCategory())
5762 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5763 break;
5764
5765 std::string FullCategoryName = ClassDecl->getNameAsString();
5766 FullCategoryName += '_';
5767 FullCategoryName += IDecl->getNameAsString();
5768
5769 // Build _objc_method_list for class's instance methods if needed
5770 SmallVector<ObjCMethodDecl *, 32>
5771 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5772
5773 // If any of our property implementations have associated getters or
5774 // setters, produce metadata for them as well.
5775 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5776 PropEnd = IDecl->propimpl_end();
5777 Prop != PropEnd; ++Prop) {
5778 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5779 continue;
5780 if (!(*Prop)->getPropertyIvarDecl())
5781 continue;
5782 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5783 if (!PD)
5784 continue;
5785 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5786 InstanceMethods.push_back(Getter);
5787 if (PD->isReadOnly())
5788 continue;
5789 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5790 InstanceMethods.push_back(Setter);
5791 }
5792 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5793 true, "CATEGORY_", FullCategoryName.c_str(),
5794 Result);
5795
5796 // Build _objc_method_list for class's class methods if needed
5797 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5798 false, "CATEGORY_", FullCategoryName.c_str(),
5799 Result);
5800
5801 // Protocols referenced in class declaration?
5802 // Null CDecl is case of a category implementation with no category interface
5803 if (CDecl)
5804 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5805 FullCategoryName, Result);
5806 /* struct _objc_category {
5807 char *category_name;
5808 char *class_name;
5809 struct _objc_method_list *instance_methods;
5810 struct _objc_method_list *class_methods;
5811 struct _objc_protocol_list *protocols;
5812 // Objective-C 1.0 extensions
5813 uint32_t size; // sizeof (struct _objc_category)
5814 struct _objc_property_list *instance_properties; // category's own
5815 // @property decl.
5816 };
5817 */
5818
5819 static bool objc_category = false;
5820 if (!objc_category) {
5821 Result += "\nstruct _objc_category {\n";
5822 Result += "\tchar *category_name;\n";
5823 Result += "\tchar *class_name;\n";
5824 Result += "\tstruct _objc_method_list *instance_methods;\n";
5825 Result += "\tstruct _objc_method_list *class_methods;\n";
5826 Result += "\tstruct _objc_protocol_list *protocols;\n";
5827 Result += "\tunsigned int size;\n";
5828 Result += "\tstruct _objc_property_list *instance_properties;\n";
5829 Result += "};\n";
5830 objc_category = true;
5831 }
5832 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5833 Result += FullCategoryName;
5834 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5835 Result += IDecl->getNameAsString();
5836 Result += "\"\n\t, \"";
5837 Result += ClassDecl->getNameAsString();
5838 Result += "\"\n";
5839
5840 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5841 Result += "\t, (struct _objc_method_list *)"
5842 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5843 Result += FullCategoryName;
5844 Result += "\n";
5845 }
5846 else
5847 Result += "\t, 0\n";
5848 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5849 Result += "\t, (struct _objc_method_list *)"
5850 "&_OBJC_CATEGORY_CLASS_METHODS_";
5851 Result += FullCategoryName;
5852 Result += "\n";
5853 }
5854 else
5855 Result += "\t, 0\n";
5856
5857 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5858 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5859 Result += FullCategoryName;
5860 Result += "\n";
5861 }
5862 else
5863 Result += "\t, 0\n";
5864 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5865}
5866
5867// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5868/// class methods.
5869template<typename MethodIterator>
5870void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5871 MethodIterator MethodEnd,
5872 bool IsInstanceMethod,
5873 StringRef prefix,
5874 StringRef ClassName,
5875 std::string &Result) {
5876 if (MethodBegin == MethodEnd) return;
5877
5878 if (!objc_impl_method) {
5879 /* struct _objc_method {
5880 SEL _cmd;
5881 char *method_types;
5882 void *_imp;
5883 }
5884 */
5885 Result += "\nstruct _objc_method {\n";
5886 Result += "\tSEL _cmd;\n";
5887 Result += "\tchar *method_types;\n";
5888 Result += "\tvoid *_imp;\n";
5889 Result += "};\n";
5890
5891 objc_impl_method = true;
5892 }
5893
5894 // Build _objc_method_list for class's methods if needed
5895
5896 /* struct {
5897 struct _objc_method_list *next_method;
5898 int method_count;
5899 struct _objc_method method_list[];
5900 }
5901 */
5902 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5903 Result += "\nstatic struct {\n";
5904 Result += "\tstruct _objc_method_list *next_method;\n";
5905 Result += "\tint method_count;\n";
5906 Result += "\tstruct _objc_method method_list[";
5907 Result += utostr(NumMethods);
5908 Result += "];\n} _OBJC_";
5909 Result += prefix;
5910 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5911 Result += "_METHODS_";
5912 Result += ClassName;
5913 Result += " __attribute__ ((used, section (\"__OBJC, __";
5914 Result += IsInstanceMethod ? "inst" : "cls";
5915 Result += "_meth\")))= ";
5916 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5917
5918 Result += "\t,{{(SEL)\"";
5919 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5920 std::string MethodTypeString;
5921 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5922 Result += "\", \"";
5923 Result += MethodTypeString;
5924 Result += "\", (void *)";
5925 Result += MethodInternalNames[*MethodBegin];
5926 Result += "}\n";
5927 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5928 Result += "\t ,{(SEL)\"";
5929 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5930 std::string MethodTypeString;
5931 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5932 Result += "\", \"";
5933 Result += MethodTypeString;
5934 Result += "\", (void *)";
5935 Result += MethodInternalNames[*MethodBegin];
5936 Result += "}\n";
5937 }
5938 Result += "\t }\n};\n";
5939}
5940
5941Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5942 SourceRange OldRange = IV->getSourceRange();
5943 Expr *BaseExpr = IV->getBase();
5944
5945 // Rewrite the base, but without actually doing replaces.
5946 {
5947 DisableReplaceStmtScope S(*this);
5948 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5949 IV->setBase(BaseExpr);
5950 }
5951
5952 ObjCIvarDecl *D = IV->getDecl();
5953
5954 Expr *Replacement = IV;
5955 if (CurMethodDef) {
5956 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5957 const ObjCInterfaceType *iFaceDecl =
5958 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5959 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5960 // lookup which class implements the instance variable.
5961 ObjCInterfaceDecl *clsDeclared = 0;
5962 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5963 clsDeclared);
5964 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5965
5966 // Synthesize an explicit cast to gain access to the ivar.
5967 std::string RecName = clsDeclared->getIdentifier()->getName();
5968 RecName += "_IMPL";
5969 IdentifierInfo *II = &Context->Idents.get(RecName);
5970 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5971 SourceLocation(), SourceLocation(),
5972 II);
5973 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5974 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5975 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5976 CK_BitCast,
5977 IV->getBase());
5978 // Don't forget the parens to enforce the proper binding.
5979 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5980 OldRange.getEnd(),
5981 castExpr);
5982 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005983 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005984 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5985 IV->getLocation(),
5986 D->getType(),
5987 VK_LValue, OK_Ordinary);
5988 Replacement = ME;
5989 } else {
5990 IV->setBase(PE);
5991 }
5992 }
5993 } else { // we are outside a method.
5994 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5995
5996 // Explicit ivar refs need to have a cast inserted.
5997 // FIXME: consider sharing some of this code with the code above.
5998 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5999 const ObjCInterfaceType *iFaceDecl =
6000 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6001 // lookup which class implements the instance variable.
6002 ObjCInterfaceDecl *clsDeclared = 0;
6003 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6004 clsDeclared);
6005 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6006
6007 // Synthesize an explicit cast to gain access to the ivar.
6008 std::string RecName = clsDeclared->getIdentifier()->getName();
6009 RecName += "_IMPL";
6010 IdentifierInfo *II = &Context->Idents.get(RecName);
6011 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6012 SourceLocation(), SourceLocation(),
6013 II);
6014 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6015 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6016 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6017 CK_BitCast,
6018 IV->getBase());
6019 // Don't forget the parens to enforce the proper binding.
6020 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6021 IV->getBase()->getLocEnd(), castExpr);
6022 // Cannot delete IV->getBase(), since PE points to it.
6023 // Replace the old base with the cast. This is important when doing
6024 // embedded rewrites. For example, [newInv->_container addObject:0].
6025 IV->setBase(PE);
6026 }
6027 }
6028
6029 ReplaceStmtWithRange(IV, Replacement, OldRange);
6030 return Replacement;
6031}
6032