blob: 501811269977f639d5fa089dee125afd71f7cff4 [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 Jahanian64cb63a2012-02-07 17:11:38 +0000593 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000594}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000595
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000596void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000597 Context = &context;
598 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000599 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000600 MsgSendFunctionDecl = 0;
601 MsgSendSuperFunctionDecl = 0;
602 MsgSendStretFunctionDecl = 0;
603 MsgSendSuperStretFunctionDecl = 0;
604 MsgSendFpretFunctionDecl = 0;
605 GetClassFunctionDecl = 0;
606 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000607 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000608 SelGetUidFunctionDecl = 0;
609 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610 ConstantStringClassReference = 0;
611 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000612 CurMethodDef = 0;
613 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000614 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000615 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000616 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000617 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000618 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000619 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000620 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000621 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000622 PropParentMap = 0;
623 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000624 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000625 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000627 // Get the ID and start/end of the main file.
628 MainFileID = SM->getMainFileID();
629 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
630 MainFileStart = MainBuf->getBufferStart();
631 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner2c78b872009-04-14 23:22:57 +0000633 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000634}
635
Chris Lattnerf04da132007-10-24 17:06:59 +0000636//===----------------------------------------------------------------------===//
637// Top Level Driver Code
638//===----------------------------------------------------------------------===//
639
Chris Lattner682bf922009-03-29 16:50:03 +0000640void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000641 if (Diags.hasErrorOccurred())
642 return;
643
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000644 // Two cases: either the decl could be in the main file, or it could be in a
645 // #included file. If the former, rewrite it now. If the later, check to see
646 // if we rewrote the #include/#import.
647 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000648 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000650 // If this is for a builtin, ignore it.
651 if (Loc.isInvalid()) return;
652
Steve Naroffebf2b562007-10-23 23:50:29 +0000653 // Look for built-in declarations that we need to refer during the rewrite.
654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000655 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000656 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000657 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000658 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000659 ConstantStringClassReference = FVD;
660 return;
661 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000662 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
663 if (ID->isThisDeclarationADefinition())
664 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000665 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000666 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000667 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000668 if (PD->isThisDeclarationADefinition())
669 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000670 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
671 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000672 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
673 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000674 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000675 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
676 if (!IFace->isThisDeclarationADefinition()) {
677 SmallVector<Decl *, 8> DG;
678 SourceLocation StartLoc = IFace->getLocStart();
679 do {
680 if (isa<ObjCInterfaceDecl>(*DI) &&
681 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
682 StartLoc == (*DI)->getLocStart())
683 DG.push_back(*DI);
684 else
685 break;
686
Douglas Gregor7723fec2011-12-15 20:29:51 +0000687 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000688 } while (DI != DIEnd);
689 RewriteForwardClassDecl(DG);
690 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000691 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000692 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000693
694 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
695 if (!Proto->isThisDeclarationADefinition()) {
696 SmallVector<Decl *, 8> DG;
697 SourceLocation StartLoc = Proto->getLocStart();
698 do {
699 if (isa<ObjCProtocolDecl>(*DI) &&
700 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
701 StartLoc == (*DI)->getLocStart())
702 DG.push_back(*DI);
703 else
704 break;
705
706 ++DI;
707 } while (DI != DIEnd);
708 RewriteForwardProtocolDecl(DG);
709 continue;
710 }
711 }
712
Chris Lattner682bf922009-03-29 16:50:03 +0000713 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000714 ++DI;
715 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000716 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000717 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000718 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000719 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000720}
721
Chris Lattnerf04da132007-10-24 17:06:59 +0000722//===----------------------------------------------------------------------===//
723// Syntactic (non-AST) Rewriting Code
724//===----------------------------------------------------------------------===//
725
Steve Naroffb29b4272008-04-14 22:03:09 +0000726void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000727 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000728 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000729 const char *MainBufStart = MainBuf.begin();
730 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000731 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000733 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000734 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
735 if (*BufPtr == '#') {
736 if (++BufPtr == MainBufEnd)
737 return;
738 while (*BufPtr == ' ' || *BufPtr == '\t')
739 if (++BufPtr == MainBufEnd)
740 return;
741 if (!strncmp(BufPtr, "import", ImportLen)) {
742 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000743 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000744 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000745 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000746 BufPtr += ImportLen;
747 }
748 }
749 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000750}
751
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000752static std::string getIvarAccessString(ObjCIvarDecl *OID) {
753 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 std::string S;
755 S = "((struct ";
756 S += ClassDecl->getIdentifier()->getName();
757 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000758 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 return S;
760}
761
Steve Naroffa0876e82008-12-02 17:36:43 +0000762void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
763 ObjCImplementationDecl *IMD,
764 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000765 static bool objcGetPropertyDefined = false;
766 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000767 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000768 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000769 const char *startBuf = SM->getCharacterData(startLoc);
770 assert((*startBuf == '@') && "bogus @synthesize location");
771 const char *semiBuf = strchr(startBuf, ';');
772 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000773 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000774 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775
776 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
777 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000783 if (!OID)
784 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000785 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000786 if (!PD->getGetterMethodDecl()->isDefined()) {
787 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
788 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
789 ObjCPropertyDecl::OBJC_PR_copy));
790 std::string Getr;
791 if (GenGetProperty && !objcGetPropertyDefined) {
792 objcGetPropertyDefined = true;
793 // FIXME. Is this attribute correct in all cases?
794 Getr = "\nextern \"C\" __declspec(dllimport) "
795 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000796 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000797 RewriteObjCMethodDecl(OID->getContainingInterface(),
798 PD->getGetterMethodDecl(), Getr);
799 Getr += "{ ";
800 // Synthesize an explicit cast to gain access to the ivar.
801 // See objc-act.c:objc_synthesize_new_getter() for details.
802 if (GenGetProperty) {
803 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
804 Getr += "typedef ";
805 const FunctionType *FPRetType = 0;
806 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
807 FPRetType);
808 Getr += " _TYPE";
809 if (FPRetType) {
810 Getr += ")"; // close the precedence "scope" for "*".
811
812 // Now, emit the argument types (if any).
813 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
814 Getr += "(";
815 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
816 if (i) Getr += ", ";
817 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000818 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000819 Getr += ParamStr;
820 }
821 if (FT->isVariadic()) {
822 if (FT->getNumArgs()) Getr += ", ";
823 Getr += "...";
824 }
825 Getr += ")";
826 } else
827 Getr += "()";
828 }
829 Getr += ";\n";
830 Getr += "return (_TYPE)";
831 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000832 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000833 Getr += ", 1)";
834 }
835 else
836 Getr += "return " + getIvarAccessString(OID);
837 Getr += "; }";
838 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000839 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000840
841 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000842 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Steve Naroffeb0646c2008-12-02 15:48:25 +0000844 // Generate the 'setter' function.
845 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000846 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
847 ObjCPropertyDecl::OBJC_PR_copy);
848 if (GenSetProperty && !objcSetPropertyDefined) {
849 objcSetPropertyDefined = true;
850 // FIXME. Is this attribute correct in all cases?
851 Setr = "\nextern \"C\" __declspec(dllimport) "
852 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
853 }
854
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000855 RewriteObjCMethodDecl(OID->getContainingInterface(),
856 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000857 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000858 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000859 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000860 if (GenSetProperty) {
861 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000862 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000863 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000864 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 Setr += ", ";
866 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
867 Setr += "0, ";
868 else
869 Setr += "1, ";
870 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
871 Setr += "1)";
872 else
873 Setr += "0)";
874 }
875 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000876 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000877 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000879 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000880 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000881}
Chris Lattner8a12c272007-10-11 18:38:32 +0000882
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000883static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
884 std::string &typedefString) {
885 typedefString += "#ifndef _REWRITER_typedef_";
886 typedefString += ForwardDecl->getNameAsString();
887 typedefString += "\n";
888 typedefString += "#define _REWRITER_typedef_";
889 typedefString += ForwardDecl->getNameAsString();
890 typedefString += "\n";
891 typedefString += "typedef struct objc_object ";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += ";\n#endif\n";
894}
895
Douglas Gregor375bb142011-12-27 22:43:10 +0000896void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000897 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000898 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000899 const char *startBuf = SM->getCharacterData(startLoc);
900 const char *semiPtr = strchr(startBuf, ';');
901 // Replace the @class with typedefs corresponding to the classes.
902 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
903}
904
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000905void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000906 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000907 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000908 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000909 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000910 // Translate to typedef's that forward reference structs with the same name
911 // as the class. As a convenience, we include the original declaration
912 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000913 typedefString += "// @class ";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000915 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000916 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000917 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000918 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000919 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000920 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000921}
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000923void RewriteObjC::RewriteForwardClassDecl(
924 const llvm::SmallVector<Decl*, 8> &D) {
925 std::string typedefString;
926 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000927 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000928 if (i == 0) {
929 typedefString += "// @class ";
930 typedefString += ForwardDecl->getNameAsString();
931 typedefString += ";\n";
932 }
933 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
934 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000935 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000936}
937
Steve Naroffb29b4272008-04-14 22:03:09 +0000938void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000939 // When method is a synthesized one, such as a getter/setter there is
940 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000941 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000942 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 SourceLocation LocStart = Method->getLocStart();
944 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chandler Carruth64211622011-07-25 21:09:52 +0000946 if (SM->getExpansionLineNumber(LocEnd) >
947 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000948 InsertText(LocStart, "#if 0\n");
949 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000950 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000951 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000952 }
953}
954
Mike Stump1eb44332009-09-09 15:08:12 +0000955void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000956 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000959 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000960}
961
Steve Naroffb29b4272008-04-14 22:03:09 +0000962void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000963 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Steve Naroff423cb562007-10-30 13:30:57 +0000965 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000966 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000968 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
969 E = CatDecl->prop_end(); I != E; ++I)
970 RewriteProperty(*I);
971
Mike Stump1eb44332009-09-09 15:08:12 +0000972 for (ObjCCategoryDecl::instmeth_iterator
973 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000974 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000975 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000976 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000977 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000978 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000979 RewriteMethodDeclaration(*I);
980
Steve Naroff423cb562007-10-30 13:30:57 +0000981 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000982 ReplaceText(CatDecl->getAtEndRange().getBegin(),
983 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000984}
985
Steve Naroffb29b4272008-04-14 22:03:09 +0000986void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000987 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000988 assert(PDecl->isThisDeclarationADefinition());
989
Steve Naroff752d6ef2007-10-30 16:42:30 +0000990 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000991 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000992
993 for (ObjCProtocolDecl::instmeth_iterator
994 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000995 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000996 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000997 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000998 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000999 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001000 RewriteMethodDeclaration(*I);
1001
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001002 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1003 E = PDecl->prop_end(); I != E; ++I)
1004 RewriteProperty(*I);
1005
Steve Naroff752d6ef2007-10-30 16:42:30 +00001006 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001007 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001008 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 // Must comment out @optional/@required
1011 const char *startBuf = SM->getCharacterData(LocStart);
1012 const char *endBuf = SM->getCharacterData(LocEnd);
1013 for (const char *p = startBuf; p < endBuf; p++) {
1014 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001015 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001016 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001018 }
1019 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
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("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001023 }
1024 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001025}
1026
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001027void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1028 SourceLocation LocStart = (*D.begin())->getLocStart();
1029 if (LocStart.isInvalid())
1030 llvm_unreachable("Invalid SourceLocation");
1031 // FIXME: handle forward protocol that are declared across multiple lines.
1032 ReplaceText(LocStart, 0, "// ");
1033}
1034
1035void
1036RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1037 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001038 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001039 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001040 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001041 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001042}
1043
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001044void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1045 const FunctionType *&FPRetType) {
1046 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001047 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048 else if (T->isFunctionPointerType() ||
1049 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001050 // needs special handling, since pointer-to-functions have special
1051 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001052 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001053 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001054 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001055 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001057 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001058 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001059 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001060 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001061 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001062 }
1063 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001064 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001065}
1066
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001067void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1068 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001069 std::string &ResultStr) {
1070 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1071 const FunctionType *FPRetType = 0;
1072 ResultStr += "\nstatic ";
1073 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001074 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001076 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001077 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001079 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001080 NameStr += "_I_";
1081 else
1082 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001084 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001085 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001086
1087 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001088 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001090 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001093 {
1094 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 int len = selString.size();
1096 for (int i = 0; i < len; i++)
1097 if (selString[i] == ':')
1098 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001099 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001101 // Remember this name for metadata emission
1102 MethodInternalNames[OMD] = NameStr;
1103 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 // Rewrite arguments
1106 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001109 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001110 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001112 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001113 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001114 ResultStr += "struct ";
1115 }
1116 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001117 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001118 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 }
1120 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001121 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001122 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001125 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001129 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1130 E = OMD->param_end(); PI != E; ++PI) {
1131 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001133 if (PDecl->getType()->isObjCQualifiedIdType()) {
1134 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001135 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001136 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001137 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001138 QualType QT = PDecl->getType();
1139 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1140 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001141 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001142 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001143 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001144 ResultStr += Name;
1145 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001147 if (OMD->isVariadic())
1148 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001149 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Steve Naroff76e429d2008-07-16 14:40:40 +00001151 if (FPRetType) {
1152 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001155 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001156 ResultStr += "(";
1157 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1158 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001159 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001160 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001161 ResultStr += ParamStr;
1162 }
1163 if (FT->isVariadic()) {
1164 if (FT->getNumArgs()) ResultStr += ", ";
1165 ResultStr += "...";
1166 }
1167 ResultStr += ")";
1168 } else {
1169 ResultStr += "()";
1170 }
1171 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001173void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1175 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001177 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001180 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1181 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001182 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001183 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001184 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001185 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001187 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001188
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001189 const char *startBuf = SM->getCharacterData(LocStart);
1190 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001191 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001192 }
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001195 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1196 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001197 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001198 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001200 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001201 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001202 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001204 const char *startBuf = SM->getCharacterData(LocStart);
1205 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001206 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001207 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001208 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001210 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001211 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001212 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001213 }
1214
Benjamin Kramerd999b372010-02-14 14:14:16 +00001215 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001216}
1217
Steve Naroffb29b4272008-04-14 22:03:09 +00001218void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001219 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001220 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001221 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001222 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001223 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001224 ResultStr += "\n";
1225 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001226 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001227 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001228 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001230 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001231 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001232 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001233 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001234 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
1236 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001237 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001238 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001239 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001241 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001242 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001243 for (ObjCInterfaceDecl::classmeth_iterator
1244 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001245 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001246 RewriteMethodDeclaration(*I);
1247
Steve Naroff2feac5e2007-10-30 03:43:13 +00001248 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001249 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1250 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001251}
1252
John McCall4b9c2d22011-11-06 09:01:30 +00001253Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1254 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCall4b9c2d22011-11-06 09:01:30 +00001256 // We just magically know some things about the structure of this
1257 // expression.
1258 ObjCMessageExpr *OldMsg =
1259 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1260 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John McCall4b9c2d22011-11-06 09:01:30 +00001262 // Because the rewriter doesn't allow us to rewrite rewritten code,
1263 // we need to suppress rewriting the sub-statements.
1264 Expr *Base, *RHS;
1265 {
1266 DisableReplaceStmtScope S(*this);
1267
1268 // Rebuild the base expression if we have one.
1269 Base = 0;
1270 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1271 Base = OldMsg->getInstanceReceiver();
1272 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1273 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1274 }
1275
1276 // Rebuild the RHS.
1277 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1278 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1279 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1280 }
1281
1282 // TODO: avoid this copy.
1283 SmallVector<SourceLocation, 1> SelLocs;
1284 OldMsg->getSelectorLocs(SelLocs);
1285
Chad Rosier0774ba72012-01-06 20:05:14 +00001286 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001287 switch (OldMsg->getReceiverKind()) {
1288 case ObjCMessageExpr::Class:
1289 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1290 OldMsg->getValueKind(),
1291 OldMsg->getLeftLoc(),
1292 OldMsg->getClassReceiverTypeInfo(),
1293 OldMsg->getSelector(),
1294 SelLocs,
1295 OldMsg->getMethodDecl(),
1296 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001297 OldMsg->getRightLoc(),
1298 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001299 break;
1300
1301 case ObjCMessageExpr::Instance:
1302 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1303 OldMsg->getValueKind(),
1304 OldMsg->getLeftLoc(),
1305 Base,
1306 OldMsg->getSelector(),
1307 SelLocs,
1308 OldMsg->getMethodDecl(),
1309 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001310 OldMsg->getRightLoc(),
1311 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001312 break;
1313
1314 case ObjCMessageExpr::SuperClass:
1315 case ObjCMessageExpr::SuperInstance:
1316 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1317 OldMsg->getValueKind(),
1318 OldMsg->getLeftLoc(),
1319 OldMsg->getSuperLoc(),
1320 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1321 OldMsg->getSuperType(),
1322 OldMsg->getSelector(),
1323 SelLocs,
1324 OldMsg->getMethodDecl(),
1325 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001326 OldMsg->getRightLoc(),
1327 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001328 break;
1329 }
1330
1331 Stmt *Replacement = SynthMessageExpr(NewMsg);
1332 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1333 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001334}
1335
John McCall4b9c2d22011-11-06 09:01:30 +00001336Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1337 SourceRange OldRange = PseudoOp->getSourceRange();
1338
1339 // We just magically know some things about the structure of this
1340 // expression.
1341 ObjCMessageExpr *OldMsg =
1342 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1343
1344 // Because the rewriter doesn't allow us to rewrite rewritten code,
1345 // we need to suppress rewriting the sub-statements.
1346 Expr *Base = 0;
1347 {
1348 DisableReplaceStmtScope S(*this);
1349
1350 // Rebuild the base expression if we have one.
1351 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1352 Base = OldMsg->getInstanceReceiver();
1353 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1354 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001355 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001356 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001357
John McCall4b9c2d22011-11-06 09:01:30 +00001358 // Intentionally empty.
1359 SmallVector<SourceLocation, 1> SelLocs;
1360 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001361
Chad Rosier0774ba72012-01-06 20:05:14 +00001362 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001363 switch (OldMsg->getReceiverKind()) {
1364 case ObjCMessageExpr::Class:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 OldMsg->getClassReceiverTypeInfo(),
1369 OldMsg->getSelector(),
1370 SelLocs,
1371 OldMsg->getMethodDecl(),
1372 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001373 OldMsg->getRightLoc(),
1374 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001375 break;
1376
1377 case ObjCMessageExpr::Instance:
1378 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1379 OldMsg->getValueKind(),
1380 OldMsg->getLeftLoc(),
1381 Base,
1382 OldMsg->getSelector(),
1383 SelLocs,
1384 OldMsg->getMethodDecl(),
1385 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001386 OldMsg->getRightLoc(),
1387 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001388 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,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001402 OldMsg->getRightLoc(),
1403 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001404 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001405 }
John McCall4b9c2d22011-11-06 09:01:30 +00001406
1407 Stmt *Replacement = SynthMessageExpr(NewMsg);
1408 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1409 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001410}
1411
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412/// SynthCountByEnumWithState - To print:
1413/// ((unsigned int (*)
1414/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001415/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001417/// "countByEnumeratingWithState:objects:count:"),
1418/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001419/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420///
Steve Naroffb29b4272008-04-14 22:03:09 +00001421void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1423 "id *, unsigned int))(void *)objc_msgSend)";
1424 buf += "\n\t\t";
1425 buf += "((id)l_collection,\n\t\t";
1426 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1427 buf += "\n\t\t";
1428 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001429 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001430}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001431
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001432/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1433/// statement to exit to its outer synthesized loop.
1434///
Steve Naroffb29b4272008-04-14 22:03:09 +00001435Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1437 return S;
1438 // replace break with goto __break_label
1439 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001441 SourceLocation startLoc = S->getLocStart();
1442 buf = "goto __break_label_";
1443 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001444 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445
1446 return 0;
1447}
1448
1449/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1450/// statement to continue with its inner synthesized loop.
1451///
Steve Naroffb29b4272008-04-14 22:03:09 +00001452Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001453 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1454 return S;
1455 // replace continue with goto __continue_label
1456 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458 SourceLocation startLoc = S->getLocStart();
1459 buf = "goto __continue_label_";
1460 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001461 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001463 return 0;
1464}
1465
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001466/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001467/// It rewrites:
1468/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001470/// Into:
1471/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001472/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001474/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001475/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001477/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001478/// if (limit) {
1479/// unsigned long startMutations = *enumState.mutationsPtr;
1480/// do {
1481/// unsigned long counter = 0;
1482/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001483/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001484/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001485/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001486/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001488/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001489/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001490/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001492/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001493/// }
1494/// else
1495/// elem = nil;
1496/// }
1497///
Steve Naroffb29b4272008-04-14 22:03:09 +00001498Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001499 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001500 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001501 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001502 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001503 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001504 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001507 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001509 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 std::string buf;
1511 buf = "\n{\n\t";
1512 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1513 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001514 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001515 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001516 if (ElementType->isObjCQualifiedIdType() ||
1517 ElementType->isObjCQualifiedInterfaceType())
1518 // Simply use 'id' for all qualified types.
1519 elementTypeAsString = "id";
1520 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001521 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001522 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001524 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 buf += elementName;
1526 buf += ";\n\t";
1527 }
Chris Lattner06767512008-04-08 05:52:18 +00001528 else {
1529 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001530 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001531 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1532 if (VD->getType()->isObjCQualifiedIdType() ||
1533 VD->getType()->isObjCQualifiedInterfaceType())
1534 // Simply use 'id' for all qualified types.
1535 elementTypeAsString = "id";
1536 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001537 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001540 // struct __objcFastEnumerationState enumState = { 0 };
1541 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001542 // id __rw_items[16];
1543 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 // id l_collection = (id)
1545 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001546 // Find start location of 'collection' the hard way!
1547 const char *startCollectionBuf = startBuf;
1548 startCollectionBuf += 3; // skip 'for'
1549 startCollectionBuf = strchr(startCollectionBuf, '(');
1550 startCollectionBuf++; // skip '('
1551 // find 'in' and skip it.
1552 while (*startCollectionBuf != ' ' ||
1553 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1554 (*(startCollectionBuf+3) != ' ' &&
1555 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1556 startCollectionBuf++;
1557 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
1559 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001560 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001561 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001562 SourceLocation rightParenLoc = S->getRParenLoc();
1563 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001564 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001568 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 // ((unsigned int (*)
1572 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001575 // "countByEnumeratingWithState:objects:count:"),
1576 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001577 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578 buf += "unsigned long limit =\n\t\t";
1579 SynthCountByEnumWithState(buf);
1580 buf += ";\n\t";
1581 /// if (limit) {
1582 /// unsigned long startMutations = *enumState.mutationsPtr;
1583 /// do {
1584 /// unsigned long counter = 0;
1585 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001586 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001588 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 buf += "if (limit) {\n\t";
1590 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1591 buf += "do {\n\t\t";
1592 buf += "unsigned long counter = 0;\n\t\t";
1593 buf += "do {\n\t\t\t";
1594 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1595 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1596 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001597 buf += " = (";
1598 buf += elementTypeAsString;
1599 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001601 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001603 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001605 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001606 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 /// }
1610 /// else
1611 /// elem = nil;
1612 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001613 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001614 buf = ";\n\t";
1615 buf += "__continue_label_";
1616 buf += utostr(ObjCBcLabelNo.back());
1617 buf += ": ;";
1618 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 buf += "} while (counter < limit);\n\t";
1620 buf += "} while (limit = ";
1621 SynthCountByEnumWithState(buf);
1622 buf += ");\n\t";
1623 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001624 buf += " = ((";
1625 buf += elementTypeAsString;
1626 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001627 buf += "__break_label_";
1628 buf += utostr(ObjCBcLabelNo.back());
1629 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630 buf += "}\n\t";
1631 buf += "else\n\t\t";
1632 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001633 buf += " = ((";
1634 buf += elementTypeAsString;
1635 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001636 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001638 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001639 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001640 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001641 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001642 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001643 } else {
1644 /* Need to treat single statements specially. For example:
1645 *
1646 * for (A *a in b) if (stuff()) break;
1647 * for (A *a in b) xxxyy;
1648 *
1649 * The following code simply scans ahead to the semi to find the actual end.
1650 */
1651 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1652 const char *semiBuf = strchr(stmtBuf, ';');
1653 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001654 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001655 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001656 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001657 Stmts.pop_back();
1658 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001659 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001660}
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001663/// This routine rewrites @synchronized(expr) stmt;
1664/// into:
1665/// objc_sync_enter(expr);
1666/// @try stmt @finally { objc_sync_exit(expr); }
1667///
Steve Naroffb29b4272008-04-14 22:03:09 +00001668Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001669 // Get the start location and compute the semi location.
1670 SourceLocation startLoc = S->getLocStart();
1671 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001673 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001674
1675 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001676 buf = "objc_sync_enter((id)";
1677 const char *lparenBuf = startBuf;
1678 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001679 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001680 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1681 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001682 // been rewritten! (which implies the SourceLocation's are invalid).
1683 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001684 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001685 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001686 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001687 buf = ");\n";
1688 // declare a new scope with two variables, _stack and _rethrow.
1689 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1690 buf += "int buf[18/*32-bit i386*/];\n";
1691 buf += "char *pointers[4];} _stack;\n";
1692 buf += "id volatile _rethrow = 0;\n";
1693 buf += "objc_exception_try_enter(&_stack);\n";
1694 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001695 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001696 startLoc = S->getSynchBody()->getLocEnd();
1697 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Steve Naroffc7089f12008-08-19 13:04:19 +00001699 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 SourceLocation lastCurlyLoc = startLoc;
1701 buf = "}\nelse {\n";
1702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001703 buf += "}\n";
1704 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001705 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001706
1707 std::string syncBuf;
1708 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001709
1710 Expr *syncExpr = S->getSynchExpr();
1711 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1712 ? CK_BitCast :
1713 syncExpr->getType()->isBlockPointerType()
1714 ? CK_BlockPointerToObjCPointerCast
1715 : CK_CPointerToObjCPointerCast;
1716 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1717 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001718 std::string syncExprBufS;
1719 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001720 syncExpr->printPretty(syncExprBuf, *Context, 0,
1721 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001722 syncBuf += syncExprBuf.str();
1723 syncBuf += ");";
1724
1725 buf += syncBuf;
1726 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001727 buf += "}\n";
1728 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Benjamin Kramerd999b372010-02-14 14:14:16 +00001730 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001731
1732 bool hasReturns = false;
1733 HasReturnStmts(S->getSynchBody(), hasReturns);
1734 if (hasReturns)
1735 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1736
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001737 return 0;
1738}
1739
Steve Naroffb85e77a2009-12-05 21:43:12 +00001740void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1741{
Steve Naroff8c565152008-12-05 17:03:39 +00001742 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001743 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001744 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001745 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001746
Steve Naroffb85e77a2009-12-05 21:43:12 +00001747 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001749 TryFinallyContainsReturnDiag);
1750 }
1751 return;
1752}
1753
Steve Naroffb85e77a2009-12-05 21:43:12 +00001754void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1755{
1756 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001757 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001758 if (*CI)
1759 HasReturnStmts(*CI, hasReturns);
1760
1761 if (isa<ReturnStmt>(S))
1762 hasReturns = true;
1763 return;
1764}
1765
1766void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1767 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001768 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001769 if (*CI) {
1770 RewriteTryReturnStmts(*CI);
1771 }
1772 if (isa<ReturnStmt>(S)) {
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
1775
1776 const char *semiBuf = strchr(startBuf, ';');
1777 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001778 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001779
1780 std::string buf;
1781 buf = "{ objc_exception_try_exit(&_stack); return";
1782
Benjamin Kramerd999b372010-02-14 14:14:16 +00001783 ReplaceText(startLoc, 6, buf);
1784 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001785 }
1786 return;
1787}
1788
1789void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1790 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001791 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001792 if (*CI) {
1793 RewriteSyncReturnStmts(*CI, syncExitBuf);
1794 }
1795 if (isa<ReturnStmt>(S)) {
1796 SourceLocation startLoc = S->getLocStart();
1797 const char *startBuf = SM->getCharacterData(startLoc);
1798
1799 const char *semiBuf = strchr(startBuf, ';');
1800 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001801 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001802
1803 std::string buf;
1804 buf = "{ objc_exception_try_exit(&_stack);";
1805 buf += syncExitBuf;
1806 buf += " return";
1807
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(startLoc, 6, buf);
1809 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001810 }
1811 return;
1812}
1813
Steve Naroffb29b4272008-04-14 22:03:09 +00001814Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001815 // Get the start location and compute the semi location.
1816 SourceLocation startLoc = S->getLocStart();
1817 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Steve Naroff75730982007-11-07 04:08:17 +00001819 assert((*startBuf == '@') && "bogus @try location");
1820
1821 std::string buf;
1822 // declare a new scope with two variables, _stack and _rethrow.
1823 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1824 buf += "int buf[18/*32-bit i386*/];\n";
1825 buf += "char *pointers[4];} _stack;\n";
1826 buf += "id volatile _rethrow = 0;\n";
1827 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001828 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001829
Benjamin Kramerd999b372010-02-14 14:14:16 +00001830 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Steve Naroff75730982007-11-07 04:08:17 +00001832 startLoc = S->getTryBody()->getLocEnd();
1833 startBuf = SM->getCharacterData(startLoc);
1834
1835 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Steve Naroff75730982007-11-07 04:08:17 +00001837 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001838 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001839 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001840 buf = " /* @catch begin */ else {\n";
1841 buf += " id _caught = objc_exception_extract(&_stack);\n";
1842 buf += " objc_exception_try_enter (&_stack);\n";
1843 buf += " if (_setjmp(_stack.buf))\n";
1844 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1845 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Benjamin Kramerd999b372010-02-14 14:14:16 +00001847 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001848 } else { /* no catch list */
1849 buf = "}\nelse {\n";
1850 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1851 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001852 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001853 }
Steve Naroff75730982007-11-07 04:08:17 +00001854 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001855 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1856 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001857 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001858
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001859 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001860 buf = "if ("; // we are generating code for the first catch clause
1861 else
1862 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001863 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001864 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Steve Naroff75730982007-11-07 04:08:17 +00001866 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Steve Naroff75730982007-11-07 04:08:17 +00001868 const char *lParenLoc = strchr(startBuf, '(');
1869
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001870 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001871 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001872 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001873 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1874 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001875 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001876 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001877 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Steve Naroffe12e6922008-02-01 20:02:07 +00001879 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001880 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001881 } else if (catchDecl) {
1882 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001883 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001884 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001885 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001886 } else if (const ObjCObjectPointerType *Ptr =
1887 t->getAs<ObjCObjectPointerType>()) {
1888 // Should be a pointer to a class.
1889 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1890 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001891 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001892 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001893 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001894 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001895 }
1896 }
1897 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001898 lastCatchBody = Catch->getCatchBody();
1899 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001900 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1901 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1902 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1903 assert((*rParenBuf == ')') && "bogus @catch paren location");
1904 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Mike Stump1eb44332009-09-09 15:08:12 +00001906 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001907 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001908 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001909 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001910 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001911 }
Steve Naroff75730982007-11-07 04:08:17 +00001912 }
1913 // Complete the catch list...
1914 if (lastCatchBody) {
1915 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001916 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1917 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff378f47a2008-09-11 15:29:03 +00001919 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001920 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001921 buf = "} /* last catch end */\n";
1922 buf += "else {\n";
1923 buf += " _rethrow = _caught;\n";
1924 buf += " objc_exception_try_exit(&_stack);\n";
1925 buf += "} } /* @catch end */\n";
1926 if (!S->getFinallyStmt())
1927 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001928 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Steve Naroff75730982007-11-07 04:08:17 +00001930 // Set lastCurlyLoc
1931 lastCurlyLoc = lastCatchBody->getLocEnd();
1932 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001934 startLoc = finalStmt->getLocStart();
1935 startBuf = SM->getCharacterData(startLoc);
1936 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Steve Naroff75730982007-11-07 04:08:17 +00001940 Stmt *body = finalStmt->getFinallyBody();
1941 SourceLocation startLoc = body->getLocStart();
1942 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001943 assert(*SM->getCharacterData(startLoc) == '{' &&
1944 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001945 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001946 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001948 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001949 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001950 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001951 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Steve Naroff75730982007-11-07 04:08:17 +00001953 // Set lastCurlyLoc
1954 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff8c565152008-12-05 17:03:39 +00001956 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001957 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001958 } else { /* no finally clause - make sure we synthesize an implicit one */
1959 buf = "{ /* implicit finally clause */\n";
1960 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1961 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1962 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001963 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001964
1965 // Now check for any return/continue/go statements within the @try.
1966 // The implicit finally clause won't called if the @try contains any
1967 // jump statements.
1968 bool hasReturns = false;
1969 HasReturnStmts(S->getTryBody(), hasReturns);
1970 if (hasReturns)
1971 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001972 }
1973 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001974 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001975 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001976 return 0;
1977}
1978
Mike Stump1eb44332009-09-09 15:08:12 +00001979// This can't be done with ReplaceStmt(S, ThrowExpr), since
1980// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001981// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001983 // Get the start location and compute the semi location.
1984 SourceLocation startLoc = S->getLocStart();
1985 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff2bd03922007-11-07 15:32:26 +00001987 assert((*startBuf == '@') && "bogus @throw location");
1988
1989 std::string buf;
1990 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001991 if (S->getThrowExpr())
1992 buf = "objc_exception_throw(";
1993 else // add an implicit argument
1994 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001996 // handle "@ throw" correctly.
1997 const char *wBuf = strchr(startBuf, 'w');
1998 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001999 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Steve Naroff2bd03922007-11-07 15:32:26 +00002001 const char *semiBuf = strchr(startBuf, ';');
2002 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002003 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002005 return 0;
2006}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002007
Steve Naroffb29b4272008-04-14 22:03:09 +00002008Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002009 // Create a new string expression.
2010 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002011 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002012 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002013 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002014 StringLiteral::Ascii, false,
2015 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002016 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Chris Lattner07506182007-11-30 22:53:43 +00002018 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002019 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002020 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002021}
2022
Steve Naroffb29b4272008-04-14 22:03:09 +00002023Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002024 if (!SelGetUidFunctionDecl)
2025 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002026 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2027 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002029 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002030 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002031 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002032 StringLiteral::Ascii, false,
2033 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002034 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2035 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002036 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002037 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002038 return SelExp;
2039}
2040
Steve Naroffb29b4272008-04-14 22:03:09 +00002041CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002042 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2043 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002044 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002045 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Steve Naroffebf2b562007-10-23 23:50:29 +00002047 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002048 DeclRefExpr *DRE =
2049 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroffebf2b562007-10-23 23:50:29 +00002051 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002052 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002053 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002054 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002055 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
John McCall183700f2009-09-21 23:43:11 +00002057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002059 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002060 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002061 FT->getCallResultType(*Context),
2062 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002063 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002064}
2065
Steve Naroffd5255f52007-11-01 13:24:47 +00002066static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2067 const char *&startRef, const char *&endRef) {
2068 while (startBuf < endBuf) {
2069 if (*startBuf == '<')
2070 startRef = startBuf; // mark the start.
2071 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002072 if (startRef && *startRef == '<') {
2073 endRef = startBuf; // mark the end.
2074 return true;
2075 }
2076 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002077 }
2078 startBuf++;
2079 }
2080 return false;
2081}
2082
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002083static void scanToNextArgument(const char *&argRef) {
2084 int angle = 0;
2085 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2086 if (*argRef == '<')
2087 angle++;
2088 else if (*argRef == '>')
2089 angle--;
2090 argRef++;
2091 }
2092 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2093}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002094
Steve Naroffb29b4272008-04-14 22:03:09 +00002095bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002096 if (T->isObjCQualifiedIdType())
2097 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002098 if (const PointerType *PT = T->getAs<PointerType>()) {
2099 if (PT->getPointeeType()->isObjCQualifiedIdType())
2100 return true;
2101 }
2102 if (T->isObjCObjectPointerType()) {
2103 T = T->getPointeeType();
2104 return T->isObjCQualifiedInterfaceType();
2105 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002106 if (T->isArrayType()) {
2107 QualType ElemTy = Context->getBaseElementType(T);
2108 return needToScanForQualifiers(ElemTy);
2109 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002110 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002111}
2112
Steve Naroff4f95b752008-07-29 18:15:38 +00002113void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2114 QualType Type = E->getType();
2115 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Steve Naroffcda658e2008-11-19 21:15:47 +00002118 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2119 Loc = ECE->getLParenLoc();
2120 EndLoc = ECE->getRParenLoc();
2121 } else {
2122 Loc = E->getLocStart();
2123 EndLoc = E->getLocEnd();
2124 }
2125 // This will defend against trying to rewrite synthesized expressions.
2126 if (Loc.isInvalid() || EndLoc.isInvalid())
2127 return;
2128
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002130 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 const char *startRef = 0, *endRef = 0;
2132 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2133 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002134 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2135 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002136 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002137 InsertText(LessLoc, "/*");
2138 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002139 }
2140 }
2141}
2142
Steve Naroffb29b4272008-04-14 22:03:09 +00002143void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002144 SourceLocation Loc;
2145 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002146 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002147 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2148 Loc = VD->getLocation();
2149 Type = VD->getType();
2150 }
2151 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2152 Loc = FD->getLocation();
2153 // Check for ObjC 'id' and class types that have been adorned with protocol
2154 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002155 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002157 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 if (!proto)
2159 return;
2160 Type = proto->getResultType();
2161 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002162 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2163 Loc = FD->getLocation();
2164 Type = FD->getType();
2165 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002166 else
2167 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002169 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Steve Naroffd5255f52007-11-01 13:24:47 +00002172 const char *endBuf = SM->getCharacterData(Loc);
2173 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002174 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 startBuf--; // scan backward (from the decl location) for return type.
2176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002179 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2180 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002181 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002184 }
2185 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002186 if (!proto)
2187 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002188 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 const char *startBuf = SM->getCharacterData(Loc);
2190 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002191 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2192 if (needToScanForQualifiers(proto->getArgType(i))) {
2193 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffd5255f52007-11-01 13:24:47 +00002195 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002196 // scan forward (from the decl location) for argument types.
2197 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002198 const char *startRef = 0, *endRef = 0;
2199 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2200 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002202 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002203 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002204 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002205 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002206 InsertText(LessLoc, "/*");
2207 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002209 startBuf = ++endBuf;
2210 }
2211 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002212 // If the function name is derived from a macro expansion, then the
2213 // argument buffer will not follow the name. Need to speak with Chris.
2214 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002215 startBuf++; // scan forward (from the decl location) for argument types.
2216 startBuf++;
2217 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002218 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002219}
2220
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002221void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2222 QualType QT = ND->getType();
2223 const Type* TypePtr = QT->getAs<Type>();
2224 if (!isa<TypeOfExprType>(TypePtr))
2225 return;
2226 while (isa<TypeOfExprType>(TypePtr)) {
2227 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2228 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2229 TypePtr = QT->getAs<Type>();
2230 }
2231 // FIXME. This will not work for multiple declarators; as in:
2232 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002233 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002234 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2235 const char *startBuf = SM->getCharacterData(DeclLoc);
2236 if (ND->getInit()) {
2237 std::string Name(ND->getNameAsString());
2238 TypeAsString += " " + Name + " = ";
2239 Expr *E = ND->getInit();
2240 SourceLocation startLoc;
2241 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2242 startLoc = ECE->getLParenLoc();
2243 else
2244 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002245 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002247 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002248 }
2249 else {
2250 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002251 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002254 }
2255}
2256
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002258void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002259 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002260 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002261 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002262 QualType getFuncType =
2263 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002264 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002265 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002266 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002267 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002268 SC_Extern,
2269 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002270}
2271
Steve Naroffb29b4272008-04-14 22:03:09 +00002272void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002273 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002274 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002275 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002277 return;
2278 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002280}
2281
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002282void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002283 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002284 const char *argPtr = TypeString.c_str();
2285 if (!strchr(argPtr, '^')) {
2286 Str += TypeString;
2287 return;
2288 }
2289 while (*argPtr) {
2290 Str += (*argPtr == '^' ? '*' : *argPtr);
2291 argPtr++;
2292 }
2293}
2294
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002295// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002296void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2297 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002299 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002300 const char *argPtr = TypeString.c_str();
2301 int paren = 0;
2302 while (*argPtr) {
2303 switch (*argPtr) {
2304 case '(':
2305 Str += *argPtr;
2306 paren++;
2307 break;
2308 case ')':
2309 Str += *argPtr;
2310 paren--;
2311 break;
2312 case '^':
2313 Str += '*';
2314 if (paren == 1)
2315 Str += VD->getNameAsString();
2316 break;
2317 default:
2318 Str += *argPtr;
2319 break;
2320 }
2321 argPtr++;
2322 }
2323}
2324
2325
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002326void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2327 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2328 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2329 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2330 if (!proto)
2331 return;
2332 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002333 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002334 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002335 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002336 FdStr += "(";
2337 unsigned numArgs = proto->getNumArgs();
2338 for (unsigned i = 0; i < numArgs; i++) {
2339 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002340 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002341 if (i+1 < numArgs)
2342 FdStr += ", ";
2343 }
2344 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002345 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002346 CurFunctionDeclToDeclareForBlock = 0;
2347}
2348
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002350void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351 if (SuperContructorFunctionDecl)
2352 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002353 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002354 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002355 QualType argT = Context->getObjCIdType();
2356 assert(!argT.isNull() && "Can't find 'id' type");
2357 ArgTys.push_back(argT);
2358 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002359 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002361 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002362 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002363 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002364 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002365 SC_Extern,
2366 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002367}
2368
Steve Naroff09b266e2007-10-30 23:14:51 +00002369// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002370void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002372 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002373 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002379 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002382 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002383 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002384 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002385 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002386 SC_Extern,
2387 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002388}
2389
Steve Naroff874e2322007-11-15 10:28:18 +00002390// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002391void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002392 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002393 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002394 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002395 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002396 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002397 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2398 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2399 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002401 assert(!argT.isNull() && "Can't find 'SEL' type");
2402 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002403 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2404 &ArgTys[0], ArgTys.size(),
2405 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002406 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002407 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002408 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002409 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002410 SC_Extern,
2411 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002412}
2413
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002414// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002415void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002417 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002418 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002424 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002425 &ArgTys[0], ArgTys.size(),
2426 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002427 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002428 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002429 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002430 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002431 SC_Extern,
2432 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002433}
2434
Mike Stump1eb44332009-09-09 15:08:12 +00002435// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002436// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002437void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002438 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002439 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002441 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002442 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002443 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2445 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2446 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002447 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002448 assert(!argT.isNull() && "Can't find 'SEL' type");
2449 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002450 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002451 &ArgTys[0], ArgTys.size(),
2452 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002453 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002454 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002455 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002456 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002457 SC_Extern,
2458 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002459}
2460
Steve Naroff1284db82008-05-08 22:02:18 +00002461// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002462void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002463 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002466 assert(!argT.isNull() && "Can't find 'id' type");
2467 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002469 assert(!argT.isNull() && "Can't find 'SEL' type");
2470 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002471 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2472 &ArgTys[0], ArgTys.size(),
2473 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002474 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002475 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002476 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002477 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002478 SC_Extern,
2479 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002480}
2481
Steve Naroff09b266e2007-10-30 23:14:51 +00002482// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002483void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002484 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002486 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002487 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2488 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002489 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002490 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002491 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002492 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002493 SC_Extern,
2494 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002495}
2496
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002497// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2498void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2499 IdentifierInfo *getSuperClassIdent =
2500 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002501 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002502 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002503 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2504 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002505 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002506 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002507 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002508 getSuperClassIdent,
2509 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002512 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002513}
2514
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002515// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002516void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002517 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002518 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002519 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002520 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2521 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002522 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002524 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002525 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002526 SC_Extern,
2527 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002528}
2529
Steve Naroffb29b4272008-04-14 22:03:09 +00002530Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002531 QualType strType = getConstantStringStructType();
2532
2533 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002534
2535 std::string tmpName = InFileName;
2536 unsigned i;
2537 for (i=0; i < tmpName.length(); i++) {
2538 char c = tmpName.at(i);
2539 // replace any non alphanumeric characters with '_'.
2540 if (!isalpha(c) && (c < '0' || c > '9'))
2541 tmpName[i] = '_';
2542 }
2543 S += tmpName;
2544 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002545 S += utostr(NumObjCStringLiterals++);
2546
Steve Naroffba92b2e2008-03-27 22:29:16 +00002547 Preamble += "static __NSConstantStringImpl " + S;
2548 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2549 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002550 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002551 std::string prettyBufS;
2552 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002553 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2554 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002555 Preamble += prettyBuf.str();
2556 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002557 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002558
2559 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002560 SourceLocation(), &Context->Idents.get(S),
2561 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002562 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2563 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002564 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002565 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002566 VK_RValue, OK_Ordinary,
2567 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002568 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002569 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002570 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002571 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002572 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002573 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002574}
2575
Steve Naroff874e2322007-11-15 10:28:18 +00002576// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002577QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002578 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002579 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002580 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002581 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002582 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Steve Naroff874e2322007-11-15 10:28:18 +00002584 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002586 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002587 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002588
Steve Naroff874e2322007-11-15 10:28:18 +00002589 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002590 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002592 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002593 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002594 FieldTypes[i], 0,
2595 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002596 /*Mutable=*/false,
2597 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Douglas Gregor838db382010-02-11 01:19:42 +00002600 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002601 }
2602 return Context->getTagDeclType(SuperStructDecl);
2603}
2604
Steve Naroffb29b4272008-04-14 22:03:09 +00002605QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002606 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002607 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002608 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002609 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002613 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002614 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002615 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002618 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002619 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002620
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002621 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002622 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002623 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2624 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002625 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002626 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002627 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002628 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002629 /*Mutable=*/true,
2630 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 }
2632
Douglas Gregor838db382010-02-11 01:19:42 +00002633 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002634 }
2635 return Context->getTagDeclType(ConstantStringDecl);
2636}
2637
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002638Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2639 SourceLocation StartLoc,
2640 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002641 if (!SelGetUidFunctionDecl)
2642 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002643 if (!MsgSendFunctionDecl)
2644 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002645 if (!MsgSendSuperFunctionDecl)
2646 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002647 if (!MsgSendStretFunctionDecl)
2648 SynthMsgSendStretFunctionDecl();
2649 if (!MsgSendSuperStretFunctionDecl)
2650 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002651 if (!MsgSendFpretFunctionDecl)
2652 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002653 if (!GetClassFunctionDecl)
2654 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002655 if (!GetSuperClassFunctionDecl)
2656 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002657 if (!GetMetaClassFunctionDecl)
2658 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Steve Naroff874e2322007-11-15 10:28:18 +00002660 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002661 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2662 // May need to use objc_msgSend_stret() as well.
2663 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002664 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2665 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002666 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002667 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002668 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002669 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002670 }
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Steve Naroff934f2762007-10-24 22:48:43 +00002672 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002674 switch (Exp->getReceiverKind()) {
2675 case ObjCMessageExpr::SuperClass: {
2676 MsgSendFlavor = MsgSendSuperFunctionDecl;
2677 if (MsgSendStretFlavor)
2678 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2679 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Douglas Gregor04badcf2010-04-21 00:45:42 +00002681 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Chris Lattner5f9e2722011-07-23 10:55:15 +00002683 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002684
Douglas Gregor04badcf2010-04-21 00:45:42 +00002685 // set the receiver to self, the first argument to all methods.
2686 InitExprs.push_back(
2687 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002688 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002689 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002690 Context->getObjCIdType(),
2691 VK_RValue,
2692 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002693 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002694
Douglas Gregor04badcf2010-04-21 00:45:42 +00002695 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002696 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002697 QualType argType = Context->getPointerType(Context->CharTy);
2698 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002699 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002700 StringLiteral::Ascii, false,
2701 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002702 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2703 &ClsExprs[0],
2704 ClsExprs.size(),
2705 StartLoc,
2706 EndLoc);
2707 // (Class)objc_getClass("CurrentClass")
2708 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2709 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002710 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002711 ClsExprs.clear();
2712 ClsExprs.push_back(ArgExpr);
2713 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2714 &ClsExprs[0], ClsExprs.size(),
2715 StartLoc, EndLoc);
2716
2717 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2718 // To turn off a warning, type-cast to 'id'
2719 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2720 NoTypeInfoCStyleCastExpr(Context,
2721 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002722 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002723 // struct objc_super
2724 QualType superType = getSuperStructType();
2725 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002726
Francois Pichet62ec1f22011-09-17 17:15:52 +00002727 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002728 SynthSuperContructorFunctionDecl();
2729 // Simulate a contructor call...
2730 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002731 superType, VK_LValue,
2732 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2734 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002735 superType, VK_LValue,
2736 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002737 // The code for super is a little tricky to prevent collision with
2738 // the structure definition in the header. The rewriter has it's own
2739 // internal definition (__rw_objc_super) that is uses. This is why
2740 // we need the cast below. For example:
2741 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2742 //
John McCall2de56d12010-08-25 11:45:40 +00002743 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002744 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002745 VK_RValue, OK_Ordinary,
2746 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002747 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2748 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002749 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002750 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002751 // (struct objc_super) { <exprs from above> }
2752 InitListExpr *ILE =
2753 new (Context) InitListExpr(*Context, SourceLocation(),
2754 &InitExprs[0], InitExprs.size(),
2755 SourceLocation());
2756 TypeSourceInfo *superTInfo
2757 = Context->getTrivialTypeSourceInfo(superType);
2758 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002759 superType, VK_LValue,
2760 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002761 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002762 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002763 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002764 VK_RValue, OK_Ordinary,
2765 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002766 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002767 MsgExprs.push_back(SuperRep);
2768 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002769 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002770
2771 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002772 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002773 QualType argType = Context->getPointerType(Context->CharTy);
2774 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002775 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776 IdentifierInfo *clsName = Class->getIdentifier();
2777 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002778 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002779 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002780 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002781 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2782 &ClsExprs[0],
2783 ClsExprs.size(),
2784 StartLoc, EndLoc);
2785 MsgExprs.push_back(Cls);
2786 break;
2787 }
2788
2789 case ObjCMessageExpr::SuperInstance:{
2790 MsgSendFlavor = MsgSendSuperFunctionDecl;
2791 if (MsgSendStretFlavor)
2792 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2793 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2794 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002795 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002796
2797 InitExprs.push_back(
2798 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002799 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002801 Context->getObjCIdType(),
2802 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002803 ); // set the 'receiver'.
2804
2805 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002806 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002807 QualType argType = Context->getPointerType(Context->CharTy);
2808 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002809 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002810 StringLiteral::Ascii, false, argType,
2811 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2813 &ClsExprs[0],
2814 ClsExprs.size(),
2815 StartLoc, EndLoc);
2816 // (Class)objc_getClass("CurrentClass")
2817 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2818 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002819 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 ClsExprs.clear();
2821 ClsExprs.push_back(ArgExpr);
2822 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2823 &ClsExprs[0], ClsExprs.size(),
2824 StartLoc, EndLoc);
2825
2826 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2827 // To turn off a warning, type-cast to 'id'
2828 InitExprs.push_back(
2829 // set 'super class', using class_getSuperclass().
2830 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002831 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 // struct objc_super
2833 QualType superType = getSuperStructType();
2834 Expr *SuperRep;
2835
Francois Pichet62ec1f22011-09-17 17:15:52 +00002836 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 SynthSuperContructorFunctionDecl();
2838 // Simulate a contructor call...
2839 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002840 superType, VK_LValue,
2841 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2843 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002844 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 // The code for super is a little tricky to prevent collision with
2846 // the structure definition in the header. The rewriter has it's own
2847 // internal definition (__rw_objc_super) that is uses. This is why
2848 // we need the cast below. For example:
2849 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2850 //
John McCall2de56d12010-08-25 11:45:40 +00002851 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002853 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 SourceLocation());
2855 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2856 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002857 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 } else {
2859 // (struct objc_super) { <exprs from above> }
2860 InitListExpr *ILE =
2861 new (Context) InitListExpr(*Context, SourceLocation(),
2862 &InitExprs[0], InitExprs.size(),
2863 SourceLocation());
2864 TypeSourceInfo *superTInfo
2865 = Context->getTrivialTypeSourceInfo(superType);
2866 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002867 superType, VK_RValue, ILE,
2868 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002869 }
2870 MsgExprs.push_back(SuperRep);
2871 break;
2872 }
2873
2874 case ObjCMessageExpr::Instance: {
2875 // Remove all type-casts because it may contain objc-style types; e.g.
2876 // Foo<Proto> *.
2877 Expr *recExpr = Exp->getInstanceReceiver();
2878 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2879 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002880 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2881 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2882 ? CK_BlockPointerToObjCPointerCast
2883 : CK_CPointerToObjCPointerCast;
2884
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002886 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002887 MsgExprs.push_back(recExpr);
2888 break;
2889 }
2890 }
2891
Steve Naroffbeaf2992007-11-03 11:27:19 +00002892 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002893 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002894 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002895 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002896 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002897 StringLiteral::Ascii, false,
2898 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002899 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002900 &SelExprs[0], SelExprs.size(),
2901 StartLoc,
2902 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002903 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Steve Naroff934f2762007-10-24 22:48:43 +00002905 // Now push any user supplied arguments.
2906 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002907 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002908 // Make all implicit casts explicit...ICE comes in handy:-)
2909 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2910 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002911 QualType type = ICE->getType();
2912 if (needToScanForQualifiers(type))
2913 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002914 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002915 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002916 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002917 CastKind CK;
2918 if (SubExpr->getType()->isIntegralType(*Context) &&
2919 type->isBooleanType()) {
2920 CK = CK_IntegralToBoolean;
2921 } else if (type->isObjCObjectPointerType()) {
2922 if (SubExpr->getType()->isBlockPointerType()) {
2923 CK = CK_BlockPointerToObjCPointerCast;
2924 } else if (SubExpr->getType()->isPointerType()) {
2925 CK = CK_CPointerToObjCPointerCast;
2926 } else {
2927 CK = CK_BitCast;
2928 }
2929 } else {
2930 CK = CK_BitCast;
2931 }
2932
2933 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002934 }
2935 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002936 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002937 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002938 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002939 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002940 CastKind CK;
2941 if (userExpr->getType()->isIntegralType(*Context)) {
2942 CK = CK_IntegralToPointer;
2943 } else if (userExpr->getType()->isBlockPointerType()) {
2944 CK = CK_BlockPointerToObjCPointerCast;
2945 } else if (userExpr->getType()->isPointerType()) {
2946 CK = CK_CPointerToObjCPointerCast;
2947 } else {
2948 CK = CK_BitCast;
2949 }
John McCall9d125032010-01-15 18:39:57 +00002950 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002951 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002952 }
Mike Stump1eb44332009-09-09 15:08:12 +00002953 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002954 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002955 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2956 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002957 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002958 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002959 }
Steve Naroffab972d32007-11-04 22:37:50 +00002960 // Generate the funky cast.
2961 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002962 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002963 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Steve Naroffab972d32007-11-04 22:37:50 +00002965 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002966 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2967 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2968 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002969 ArgTypes.push_back(Context->getObjCIdType());
2970 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002971 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002972 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002973 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2974 E = OMD->param_end(); PI != E; ++PI) {
2975 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002976 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002977 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002978 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002979 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002980 ArgTypes.push_back(t);
2981 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002982 returnType = Exp->getType();
2983 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002984 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002985 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002986 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002987 }
2988 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002989 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Steve Naroffab972d32007-11-04 22:37:50 +00002991 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002992 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002993 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002994
Mike Stump1eb44332009-09-09 15:08:12 +00002995 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002996 // If we don't do this cast, we get the following bizarre warning/note:
2997 // xx.m:13: warning: function called through a non-compatible type
2998 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002999 cast = NoTypeInfoCStyleCastExpr(Context,
3000 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003001 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroffab972d32007-11-04 22:37:50 +00003003 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003004 QualType castType =
3005 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3006 // If we don't have a method decl, force a variadic cast.
3007 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003008 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003009 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003010 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003011
3012 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003013 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003014
John McCall183700f2009-09-21 23:43:11 +00003015 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003016 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003017 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003018 FT->getResultType(), VK_RValue,
3019 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003020 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003021 if (MsgSendStretFlavor) {
3022 // We have the method which returns a struct/union. Must also generate
3023 // call to objc_msgSend_stret and hang both varieties on a conditional
3024 // expression which dictate which one to envoke depending on size of
3025 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003027 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003028 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003029 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003030 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003031 cast = NoTypeInfoCStyleCastExpr(Context,
3032 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003033 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003034 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003035 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3036 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003037 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003038 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003039 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003041 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003042 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003043
John McCall183700f2009-09-21 23:43:11 +00003044 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003045 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003046 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003047 FT->getResultType(), VK_RValue,
3048 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003050 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003051 UnaryExprOrTypeTraitExpr *sizeofExpr =
3052 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3053 Context->getTrivialTypeSourceInfo(returnType),
3054 Context->getSizeType(), SourceLocation(),
3055 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003056 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3057 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3058 // For X86 it is more complicated and some kind of target specific routine
3059 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003060 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003061 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003062 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3063 llvm::APInt(IntSize, 8),
3064 Context->IntTy,
3065 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003066 BinaryOperator *lessThanExpr =
3067 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3068 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003069 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003070 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003071 new (Context) ConditionalOperator(lessThanExpr,
3072 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003073 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003074 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003075 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3076 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003077 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003078 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003079 return ReplacingStmt;
3080}
3081
Steve Naroffb29b4272008-04-14 22:03:09 +00003082Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003083 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3084 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003085
Steve Naroff934f2762007-10-24 22:48:43 +00003086 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003087 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003089 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003090 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003091}
3092
Steve Naroff621edce2009-04-29 16:37:50 +00003093// typedef struct objc_object Protocol;
3094QualType RewriteObjC::getProtocolType() {
3095 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003096 TypeSourceInfo *TInfo
3097 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003098 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003099 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003100 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003101 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003102 }
3103 return Context->getTypeDeclType(ProtocolTypeDecl);
3104}
3105
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003106/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003107/// a synthesized/forward data reference (to the protocol's metadata).
3108/// The forward references (and metadata) are generated in
3109/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003110Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003111 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3112 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003113 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003114 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003115 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003116 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3117 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003118 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003119 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003120 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003121 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003122 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003123 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003124 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003125 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003126 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003127 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003129}
3130
Mike Stump1eb44332009-09-09 15:08:12 +00003131bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003132 const char *endBuf) {
3133 while (startBuf < endBuf) {
3134 if (*startBuf == '#') {
3135 // Skip whitespace.
3136 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3137 ;
3138 if (!strncmp(startBuf, "if", strlen("if")) ||
3139 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3140 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3141 !strncmp(startBuf, "define", strlen("define")) ||
3142 !strncmp(startBuf, "undef", strlen("undef")) ||
3143 !strncmp(startBuf, "else", strlen("else")) ||
3144 !strncmp(startBuf, "elif", strlen("elif")) ||
3145 !strncmp(startBuf, "endif", strlen("endif")) ||
3146 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3147 !strncmp(startBuf, "include", strlen("include")) ||
3148 !strncmp(startBuf, "import", strlen("import")) ||
3149 !strncmp(startBuf, "include_next", strlen("include_next")))
3150 return true;
3151 }
3152 startBuf++;
3153 }
3154 return false;
3155}
3156
Fariborz Jahanian58457172011-12-05 18:43:13 +00003157/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003158/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003159void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003160 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003161 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003162 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003163 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003164 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003165 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003166 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003167 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003168 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003169 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003170 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Steve Narofffea763e82007-11-14 19:25:57 +00003172 const char *startBuf = SM->getCharacterData(LocStart);
3173 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003174
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003175 // If no ivars and no root or if its root, directly or indirectly,
3176 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003177 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003178 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003179 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003180 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003181 return;
3182 }
Mike Stump1eb44332009-09-09 15:08:12 +00003183
3184 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003185 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003186 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003187 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003188 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003189 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003190
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003191 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003192 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003193 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003194 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003195 // If the buffer contains preprocessor directives, we do more fine-grained
3196 // rewrites. This is intended to fix code that looks like (which occurs in
3197 // NSURL.h, for example):
3198 //
3199 // #ifdef XYZ
3200 // @interface Foo : NSObject
3201 // #else
3202 // @interface FooBar : NSObject
3203 // #endif
3204 // {
3205 // int i;
3206 // }
3207 // @end
3208 //
3209 // This clause is segregated to avoid breaking the common case.
3210 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003211 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003212 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003213 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003214 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003215
Chris Lattnercafeb352009-02-20 18:18:36 +00003216 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003217 // advance to the end of the referenced protocols.
3218 while (endHeader < cursor && *endHeader != '>') endHeader++;
3219 endHeader++;
3220 }
3221 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003222 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003223 } else {
3224 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003225 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003226 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003227 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003228 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003229 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003230 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003231 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003232 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Steve Narofffea763e82007-11-14 19:25:57 +00003234 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003235 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003236 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003237 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003238 }
3239 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Steve Narofffea763e82007-11-14 19:25:57 +00003241 // Now comment out any visibility specifiers.
3242 while (cursor < endBuf) {
3243 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003244 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003245 // Skip whitespace.
3246 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3247 /*scan*/;
3248
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003249 // FIXME: presence of @public, etc. inside comment results in
3250 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003251 if (!strncmp(cursor, "public", strlen("public")) ||
3252 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003253 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003254 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003255 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003256 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003257 // FIXME: If there are cases where '<' is used in ivar declaration part
3258 // of user code, then scan the ivar list and use needToScanForQualifiers
3259 // for type checking.
3260 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003261 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003262 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003263 cursor = strchr(cursor, '>');
3264 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003265 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003266 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003267 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003268 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003269 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003270 }
Steve Narofffea763e82007-11-14 19:25:57 +00003271 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003272 }
Steve Narofffea763e82007-11-14 19:25:57 +00003273 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003274 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003275 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003276 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003277 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003278 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003279 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003280 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003281 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003282 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003283 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003284 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003285 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003286 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003287}
3288
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003289//===----------------------------------------------------------------------===//
3290// Meta Data Emission
3291//===----------------------------------------------------------------------===//
3292
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003293
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003294/// RewriteImplementations - This routine rewrites all method implementations
3295/// and emits meta-data.
3296
Steve Narofface66252008-11-13 20:07:04 +00003297void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003298 int ClsDefCount = ClassImplementation.size();
3299 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003301 // Rewrite implemented methods
3302 for (int i = 0; i < ClsDefCount; i++)
3303 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003304
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003305 for (int i = 0; i < CatDefCount; i++)
3306 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003307}
Mike Stump1eb44332009-09-09 15:08:12 +00003308
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003309void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3310 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003311 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003312 assert(BlockByRefDeclNo.count(VD) &&
3313 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003314 if (def)
3315 ResultStr += "struct ";
3316 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003317 "_" + utostr(BlockByRefDeclNo[VD]) ;
3318}
3319
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003320static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3321 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3322 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3323 return false;
3324}
3325
Steve Naroff54055232008-10-27 17:20:55 +00003326std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003327 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003328 std::string Tag) {
3329 const FunctionType *AFT = CE->getFunctionType();
3330 QualType RT = AFT->getResultType();
3331 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003332 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003333 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003334
Steve Naroff54055232008-10-27 17:20:55 +00003335 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003336
Douglas Gregor72564e72009-02-26 23:50:07 +00003337 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003338 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003339 // block (to reference imported block decl refs).
3340 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003341 } else if (BD->param_empty()) {
3342 S += "(" + StructRef + " *__cself)";
3343 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003344 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003345 assert(FT && "SynthesizeBlockFunc: No function proto");
3346 S += '(';
3347 // first add the implicit argument.
3348 S += StructRef + " *__cself, ";
3349 std::string ParamStr;
3350 for (BlockDecl::param_iterator AI = BD->param_begin(),
3351 E = BD->param_end(); AI != E; ++AI) {
3352 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003353 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003354 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003355 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003356 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003357 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003358 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003359 S += ParamStr;
3360 }
3361 if (FT->isVariadic()) {
3362 if (!BD->param_empty()) S += ", ";
3363 S += "...";
3364 }
3365 S += ')';
3366 }
3367 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Steve Naroff54055232008-10-27 17:20:55 +00003369 // Create local declarations to avoid rewriting all closure decl ref exprs.
3370 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003371 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003372 E = BlockByRefDecls.end(); I != E; ++I) {
3373 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003375 std::string TypeString;
3376 RewriteByRefString(TypeString, Name, (*I));
3377 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003378 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003379 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003380 }
Steve Naroff54055232008-10-27 17:20:55 +00003381 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003382 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003383 E = BlockByCopyDecls.end(); I != E; ++I) {
3384 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003385 // Handle nested closure invocation. For example:
3386 //
3387 // void (^myImportedClosure)(void);
3388 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003389 //
Steve Naroff54055232008-10-27 17:20:55 +00003390 // void (^anotherClosure)(void);
3391 // anotherClosure = ^(void) {
3392 // myImportedClosure(); // import and invoke the closure
3393 // };
3394 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003395 if (isTopLevelBlockPointerType((*I)->getType())) {
3396 RewriteBlockPointerTypeVariable(S, (*I));
3397 S += " = (";
3398 RewriteBlockPointerType(S, (*I)->getType());
3399 S += ")";
3400 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3401 }
3402 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003403 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003404 QualType QT = (*I)->getType();
3405 if (HasLocalVariableExternalStorage(*I))
3406 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003407 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003408 S += Name + " = __cself->" +
3409 (*I)->getNameAsString() + "; // bound by copy\n";
3410 }
Steve Naroff54055232008-10-27 17:20:55 +00003411 }
3412 std::string RewrittenStr = RewrittenBlockExprs[CE];
3413 const char *cstr = RewrittenStr.c_str();
3414 while (*cstr++ != '{') ;
3415 S += cstr;
3416 S += "\n";
3417 return S;
3418}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003419
Steve Naroff54055232008-10-27 17:20:55 +00003420std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003421 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003422 std::string Tag) {
3423 std::string StructRef = "struct " + Tag;
3424 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003425
Steve Naroff54055232008-10-27 17:20:55 +00003426 S += funcName;
3427 S += "_block_copy_" + utostr(i);
3428 S += "(" + StructRef;
3429 S += "*dst, " + StructRef;
3430 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003431 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003432 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003433 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003434 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003435 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003436 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003437 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003438 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003439 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003440 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003441 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003442 else
3443 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003444 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003445 S += "}\n";
3446
Steve Naroff54055232008-10-27 17:20:55 +00003447 S += "\nstatic void __";
3448 S += funcName;
3449 S += "_block_dispose_" + utostr(i);
3450 S += "(" + StructRef;
3451 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003452 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003453 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003454 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003455 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003456 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003457 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003458 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003459 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003460 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003461 else
3462 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003463 }
Mike Stump1eb44332009-09-09 15:08:12 +00003464 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003465 return S;
3466}
3467
Steve Naroff01aec112009-12-06 21:14:13 +00003468std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3469 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003470 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003471 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Steve Naroff54055232008-10-27 17:20:55 +00003473 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003474 S += " struct " + Desc;
3475 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003476
Steve Naroff01aec112009-12-06 21:14:13 +00003477 Constructor += "(void *fp, "; // Invoke function pointer.
3478 Constructor += "struct " + Desc; // Descriptor pointer.
3479 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003480
Steve Naroff54055232008-10-27 17:20:55 +00003481 if (BlockDeclRefs.size()) {
3482 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003483 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003484 E = BlockByCopyDecls.end(); I != E; ++I) {
3485 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003486 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003487 std::string ArgName = "_" + FieldName;
3488 // Handle nested closure invocation. For example:
3489 //
3490 // void (^myImportedBlock)(void);
3491 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003492 //
Steve Naroff54055232008-10-27 17:20:55 +00003493 // void (^anotherBlock)(void);
3494 // anotherBlock = ^(void) {
3495 // myImportedBlock(); // import and invoke the closure
3496 // };
3497 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003498 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003499 S += "struct __block_impl *";
3500 Constructor += ", void *" + ArgName;
3501 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003502 QualType QT = (*I)->getType();
3503 if (HasLocalVariableExternalStorage(*I))
3504 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003505 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3506 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003507 Constructor += ", " + ArgName;
3508 }
3509 S += FieldName + ";\n";
3510 }
3511 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003512 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003513 E = BlockByRefDecls.end(); I != E; ++I) {
3514 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003515 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003516 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003517 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003518 std::string TypeString;
3519 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003520 TypeString += " *";
3521 FieldName = TypeString + FieldName;
3522 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003523 Constructor += ", " + ArgName;
3524 }
3525 S += FieldName + "; // by ref\n";
3526 }
3527 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003528 Constructor += ", int flags=0)";
3529 // Initialize all "by copy" arguments.
3530 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003531 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003532 E = BlockByCopyDecls.end(); I != E; ++I) {
3533 std::string Name = (*I)->getNameAsString();
3534 if (firsTime) {
3535 Constructor += " : ";
3536 firsTime = false;
3537 }
3538 else
3539 Constructor += ", ";
3540 if (isTopLevelBlockPointerType((*I)->getType()))
3541 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3542 else
3543 Constructor += Name + "(_" + Name + ")";
3544 }
3545 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003546 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003547 E = BlockByRefDecls.end(); I != E; ++I) {
3548 std::string Name = (*I)->getNameAsString();
3549 if (firsTime) {
3550 Constructor += " : ";
3551 firsTime = false;
3552 }
3553 else
3554 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003555 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003556 }
3557
3558 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003559 if (GlobalVarDecl)
3560 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3561 else
3562 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003563 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Steve Naroff01aec112009-12-06 21:14:13 +00003565 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003566 } else {
3567 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003568 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003569 if (GlobalVarDecl)
3570 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3571 else
3572 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003573 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3574 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003575 }
3576 Constructor += " ";
3577 Constructor += "}\n";
3578 S += Constructor;
3579 S += "};\n";
3580 return S;
3581}
3582
Steve Naroff01aec112009-12-06 21:14:13 +00003583std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3584 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003585 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003586 unsigned hasCopy) {
3587 std::string S = "\nstatic struct " + DescTag;
3588
3589 S += " {\n unsigned long reserved;\n";
3590 S += " unsigned long Block_size;\n";
3591 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003592 S += " void (*copy)(struct ";
3593 S += ImplTag; S += "*, struct ";
3594 S += ImplTag; S += "*);\n";
3595
3596 S += " void (*dispose)(struct ";
3597 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003598 }
3599 S += "} ";
3600
3601 S += DescTag + "_DATA = { 0, sizeof(struct ";
3602 S += ImplTag + ")";
3603 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003604 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3605 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003606 }
3607 S += "};\n";
3608 return S;
3609}
3610
Steve Naroff54055232008-10-27 17:20:55 +00003611void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003612 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003613 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003614 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003615 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003616 bool RewriteSC = (GlobalVarDecl &&
3617 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003618 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003619 GlobalVarDecl->getType().getCVRQualifiers());
3620 if (RewriteSC) {
3621 std::string SC(" void __");
3622 SC += GlobalVarDecl->getNameAsString();
3623 SC += "() {}";
3624 InsertText(FunLocStart, SC);
3625 }
3626
Steve Naroff54055232008-10-27 17:20:55 +00003627 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003628 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3629 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003630 // Need to copy-in the inner copied-in variables not actually used in this
3631 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003632 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3633 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3634 ValueDecl *VD = Exp->getDecl();
3635 BlockDeclRefs.push_back(Exp);
3636 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3637 BlockByCopyDeclsPtrSet.insert(VD);
3638 BlockByCopyDecls.push_back(VD);
3639 }
3640 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3641 BlockByRefDeclsPtrSet.insert(VD);
3642 BlockByRefDecls.push_back(VD);
3643 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003644 // imported objects in the inner blocks not used in the outer
3645 // blocks must be copied/disposed in the outer block as well.
3646 if (Exp->isByRef() ||
3647 VD->getType()->isObjCObjectPointerType() ||
3648 VD->getType()->isBlockPointerType())
3649 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003650 }
Steve Naroff54055232008-10-27 17:20:55 +00003651
Daniel Dunbar4087f272010-08-17 22:39:59 +00003652 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3653 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003654
Steve Naroff01aec112009-12-06 21:14:13 +00003655 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003656
Benjamin Kramerd999b372010-02-14 14:14:16 +00003657 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003658
Steve Naroff01aec112009-12-06 21:14:13 +00003659 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Benjamin Kramerd999b372010-02-14 14:14:16 +00003661 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003662
3663 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003664 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003665 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003666 }
Steve Naroff01aec112009-12-06 21:14:13 +00003667 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3668 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003669 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Steve Naroff54055232008-10-27 17:20:55 +00003671 BlockDeclRefs.clear();
3672 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003673 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003674 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003675 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003676 ImportedBlockDecls.clear();
3677 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003678 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003679 // Must insert any 'const/volatile/static here. Since it has been
3680 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003681 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003682 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003683 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003684 if (GlobalVarDecl->getType().isConstQualified())
3685 SC += "const ";
3686 if (GlobalVarDecl->getType().isVolatileQualified())
3687 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003688 if (GlobalVarDecl->getType().isRestrictQualified())
3689 SC += "restrict ";
3690 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003691 }
3692
Steve Naroff54055232008-10-27 17:20:55 +00003693 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003694 InnerDeclRefsCount.clear();
3695 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003696 RewrittenBlockExprs.clear();
3697}
3698
3699void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3700 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003701 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Steve Naroff54055232008-10-27 17:20:55 +00003703 SynthesizeBlockLiterals(FunLocStart, FuncName);
3704}
3705
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003706static void BuildUniqueMethodName(std::string &Name,
3707 ObjCMethodDecl *MD) {
3708 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003709 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003710 Name += "__" + MD->getSelector().getAsString();
3711 // Convert colons to underscores.
3712 std::string::size_type loc = 0;
3713 while ((loc = Name.find(":", loc)) != std::string::npos)
3714 Name.replace(loc, 1, "_");
3715}
3716
Steve Naroff54055232008-10-27 17:20:55 +00003717void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003718 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3719 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003720 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003721 std::string FuncName;
3722 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003723 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003724}
3725
3726void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003727 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003728 if (*CI) {
3729 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3730 GetBlockDeclRefExprs(CBE->getBody());
3731 else
3732 GetBlockDeclRefExprs(*CI);
3733 }
3734 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003735 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003736 // FIXME: Handle enums.
3737 if (!isa<FunctionDecl>(CDRE->getDecl()))
3738 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003739 }
3740 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3741 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3742 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003743 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3744 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003745 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003746 BlockDeclRefs.push_back(BDRE);
3747 }
3748
Steve Naroff54055232008-10-27 17:20:55 +00003749 return;
3750}
3751
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003752void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003753 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003754 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003755 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003756 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003757 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3758 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003759 GetInnerBlockDeclRefExprs(CBE->getBody(),
3760 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003761 InnerContexts);
3762 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003763 else
3764 GetInnerBlockDeclRefExprs(*CI,
3765 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003766 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003767
3768 }
3769 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003770 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003771 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003772 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003773 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003774 }
3775 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3776 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3777 if (Var->isFunctionOrMethodVarDecl())
3778 ImportedLocalExternalDecls.insert(Var);
3779 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003780
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003781 return;
3782}
3783
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003784/// convertFunctionTypeOfBlocks - This routine converts a function type
3785/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003786/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003787/// all block pointers to function pointers.
3788QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3789 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3790 // FTP will be null for closures that don't take arguments.
3791 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003792 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003793 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003794 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003795
3796 if (FTP) {
3797 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3798 E = FTP->arg_type_end(); I && (I != E); ++I) {
3799 QualType t = *I;
3800 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003801 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003802 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003803 ArgTypes.push_back(t);
3804 }
3805 }
3806 QualType FuncType;
3807 // FIXME. Does this work if block takes no argument but has a return type
3808 // which is of block type?
3809 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003810 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003811 else FuncType = QualType(FT, 0);
3812 return FuncType;
3813}
3814
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003815Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003816 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003817 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003819 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003820 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003821 } else if (const BlockDeclRefExpr *CDRE =
3822 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003823 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003824 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003825 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003826 }
3827 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3828 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3829 }
3830 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3831 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3832 else if (const ConditionalOperator *CEXPR =
3833 dyn_cast<ConditionalOperator>(BlockExp)) {
3834 Expr *LHSExp = CEXPR->getLHS();
3835 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3836 Expr *RHSExp = CEXPR->getRHS();
3837 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3838 Expr *CONDExp = CEXPR->getCond();
3839 ConditionalOperator *CondExpr =
3840 new (Context) ConditionalOperator(CONDExp,
3841 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003842 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003843 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003844 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003845 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3846 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003847 } else if (const PseudoObjectExpr *POE
3848 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3849 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003850 } else {
3851 assert(1 && "RewriteBlockClass: Bad type");
3852 }
3853 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003854 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003855 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003856 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003857 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003859 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003860 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003861 &Context->Idents.get("__block_impl"));
3862 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003863
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003864 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003865 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003867 // Push the block argument type.
3868 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003869 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003870 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003871 E = FTP->arg_type_end(); I && (I != E); ++I) {
3872 QualType t = *I;
3873 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003874 if (!convertBlockPointerToFunctionPointer(t))
3875 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003876 ArgTypes.push_back(t);
3877 }
Steve Naroff54055232008-10-27 17:20:55 +00003878 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003879 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003880 QualType PtrToFuncCastType
3881 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003883 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003884
John McCall9d125032010-01-15 18:39:57 +00003885 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003886 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003887 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003888 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003889 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3890 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003891 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003892
Douglas Gregor44b43212008-12-11 16:49:14 +00003893 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003894 SourceLocation(),
3895 &Context->Idents.get("FuncPtr"),
3896 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003897 /*BitWidth=*/0, /*Mutable=*/true,
3898 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003899 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003900 FD->getType(), VK_LValue,
3901 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003903
John McCall9d125032010-01-15 18:39:57 +00003904 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003905 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003906 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003907
Chris Lattner5f9e2722011-07-23 10:55:15 +00003908 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003909 // Add the implicit argument.
3910 BlkExprs.push_back(BlkCast);
3911 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003912 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003913 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003914 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003915 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003916 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3917 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003918 Exp->getType(), VK_RValue,
3919 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003920 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003921}
3922
Steve Naroff621edce2009-04-29 16:37:50 +00003923// We need to return the rewritten expression to handle cases where the
3924// BlockDeclRefExpr is embedded in another expression being rewritten.
3925// For example:
3926//
3927// int main() {
3928// __block Foo *f;
3929// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003930//
Steve Naroff621edce2009-04-29 16:37:50 +00003931// void (^myblock)() = ^() {
3932// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3933// i = 77;
3934// };
3935//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003936Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003937 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003938 // for each DeclRefExp where BYREFVAR is name of the variable.
3939 ValueDecl *VD;
3940 bool isArrow = true;
3941 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3942 VD = BDRE->getDecl();
3943 else {
3944 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3945 isArrow = false;
3946 }
3947
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003948 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003949 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003950 &Context->Idents.get("__forwarding"),
3951 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003952 /*BitWidth=*/0, /*Mutable=*/true,
3953 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003954 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3955 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003956 FD->getType(), VK_LValue,
3957 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003958
Chris Lattner5f9e2722011-07-23 10:55:15 +00003959 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003960 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003961 &Context->Idents.get(Name),
3962 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003963 /*BitWidth=*/0, /*Mutable=*/true,
3964 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003965 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003966 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003967
3968
3969
Steve Naroffdf8570d2009-02-02 17:19:26 +00003970 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003971 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3972 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003973 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003974 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003975 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003976}
3977
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003978// Rewrites the imported local variable V with external storage
3979// (static, extern, etc.) as *V
3980//
3981Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3982 ValueDecl *VD = DRE->getDecl();
3983 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3984 if (!ImportedLocalExternalDecls.count(Var))
3985 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003986 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3987 VK_LValue, OK_Ordinary,
3988 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003989 // Need parens to enforce precedence.
3990 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3991 Exp);
3992 ReplaceStmt(DRE, PE);
3993 return PE;
3994}
3995
Steve Naroffb2f9e512008-11-03 23:29:32 +00003996void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3997 SourceLocation LocStart = CE->getLParenLoc();
3998 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003999
4000 // Need to avoid trying to rewrite synthesized casts.
4001 if (LocStart.isInvalid())
4002 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004003 // Need to avoid trying to rewrite casts contained in macros.
4004 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4005 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004006
Steve Naroff54055232008-10-27 17:20:55 +00004007 const char *startBuf = SM->getCharacterData(LocStart);
4008 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004009 QualType QT = CE->getType();
4010 const Type* TypePtr = QT->getAs<Type>();
4011 if (isa<TypeOfExprType>(TypePtr)) {
4012 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4013 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4014 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004015 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004016 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004017 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004018 return;
4019 }
Steve Naroff54055232008-10-27 17:20:55 +00004020 // advance the location to startArgList.
4021 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Steve Naroff54055232008-10-27 17:20:55 +00004023 while (*argPtr++ && (argPtr < endBuf)) {
4024 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004025 case '^':
4026 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004027 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004028 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004029 break;
Steve Naroff54055232008-10-27 17:20:55 +00004030 }
4031 }
4032 return;
4033}
4034
4035void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4036 SourceLocation DeclLoc = FD->getLocation();
4037 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004038
Steve Naroff54055232008-10-27 17:20:55 +00004039 // We have 1 or more arguments that have closure pointers.
4040 const char *startBuf = SM->getCharacterData(DeclLoc);
4041 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Steve Naroff54055232008-10-27 17:20:55 +00004043 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Steve Naroff54055232008-10-27 17:20:55 +00004045 parenCount++;
4046 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004047 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004048 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004049
Steve Naroff54055232008-10-27 17:20:55 +00004050 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Steve Naroff54055232008-10-27 17:20:55 +00004052 while (*argPtr++ && parenCount) {
4053 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004054 case '^':
4055 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004056 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004057 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004058 break;
4059 case '(':
4060 parenCount++;
4061 break;
4062 case ')':
4063 parenCount--;
4064 break;
Steve Naroff54055232008-10-27 17:20:55 +00004065 }
4066 }
4067 return;
4068}
4069
4070bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004071 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004072 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004073 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004074 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004075 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004076 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004077 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004078 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004079 }
4080 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004081 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004082 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004083 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004084 return true;
4085 }
4086 return false;
4087}
4088
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004089bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4090 const FunctionProtoType *FTP;
4091 const PointerType *PT = QT->getAs<PointerType>();
4092 if (PT) {
4093 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4094 } else {
4095 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4096 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4097 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4098 }
4099 if (FTP) {
4100 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004101 E = FTP->arg_type_end(); I != E; ++I) {
4102 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004103 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004104 if ((*I)->isObjCObjectPointerType() &&
4105 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4106 return true;
4107 }
4108
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004109 }
4110 return false;
4111}
4112
Ted Kremenek8189cde2009-02-07 01:47:29 +00004113void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4114 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004115 const char *argPtr = strchr(Name, '(');
4116 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004117
Steve Naroff54055232008-10-27 17:20:55 +00004118 LParen = argPtr; // output the start.
4119 argPtr++; // skip past the left paren.
4120 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004121
Steve Naroff54055232008-10-27 17:20:55 +00004122 while (*argPtr && parenCount) {
4123 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004124 case '(': parenCount++; break;
4125 case ')': parenCount--; break;
4126 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004127 }
4128 if (parenCount) argPtr++;
4129 }
4130 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4131 RParen = argPtr; // output the end
4132}
4133
4134void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4135 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4136 RewriteBlockPointerFunctionArgs(FD);
4137 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004138 }
Steve Naroff54055232008-10-27 17:20:55 +00004139 // Handle Variables and Typedefs.
4140 SourceLocation DeclLoc = ND->getLocation();
4141 QualType DeclT;
4142 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4143 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004144 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004145 DeclT = TDD->getUnderlyingType();
4146 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4147 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004148 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004149 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004150
Steve Naroff54055232008-10-27 17:20:55 +00004151 const char *startBuf = SM->getCharacterData(DeclLoc);
4152 const char *endBuf = startBuf;
4153 // scan backward (from the decl location) for the end of the previous decl.
4154 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4155 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004156 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004157 std::string buf;
4158 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004159 // *startBuf != '^' if we are dealing with a pointer to function that
4160 // may take block argument types (which will be handled below).
4161 if (*startBuf == '^') {
4162 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004163 buf = '*';
4164 startBuf++;
4165 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004166 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004167 while (*startBuf != ')') {
4168 buf += *startBuf;
4169 startBuf++;
4170 OrigLength++;
4171 }
4172 buf += ')';
4173 OrigLength++;
4174
4175 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4176 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004177 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004178 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004179 DeclLoc = ND->getLocation();
4180 startBuf = SM->getCharacterData(DeclLoc);
4181 const char *argListBegin, *argListEnd;
4182 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4183 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004184 if (*argListBegin == '^')
4185 buf += '*';
4186 else if (*argListBegin == '<') {
4187 buf += "/*";
4188 buf += *argListBegin++;
4189 OrigLength++;;
4190 while (*argListBegin != '>') {
4191 buf += *argListBegin++;
4192 OrigLength++;
4193 }
4194 buf += *argListBegin;
4195 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004196 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004197 else
4198 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004199 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004200 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004201 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004202 buf += ')';
4203 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004204 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004205 ReplaceText(Start, OrigLength, buf);
4206
Steve Naroff54055232008-10-27 17:20:55 +00004207 return;
4208}
4209
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004210
4211/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4212/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4213/// struct Block_byref_id_object *src) {
4214/// _Block_object_assign (&_dest->object, _src->object,
4215/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4216/// [|BLOCK_FIELD_IS_WEAK]) // object
4217/// _Block_object_assign(&_dest->object, _src->object,
4218/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4219/// [|BLOCK_FIELD_IS_WEAK]) // block
4220/// }
4221/// And:
4222/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4223/// _Block_object_dispose(_src->object,
4224/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4225/// [|BLOCK_FIELD_IS_WEAK]) // object
4226/// _Block_object_dispose(_src->object,
4227/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4228/// [|BLOCK_FIELD_IS_WEAK]) // block
4229/// }
4230
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004231std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4232 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004233 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004234 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004235 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004236 CopyDestroyCache.insert(flag);
4237 S = "static void __Block_byref_id_object_copy_";
4238 S += utostr(flag);
4239 S += "(void *dst, void *src) {\n";
4240
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004241 // offset into the object pointer is computed as:
4242 // void * + void* + int + int + void* + void *
4243 unsigned IntSize =
4244 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4245 unsigned VoidPtrSize =
4246 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4247
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004248 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004249 S += " _Block_object_assign((char*)dst + ";
4250 S += utostr(offset);
4251 S += ", *(void * *) ((char*)src + ";
4252 S += utostr(offset);
4253 S += "), ";
4254 S += utostr(flag);
4255 S += ");\n}\n";
4256
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004257 S += "static void __Block_byref_id_object_dispose_";
4258 S += utostr(flag);
4259 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004260 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4261 S += utostr(offset);
4262 S += "), ";
4263 S += utostr(flag);
4264 S += ");\n}\n";
4265 return S;
4266}
4267
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004268/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4269/// the declaration into:
4270/// struct __Block_byref_ND {
4271/// void *__isa; // NULL for everything except __weak pointers
4272/// struct __Block_byref_ND *__forwarding;
4273/// int32_t __flags;
4274/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004275/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4276/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004277/// typex ND;
4278/// };
4279///
4280/// It then replaces declaration of ND variable with:
4281/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4282/// __size=sizeof(struct __Block_byref_ND),
4283/// ND=initializer-if-any};
4284///
4285///
4286void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004287 // Insert declaration for the function in which block literal is
4288 // used.
4289 if (CurFunctionDeclToDeclareForBlock)
4290 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004291 int flag = 0;
4292 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004293 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004294 if (DeclLoc.isInvalid())
4295 // If type location is missing, it is because of missing type (a warning).
4296 // Use variable's location which is good for this case.
4297 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004298 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004299 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004300 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004301 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004302 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004303 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004304 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004305 ByrefType += " {\n";
4306 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004307 RewriteByRefString(ByrefType, Name, ND);
4308 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004309 ByrefType += " int __flags;\n";
4310 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004311 // Add void *__Block_byref_id_object_copy;
4312 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004313 QualType Ty = ND->getType();
4314 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4315 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004316 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4317 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004318 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004319
4320 QualType T = Ty;
4321 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004322 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004323
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004324 ByrefType += " " + Name + ";\n";
4325 ByrefType += "};\n";
4326 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004327 SourceLocation FunLocStart;
4328 if (CurFunctionDef)
4329 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4330 else {
4331 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4332 FunLocStart = CurMethodDef->getLocStart();
4333 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004334 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004335 if (Ty.isObjCGCWeak()) {
4336 flag |= BLOCK_FIELD_IS_WEAK;
4337 isa = 1;
4338 }
4339
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004340 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004341 flag = BLOCK_BYREF_CALLER;
4342 QualType Ty = ND->getType();
4343 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4344 if (Ty->isBlockPointerType())
4345 flag |= BLOCK_FIELD_IS_BLOCK;
4346 else
4347 flag |= BLOCK_FIELD_IS_OBJECT;
4348 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004349 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004350 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004351 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004352
4353 // struct __Block_byref_ND ND =
4354 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4355 // initializer-if-any};
4356 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004357 unsigned flags = 0;
4358 if (HasCopyAndDispose)
4359 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004360 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004361 ByrefType.clear();
4362 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004363 std::string ForwardingCastType("(");
4364 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004365 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004366 ByrefType += " " + Name + " = {(void*)";
4367 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004368 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004369 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004370 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004371 ByrefType += "sizeof(";
4372 RewriteByRefString(ByrefType, Name, ND);
4373 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004374 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004375 ByrefType += ", __Block_byref_id_object_copy_";
4376 ByrefType += utostr(flag);
4377 ByrefType += ", __Block_byref_id_object_dispose_";
4378 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004379 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004380 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004381 unsigned nameSize = Name.size();
4382 // for block or function pointer declaration. Name is aleady
4383 // part of the declaration.
4384 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4385 nameSize = 1;
4386 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004387 }
4388 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004389 SourceLocation startLoc;
4390 Expr *E = ND->getInit();
4391 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4392 startLoc = ECE->getLParenLoc();
4393 else
4394 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004395 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004396 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004397 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004398 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004399 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004400 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004401 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004402 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004403 ByrefType += "sizeof(";
4404 RewriteByRefString(ByrefType, Name, ND);
4405 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004406 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004407 ByrefType += "__Block_byref_id_object_copy_";
4408 ByrefType += utostr(flag);
4409 ByrefType += ", __Block_byref_id_object_dispose_";
4410 ByrefType += utostr(flag);
4411 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004412 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004413 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004414
4415 // Complete the newly synthesized compound expression by inserting a right
4416 // curly brace before the end of the declaration.
4417 // FIXME: This approach avoids rewriting the initializer expression. It
4418 // also assumes there is only one declarator. For example, the following
4419 // isn't currently supported by this routine (in general):
4420 //
4421 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4422 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004423 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4424 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004425 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4426 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004427 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004428
Benjamin Kramerd999b372010-02-14 14:14:16 +00004429 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004430 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004431 return;
4432}
4433
Mike Stump1eb44332009-09-09 15:08:12 +00004434void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004435 // Add initializers for any closure decl refs.
4436 GetBlockDeclRefExprs(Exp->getBody());
4437 if (BlockDeclRefs.size()) {
4438 // Unique all "by copy" declarations.
4439 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004440 if (!BlockDeclRefs[i]->isByRef()) {
4441 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4442 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4443 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4444 }
4445 }
Steve Naroff54055232008-10-27 17:20:55 +00004446 // Unique all "by ref" declarations.
4447 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4448 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004449 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4450 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4451 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4452 }
Steve Naroff54055232008-10-27 17:20:55 +00004453 }
4454 // Find any imported blocks...they will need special attention.
4455 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004456 if (BlockDeclRefs[i]->isByRef() ||
4457 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004458 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004459 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004460 }
4461}
4462
Chris Lattner5f9e2722011-07-23 10:55:15 +00004463FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004464 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004465 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004466 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4467 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004468 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004469}
4470
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004471Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004472 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004473 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004474 Blocks.push_back(Exp);
4475
4476 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004477
4478 // Add inner imported variables now used in current block.
4479 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004480 if (!InnerBlockDeclRefs.empty()) {
4481 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4482 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4483 ValueDecl *VD = Exp->getDecl();
4484 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004485 // We need to save the copied-in variables in nested
4486 // blocks because it is needed at the end for some of the API generations.
4487 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004488 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4489 BlockDeclRefs.push_back(Exp);
4490 BlockByCopyDeclsPtrSet.insert(VD);
4491 BlockByCopyDecls.push_back(VD);
4492 }
4493 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4494 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4495 BlockDeclRefs.push_back(Exp);
4496 BlockByRefDeclsPtrSet.insert(VD);
4497 BlockByRefDecls.push_back(VD);
4498 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004499 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004500 // Find any imported blocks...they will need special attention.
4501 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4502 if (InnerBlockDeclRefs[i]->isByRef() ||
4503 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4504 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4505 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004506 }
4507 InnerDeclRefsCount.push_back(countOfInnerDecls);
4508
Steve Narofffa15fd92008-10-28 20:29:00 +00004509 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004510
Steve Narofffa15fd92008-10-28 20:29:00 +00004511 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004512 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004513 else if (CurMethodDef)
4514 BuildUniqueMethodName(FuncName, CurMethodDef);
4515 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004516 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004517
Steve Narofffa15fd92008-10-28 20:29:00 +00004518 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4521 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004522
Steve Narofffa15fd92008-10-28 20:29:00 +00004523 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004524 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4525 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004526
4527 FunctionDecl *FD;
4528 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Steve Narofffa15fd92008-10-28 20:29:00 +00004530 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004531 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004532 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4533 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Chris Lattner5f9e2722011-07-23 10:55:15 +00004535 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Steve Narofffdc03722008-10-29 21:23:59 +00004537 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004538 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004539 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004540 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004541 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004542 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004543 InitExprs.push_back(castExpr);
4544
Steve Naroff01aec112009-12-06 21:14:13 +00004545 // Initialize the block descriptor.
4546 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004547
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004548 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4549 SourceLocation(), SourceLocation(),
4550 &Context->Idents.get(DescData.c_str()),
4551 Context->VoidPtrTy, 0,
4552 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004553 UnaryOperator *DescRefExpr =
4554 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4555 Context->VoidPtrTy,
4556 VK_LValue,
4557 SourceLocation()),
4558 UO_AddrOf,
4559 Context->getPointerType(Context->VoidPtrTy),
4560 VK_RValue, OK_Ordinary,
4561 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004562 InitExprs.push_back(DescRefExpr);
4563
Steve Narofffa15fd92008-10-28 20:29:00 +00004564 // Add initializers for any closure decl refs.
4565 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004566 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004567 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004568 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004569 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004570 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004571 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004572 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004573 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4574 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004575 if (HasLocalVariableExternalStorage(*I)) {
4576 QualType QT = (*I)->getType();
4577 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004578 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4579 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004580 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004581 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004582 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004583 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4584 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004585 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004586 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004587 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004588 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004589 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4590 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004591 if (HasLocalVariableExternalStorage(*I)) {
4592 QualType QT = (*I)->getType();
4593 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004594 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4595 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004596 }
4597
Steve Narofffa15fd92008-10-28 20:29:00 +00004598 }
Mike Stump1eb44332009-09-09 15:08:12 +00004599 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004600 }
4601 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004602 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004603 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004604 ValueDecl *ND = (*I);
4605 std::string Name(ND->getNameAsString());
4606 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004607 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004608 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4609 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004610 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004611 SourceLocation(), SourceLocation(),
4612 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004613 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4614 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4615
Daniel Dunbar4087f272010-08-17 22:39:59 +00004616 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004617 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4618 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004619 bool isNestedCapturedVar = false;
4620 if (block)
4621 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4622 ce = block->capture_end(); ci != ce; ++ci) {
4623 const VarDecl *variable = ci->getVariable();
4624 if (variable == ND && ci->isNested()) {
4625 assert (ci->isByRef() &&
4626 "SynthBlockInitExpr - captured block variable is not byref");
4627 isNestedCapturedVar = true;
4628 break;
4629 }
4630 }
4631 // captured nested byref variable has its address passed. Do not take
4632 // its address again.
4633 if (!isNestedCapturedVar)
4634 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004635 Context->getPointerType(Exp->getType()),
4636 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004637 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004638 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004639 }
4640 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004641 if (ImportedBlockDecls.size()) {
4642 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4643 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004644 unsigned IntSize =
4645 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004646 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4647 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004648 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004649 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004650 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004651 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004652 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004653 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004654 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004655 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004656 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004657 BlockDeclRefs.clear();
4658 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004659 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004660 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004661 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004662 ImportedBlockDecls.clear();
4663 return NewRep;
4664}
4665
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004666bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4667 if (const ObjCForCollectionStmt * CS =
4668 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4669 return CS->getElement() == DS;
4670 return false;
4671}
4672
Steve Narofffa15fd92008-10-28 20:29:00 +00004673//===----------------------------------------------------------------------===//
4674// Function Body / Expression rewriting
4675//===----------------------------------------------------------------------===//
4676
4677Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004678 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004679 isa<DoStmt>(S) || isa<ForStmt>(S))
4680 Stmts.push_back(S);
4681 else if (isa<ObjCForCollectionStmt>(S)) {
4682 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004683 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 }
Mike Stump1eb44332009-09-09 15:08:12 +00004685
John McCall4b9c2d22011-11-06 09:01:30 +00004686 // Pseudo-object operations and ivar references need special
4687 // treatment because we're going to recursively rewrite them.
4688 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4689 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4690 return RewritePropertyOrImplicitSetter(PseudoOp);
4691 } else {
4692 return RewritePropertyOrImplicitGetter(PseudoOp);
4693 }
4694 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4695 return RewriteObjCIvarRefExpr(IvarRefExpr);
4696 }
4697
Steve Narofffa15fd92008-10-28 20:29:00 +00004698 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Steve Narofffa15fd92008-10-28 20:29:00 +00004700 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004701 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004702 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004703 Stmt *childStmt = (*CI);
4704 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004705 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004706 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004707 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004708 }
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Steve Narofffa15fd92008-10-28 20:29:00 +00004710 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004711 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004712 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4713 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004714 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004715 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004716 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004717 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004718 Stmt *SaveCurrentBody = CurrentBody;
4719 CurrentBody = BE->getBody();
4720 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004721 // block literal on rhs of a property-dot-sytax assignment
4722 // must be replaced by its synthesize ast so getRewrittenText
4723 // works as expected. In this case, what actually ends up on RHS
4724 // is the blockTranscribed which is the helper function for the
4725 // block literal; as in: self.c = ^() {[ace ARR];};
4726 bool saveDisableReplaceStmt = DisableReplaceStmt;
4727 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004728 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004729 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004730 CurrentBody = SaveCurrentBody;
4731 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004732 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004733 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004734 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004735 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004737 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4738
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004740 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004741 return blockTranscribed;
4742 }
4743 // Handle specific things.
4744 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4745 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4748 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Steve Narofffa15fd92008-10-28 20:29:00 +00004750 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4751 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Steve Narofffa15fd92008-10-28 20:29:00 +00004753 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004754#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004755 // Before we rewrite it, put the original message expression in a comment.
4756 SourceLocation startLoc = MessExpr->getLocStart();
4757 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004758
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 const char *startBuf = SM->getCharacterData(startLoc);
4760 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Steve Narofffa15fd92008-10-28 20:29:00 +00004762 std::string messString;
4763 messString += "// ";
4764 messString.append(startBuf, endBuf-startBuf+1);
4765 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004766
4767 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004768 // InsertText(clang::SourceLocation, char const*, unsigned int).
4769 // InsertText(startLoc, messString.c_str(), messString.size());
4770 // Tried this, but it didn't work either...
4771 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004772#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004773 return RewriteMessageExpr(MessExpr);
4774 }
Mike Stump1eb44332009-09-09 15:08:12 +00004775
Steve Narofffa15fd92008-10-28 20:29:00 +00004776 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4777 return RewriteObjCTryStmt(StmtTry);
4778
4779 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4780 return RewriteObjCSynchronizedStmt(StmtTry);
4781
4782 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4783 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Steve Narofffa15fd92008-10-28 20:29:00 +00004785 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4786 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004787
4788 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004789 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004790 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004791 OrigStmtRange.getEnd());
4792 if (BreakStmt *StmtBreakStmt =
4793 dyn_cast<BreakStmt>(S))
4794 return RewriteBreakStmt(StmtBreakStmt);
4795 if (ContinueStmt *StmtContinueStmt =
4796 dyn_cast<ContinueStmt>(S))
4797 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004798
4799 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 // and cast exprs.
4801 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4802 // FIXME: What we're doing here is modifying the type-specifier that
4803 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004804 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004805 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4806 // the context of an ObjCForCollectionStmt. For example:
4807 // NSArray *someArray;
4808 // for (id <FooProtocol> index in someArray) ;
4809 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4810 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004811 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004812 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Steve Narofffa15fd92008-10-28 20:29:00 +00004814 // Blocks rewrite rules.
4815 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4816 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004817 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004818 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004819 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004820 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004821 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004822 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004823 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004824 if (VD->hasAttr<BlocksAttr>()) {
4825 static unsigned uniqueByrefDeclCount = 0;
4826 assert(!BlockByRefDeclNo.count(ND) &&
4827 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4828 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004829 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004830 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004831 else
4832 RewriteTypeOfDecl(VD);
4833 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004834 }
Richard Smith162e1c12011-04-15 14:24:37 +00004835 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004836 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004837 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004838 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004839 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4840 }
4841 }
4842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Steve Narofffa15fd92008-10-28 20:29:00 +00004844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4845 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004846
4847 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004848 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4849 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004850 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4851 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004852 && "Statement stack mismatch");
4853 Stmts.pop_back();
4854 }
4855 // Handle blocks rewriting.
4856 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4857 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004858 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004860 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4861 ValueDecl *VD = DRE->getDecl();
4862 if (VD->hasAttr<BlocksAttr>())
4863 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004864 if (HasLocalVariableExternalStorage(VD))
4865 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004866 }
4867
Steve Narofffa15fd92008-10-28 20:29:00 +00004868 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004869 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004870 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004871 ReplaceStmt(S, BlockCall);
4872 return BlockCall;
4873 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004874 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004875 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004876 RewriteCastExpr(CE);
4877 }
4878#if 0
4879 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004880 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4881 ICE->getSubExpr(),
4882 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004883 // Get the new text.
4884 std::string SStr;
4885 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004886 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004887 const std::string &Str = Buf.str();
4888
4889 printf("CAST = %s\n", &Str[0]);
4890 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4891 delete S;
4892 return Replacement;
4893 }
4894#endif
4895 // Return this stmt unmodified.
4896 return S;
4897}
4898
Steve Naroff3d7e7862009-12-05 15:55:59 +00004899void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4900 for (RecordDecl::field_iterator i = RD->field_begin(),
4901 e = RD->field_end(); i != e; ++i) {
4902 FieldDecl *FD = *i;
4903 if (isTopLevelBlockPointerType(FD->getType()))
4904 RewriteBlockPointerDecl(FD);
4905 if (FD->getType()->isObjCQualifiedIdType() ||
4906 FD->getType()->isObjCQualifiedInterfaceType())
4907 RewriteObjCQualifiedInterfaceTypes(FD);
4908 }
4909}
4910
Steve Narofffa15fd92008-10-28 20:29:00 +00004911/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4912/// main file of the input.
4913void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004914 switch (D->getKind()) {
4915 case Decl::Function: {
4916 FunctionDecl *FD = cast<FunctionDecl>(D);
4917 if (FD->isOverloadedOperator())
4918 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004920 // Since function prototypes don't have ParmDecl's, we check the function
4921 // prototype. This enables us to rewrite function declarations and
4922 // definitions using the same code.
4923 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004924
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004925 // FIXME: If this should support Obj-C++, support CXXTryStmt
4926 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4927 CurFunctionDef = FD;
4928 CurFunctionDeclToDeclareForBlock = FD;
4929 CurrentBody = Body;
4930 Body =
4931 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4932 FD->setBody(Body);
4933 CurrentBody = 0;
4934 if (PropParentMap) {
4935 delete PropParentMap;
4936 PropParentMap = 0;
4937 }
4938 // This synthesizes and inserts the block "impl" struct, invoke function,
4939 // and any copy/dispose helper functions.
4940 InsertBlockLiteralsWithinFunction(FD);
4941 CurFunctionDef = 0;
4942 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004943 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004944 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004945 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004946 case Decl::ObjCMethod: {
4947 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4948 if (CompoundStmt *Body = MD->getCompoundBody()) {
4949 CurMethodDef = MD;
4950 CurrentBody = Body;
4951 Body =
4952 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4953 MD->setBody(Body);
4954 CurrentBody = 0;
4955 if (PropParentMap) {
4956 delete PropParentMap;
4957 PropParentMap = 0;
4958 }
4959 InsertBlockLiteralsWithinMethod(MD);
4960 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004961 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004962 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004963 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004964 case Decl::ObjCImplementation: {
4965 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4966 ClassImplementation.push_back(CI);
4967 break;
4968 }
4969 case Decl::ObjCCategoryImpl: {
4970 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4971 CategoryImplementation.push_back(CI);
4972 break;
4973 }
4974 case Decl::Var: {
4975 VarDecl *VD = cast<VarDecl>(D);
4976 RewriteObjCQualifiedInterfaceTypes(VD);
4977 if (isTopLevelBlockPointerType(VD->getType()))
4978 RewriteBlockPointerDecl(VD);
4979 else if (VD->getType()->isFunctionPointerType()) {
4980 CheckFunctionPointerDecl(VD->getType(), VD);
4981 if (VD->getInit()) {
4982 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4983 RewriteCastExpr(CE);
4984 }
4985 }
4986 } else if (VD->getType()->isRecordType()) {
4987 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4988 if (RD->isCompleteDefinition())
4989 RewriteRecordBody(RD);
4990 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004991 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004992 GlobalVarDecl = VD;
4993 CurrentBody = VD->getInit();
4994 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4995 CurrentBody = 0;
4996 if (PropParentMap) {
4997 delete PropParentMap;
4998 PropParentMap = 0;
4999 }
5000 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5001 GlobalVarDecl = 0;
5002
5003 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005004 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005005 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005006 }
5007 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005008 break;
5009 }
5010 case Decl::TypeAlias:
5011 case Decl::Typedef: {
5012 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5013 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5014 RewriteBlockPointerDecl(TD);
5015 else if (TD->getUnderlyingType()->isFunctionPointerType())
5016 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5017 }
5018 break;
5019 }
5020 case Decl::CXXRecord:
5021 case Decl::Record: {
5022 RecordDecl *RD = cast<RecordDecl>(D);
5023 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005024 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005025 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005026 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005027 default:
5028 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005029 }
5030 // Nothing yet.
5031}
5032
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005033void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005034 if (Diags.hasErrorOccurred())
5035 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005036
Steve Narofffa15fd92008-10-28 20:29:00 +00005037 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005038
Steve Naroff621edce2009-04-29 16:37:50 +00005039 // Here's a great place to add any extra declarations that may be needed.
5040 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005041 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005042 E = ProtocolExprDecls.end(); I != E; ++I)
5043 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5044
Benjamin Kramerd999b372010-02-14 14:14:16 +00005045 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005046 if (ClassImplementation.size() || CategoryImplementation.size())
5047 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005048
Steve Narofffa15fd92008-10-28 20:29:00 +00005049 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5050 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005051 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005052 Rewrite.getRewriteBufferFor(MainFileID)) {
5053 //printf("Changed:\n");
5054 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5055 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005056 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005057 }
Steve Narofface66252008-11-13 20:07:04 +00005058
Steve Naroff621edce2009-04-29 16:37:50 +00005059 if (ClassImplementation.size() || CategoryImplementation.size() ||
5060 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005061 // Rewrite Objective-c meta data*
5062 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005063 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005064 // Emit metadata.
5065 *OutFile << ResultStr;
5066 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005067 OutFile->flush();
5068}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005069
5070void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5071 InitializeCommon(context);
5072
5073 // declaring objc_selector outside the parameter list removes a silly
5074 // scope related warning...
5075 if (IsHeader)
5076 Preamble = "#pragma once\n";
5077 Preamble += "struct objc_selector; struct objc_class;\n";
5078 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5079 Preamble += "struct objc_object *superClass; ";
5080 if (LangOpts.MicrosoftExt) {
5081 // Add a constructor for creating temporary objects.
5082 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5083 ": ";
5084 Preamble += "object(o), superClass(s) {} ";
5085 }
5086 Preamble += "};\n";
5087 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5088 Preamble += "typedef struct objc_object Protocol;\n";
5089 Preamble += "#define _REWRITER_typedef_Protocol\n";
5090 Preamble += "#endif\n";
5091 if (LangOpts.MicrosoftExt) {
5092 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5093 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5094 } else
5095 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5097 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5099 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5101 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5103 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5105 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5106 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5107 Preamble += "(const char *);\n";
5108 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5109 Preamble += "(struct objc_class *);\n";
5110 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5111 Preamble += "(const char *);\n";
5112 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5114 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5115 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5116 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5117 Preamble += "(struct objc_class *, struct objc_object *);\n";
5118 // @synchronized hooks.
5119 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5120 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5121 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5122 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5123 Preamble += "struct __objcFastEnumerationState {\n\t";
5124 Preamble += "unsigned long state;\n\t";
5125 Preamble += "void **itemsPtr;\n\t";
5126 Preamble += "unsigned long *mutationsPtr;\n\t";
5127 Preamble += "unsigned long extra[5];\n};\n";
5128 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5129 Preamble += "#define __FASTENUMERATIONSTATE\n";
5130 Preamble += "#endif\n";
5131 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5132 Preamble += "struct __NSConstantStringImpl {\n";
5133 Preamble += " int *isa;\n";
5134 Preamble += " int flags;\n";
5135 Preamble += " char *str;\n";
5136 Preamble += " long length;\n";
5137 Preamble += "};\n";
5138 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5139 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5140 Preamble += "#else\n";
5141 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5142 Preamble += "#endif\n";
5143 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5144 Preamble += "#endif\n";
5145 // Blocks preamble.
5146 Preamble += "#ifndef BLOCK_IMPL\n";
5147 Preamble += "#define BLOCK_IMPL\n";
5148 Preamble += "struct __block_impl {\n";
5149 Preamble += " void *isa;\n";
5150 Preamble += " int Flags;\n";
5151 Preamble += " int Reserved;\n";
5152 Preamble += " void *FuncPtr;\n";
5153 Preamble += "};\n";
5154 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5155 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5156 Preamble += "extern \"C\" __declspec(dllexport) "
5157 "void _Block_object_assign(void *, const void *, const int);\n";
5158 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5159 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5160 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5161 Preamble += "#else\n";
5162 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5163 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5164 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5165 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5166 Preamble += "#endif\n";
5167 Preamble += "#endif\n";
5168 if (LangOpts.MicrosoftExt) {
5169 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5170 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5171 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5172 Preamble += "#define __attribute__(X)\n";
5173 Preamble += "#endif\n";
5174 Preamble += "#define __weak\n";
5175 }
5176 else {
5177 Preamble += "#define __block\n";
5178 Preamble += "#define __weak\n";
5179 }
5180 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5181 // as this avoids warning in any 64bit/32bit compilation model.
5182 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5183}
5184
5185/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5186/// ivar offset.
5187void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5188 std::string &Result) {
5189 if (ivar->isBitField()) {
5190 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5191 // place all bitfields at offset 0.
5192 Result += "0";
5193 } else {
5194 Result += "__OFFSETOFIVAR__(struct ";
5195 Result += ivar->getContainingInterface()->getNameAsString();
5196 if (LangOpts.MicrosoftExt)
5197 Result += "_IMPL";
5198 Result += ", ";
5199 Result += ivar->getNameAsString();
5200 Result += ")";
5201 }
5202}
5203
5204/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5205void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5206 ObjCProtocolDecl *PDecl, StringRef prefix,
5207 StringRef ClassName, std::string &Result) {
5208 static bool objc_protocol_methods = false;
5209
5210 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005211 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005212 /* struct protocol_methods {
5213 SEL _cmd;
5214 char *method_types;
5215 }
5216 */
5217 Result += "\nstruct _protocol_methods {\n";
5218 Result += "\tstruct objc_selector *_cmd;\n";
5219 Result += "\tchar *method_types;\n";
5220 Result += "};\n";
5221
5222 objc_protocol_methods = true;
5223 }
5224 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005225 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005226 return;
5227
Douglas Gregor61cc2962012-01-02 02:00:30 +00005228 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5229 PDecl = Def;
5230
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005231 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5232 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5233 PDecl->instmeth_end());
5234 /* struct _objc_protocol_method_list {
5235 int protocol_method_count;
5236 struct protocol_methods protocols[];
5237 }
5238 */
5239 Result += "\nstatic struct {\n";
5240 Result += "\tint protocol_method_count;\n";
5241 Result += "\tstruct _protocol_methods protocol_methods[";
5242 Result += utostr(NumMethods);
5243 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5244 Result += PDecl->getNameAsString();
5245 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5246 "{\n\t" + utostr(NumMethods) + "\n";
5247
5248 // Output instance methods declared in this protocol.
5249 for (ObjCProtocolDecl::instmeth_iterator
5250 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5251 I != E; ++I) {
5252 if (I == PDecl->instmeth_begin())
5253 Result += "\t ,{{(struct objc_selector *)\"";
5254 else
5255 Result += "\t ,{(struct objc_selector *)\"";
5256 Result += (*I)->getSelector().getAsString();
5257 std::string MethodTypeString;
5258 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5259 Result += "\", \"";
5260 Result += MethodTypeString;
5261 Result += "\"}\n";
5262 }
5263 Result += "\t }\n};\n";
5264 }
5265
5266 // Output class methods declared in this protocol.
5267 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5268 PDecl->classmeth_end());
5269 if (NumMethods > 0) {
5270 /* struct _objc_protocol_method_list {
5271 int protocol_method_count;
5272 struct protocol_methods protocols[];
5273 }
5274 */
5275 Result += "\nstatic struct {\n";
5276 Result += "\tint protocol_method_count;\n";
5277 Result += "\tstruct _protocol_methods protocol_methods[";
5278 Result += utostr(NumMethods);
5279 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5280 Result += PDecl->getNameAsString();
5281 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5282 "{\n\t";
5283 Result += utostr(NumMethods);
5284 Result += "\n";
5285
5286 // Output instance methods declared in this protocol.
5287 for (ObjCProtocolDecl::classmeth_iterator
5288 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5289 I != E; ++I) {
5290 if (I == PDecl->classmeth_begin())
5291 Result += "\t ,{{(struct objc_selector *)\"";
5292 else
5293 Result += "\t ,{(struct objc_selector *)\"";
5294 Result += (*I)->getSelector().getAsString();
5295 std::string MethodTypeString;
5296 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5297 Result += "\", \"";
5298 Result += MethodTypeString;
5299 Result += "\"}\n";
5300 }
5301 Result += "\t }\n};\n";
5302 }
5303
5304 // Output:
5305 /* struct _objc_protocol {
5306 // Objective-C 1.0 extensions
5307 struct _objc_protocol_extension *isa;
5308 char *protocol_name;
5309 struct _objc_protocol **protocol_list;
5310 struct _objc_protocol_method_list *instance_methods;
5311 struct _objc_protocol_method_list *class_methods;
5312 };
5313 */
5314 static bool objc_protocol = false;
5315 if (!objc_protocol) {
5316 Result += "\nstruct _objc_protocol {\n";
5317 Result += "\tstruct _objc_protocol_extension *isa;\n";
5318 Result += "\tchar *protocol_name;\n";
5319 Result += "\tstruct _objc_protocol **protocol_list;\n";
5320 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5321 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5322 Result += "};\n";
5323
5324 objc_protocol = true;
5325 }
5326
5327 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5328 Result += PDecl->getNameAsString();
5329 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5330 "{\n\t0, \"";
5331 Result += PDecl->getNameAsString();
5332 Result += "\", 0, ";
5333 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5334 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5335 Result += PDecl->getNameAsString();
5336 Result += ", ";
5337 }
5338 else
5339 Result += "0, ";
5340 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5341 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5342 Result += PDecl->getNameAsString();
5343 Result += "\n";
5344 }
5345 else
5346 Result += "0\n";
5347 Result += "};\n";
5348
5349 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005350 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005351 llvm_unreachable("protocol already synthesized");
5352
5353}
5354
5355void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5356 const ObjCList<ObjCProtocolDecl> &Protocols,
5357 StringRef prefix, StringRef ClassName,
5358 std::string &Result) {
5359 if (Protocols.empty()) return;
5360
5361 for (unsigned i = 0; i != Protocols.size(); i++)
5362 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5363
5364 // Output the top lovel protocol meta-data for the class.
5365 /* struct _objc_protocol_list {
5366 struct _objc_protocol_list *next;
5367 int protocol_count;
5368 struct _objc_protocol *class_protocols[];
5369 }
5370 */
5371 Result += "\nstatic struct {\n";
5372 Result += "\tstruct _objc_protocol_list *next;\n";
5373 Result += "\tint protocol_count;\n";
5374 Result += "\tstruct _objc_protocol *class_protocols[";
5375 Result += utostr(Protocols.size());
5376 Result += "];\n} _OBJC_";
5377 Result += prefix;
5378 Result += "_PROTOCOLS_";
5379 Result += ClassName;
5380 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5381 "{\n\t0, ";
5382 Result += utostr(Protocols.size());
5383 Result += "\n";
5384
5385 Result += "\t,{&_OBJC_PROTOCOL_";
5386 Result += Protocols[0]->getNameAsString();
5387 Result += " \n";
5388
5389 for (unsigned i = 1; i != Protocols.size(); i++) {
5390 Result += "\t ,&_OBJC_PROTOCOL_";
5391 Result += Protocols[i]->getNameAsString();
5392 Result += "\n";
5393 }
5394 Result += "\t }\n};\n";
5395}
5396
5397void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5398 std::string &Result) {
5399 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5400
5401 // Explicitly declared @interface's are already synthesized.
5402 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005403 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005404 // produce correct synthesis as yet.
5405 RewriteObjCInternalStruct(CDecl, Result);
5406 }
5407
5408 // Build _objc_ivar_list metadata for classes ivars if needed
5409 unsigned NumIvars = !IDecl->ivar_empty()
5410 ? IDecl->ivar_size()
5411 : (CDecl ? CDecl->ivar_size() : 0);
5412 if (NumIvars > 0) {
5413 static bool objc_ivar = false;
5414 if (!objc_ivar) {
5415 /* struct _objc_ivar {
5416 char *ivar_name;
5417 char *ivar_type;
5418 int ivar_offset;
5419 };
5420 */
5421 Result += "\nstruct _objc_ivar {\n";
5422 Result += "\tchar *ivar_name;\n";
5423 Result += "\tchar *ivar_type;\n";
5424 Result += "\tint ivar_offset;\n";
5425 Result += "};\n";
5426
5427 objc_ivar = true;
5428 }
5429
5430 /* struct {
5431 int ivar_count;
5432 struct _objc_ivar ivar_list[nIvars];
5433 };
5434 */
5435 Result += "\nstatic struct {\n";
5436 Result += "\tint ivar_count;\n";
5437 Result += "\tstruct _objc_ivar ivar_list[";
5438 Result += utostr(NumIvars);
5439 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5440 Result += IDecl->getNameAsString();
5441 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5442 "{\n\t";
5443 Result += utostr(NumIvars);
5444 Result += "\n";
5445
5446 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5447 SmallVector<ObjCIvarDecl *, 8> IVars;
5448 if (!IDecl->ivar_empty()) {
5449 for (ObjCInterfaceDecl::ivar_iterator
5450 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5451 IV != IVEnd; ++IV)
5452 IVars.push_back(*IV);
5453 IVI = IDecl->ivar_begin();
5454 IVE = IDecl->ivar_end();
5455 } else {
5456 IVI = CDecl->ivar_begin();
5457 IVE = CDecl->ivar_end();
5458 }
5459 Result += "\t,{{\"";
5460 Result += (*IVI)->getNameAsString();
5461 Result += "\", \"";
5462 std::string TmpString, StrEncoding;
5463 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5464 QuoteDoublequotes(TmpString, StrEncoding);
5465 Result += StrEncoding;
5466 Result += "\", ";
5467 RewriteIvarOffsetComputation(*IVI, Result);
5468 Result += "}\n";
5469 for (++IVI; IVI != IVE; ++IVI) {
5470 Result += "\t ,{\"";
5471 Result += (*IVI)->getNameAsString();
5472 Result += "\", \"";
5473 std::string TmpString, StrEncoding;
5474 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5475 QuoteDoublequotes(TmpString, StrEncoding);
5476 Result += StrEncoding;
5477 Result += "\", ";
5478 RewriteIvarOffsetComputation((*IVI), Result);
5479 Result += "}\n";
5480 }
5481
5482 Result += "\t }\n};\n";
5483 }
5484
5485 // Build _objc_method_list for class's instance methods if needed
5486 SmallVector<ObjCMethodDecl *, 32>
5487 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5488
5489 // If any of our property implementations have associated getters or
5490 // setters, produce metadata for them as well.
5491 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5492 PropEnd = IDecl->propimpl_end();
5493 Prop != PropEnd; ++Prop) {
5494 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5495 continue;
5496 if (!(*Prop)->getPropertyIvarDecl())
5497 continue;
5498 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5499 if (!PD)
5500 continue;
5501 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5502 if (!Getter->isDefined())
5503 InstanceMethods.push_back(Getter);
5504 if (PD->isReadOnly())
5505 continue;
5506 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5507 if (!Setter->isDefined())
5508 InstanceMethods.push_back(Setter);
5509 }
5510 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5511 true, "", IDecl->getName(), Result);
5512
5513 // Build _objc_method_list for class's class methods if needed
5514 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5515 false, "", IDecl->getName(), Result);
5516
5517 // Protocols referenced in class declaration?
5518 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5519 "CLASS", CDecl->getName(), Result);
5520
5521 // Declaration of class/meta-class metadata
5522 /* struct _objc_class {
5523 struct _objc_class *isa; // or const char *root_class_name when metadata
5524 const char *super_class_name;
5525 char *name;
5526 long version;
5527 long info;
5528 long instance_size;
5529 struct _objc_ivar_list *ivars;
5530 struct _objc_method_list *methods;
5531 struct objc_cache *cache;
5532 struct objc_protocol_list *protocols;
5533 const char *ivar_layout;
5534 struct _objc_class_ext *ext;
5535 };
5536 */
5537 static bool objc_class = false;
5538 if (!objc_class) {
5539 Result += "\nstruct _objc_class {\n";
5540 Result += "\tstruct _objc_class *isa;\n";
5541 Result += "\tconst char *super_class_name;\n";
5542 Result += "\tchar *name;\n";
5543 Result += "\tlong version;\n";
5544 Result += "\tlong info;\n";
5545 Result += "\tlong instance_size;\n";
5546 Result += "\tstruct _objc_ivar_list *ivars;\n";
5547 Result += "\tstruct _objc_method_list *methods;\n";
5548 Result += "\tstruct objc_cache *cache;\n";
5549 Result += "\tstruct _objc_protocol_list *protocols;\n";
5550 Result += "\tconst char *ivar_layout;\n";
5551 Result += "\tstruct _objc_class_ext *ext;\n";
5552 Result += "};\n";
5553 objc_class = true;
5554 }
5555
5556 // Meta-class metadata generation.
5557 ObjCInterfaceDecl *RootClass = 0;
5558 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5559 while (SuperClass) {
5560 RootClass = SuperClass;
5561 SuperClass = SuperClass->getSuperClass();
5562 }
5563 SuperClass = CDecl->getSuperClass();
5564
5565 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5566 Result += CDecl->getNameAsString();
5567 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5568 "{\n\t(struct _objc_class *)\"";
5569 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5570 Result += "\"";
5571
5572 if (SuperClass) {
5573 Result += ", \"";
5574 Result += SuperClass->getNameAsString();
5575 Result += "\", \"";
5576 Result += CDecl->getNameAsString();
5577 Result += "\"";
5578 }
5579 else {
5580 Result += ", 0, \"";
5581 Result += CDecl->getNameAsString();
5582 Result += "\"";
5583 }
5584 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5585 // 'info' field is initialized to CLS_META(2) for metaclass
5586 Result += ", 0,2, sizeof(struct _objc_class), 0";
5587 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5588 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5589 Result += IDecl->getNameAsString();
5590 Result += "\n";
5591 }
5592 else
5593 Result += ", 0\n";
5594 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5595 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5596 Result += CDecl->getNameAsString();
5597 Result += ",0,0\n";
5598 }
5599 else
5600 Result += "\t,0,0,0,0\n";
5601 Result += "};\n";
5602
5603 // class metadata generation.
5604 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5605 Result += CDecl->getNameAsString();
5606 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5607 "{\n\t&_OBJC_METACLASS_";
5608 Result += CDecl->getNameAsString();
5609 if (SuperClass) {
5610 Result += ", \"";
5611 Result += SuperClass->getNameAsString();
5612 Result += "\", \"";
5613 Result += CDecl->getNameAsString();
5614 Result += "\"";
5615 }
5616 else {
5617 Result += ", 0, \"";
5618 Result += CDecl->getNameAsString();
5619 Result += "\"";
5620 }
5621 // 'info' field is initialized to CLS_CLASS(1) for class
5622 Result += ", 0,1";
5623 if (!ObjCSynthesizedStructs.count(CDecl))
5624 Result += ",0";
5625 else {
5626 // class has size. Must synthesize its size.
5627 Result += ",sizeof(struct ";
5628 Result += CDecl->getNameAsString();
5629 if (LangOpts.MicrosoftExt)
5630 Result += "_IMPL";
5631 Result += ")";
5632 }
5633 if (NumIvars > 0) {
5634 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5635 Result += CDecl->getNameAsString();
5636 Result += "\n\t";
5637 }
5638 else
5639 Result += ",0";
5640 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5641 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5642 Result += CDecl->getNameAsString();
5643 Result += ", 0\n\t";
5644 }
5645 else
5646 Result += ",0,0";
5647 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5648 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5649 Result += CDecl->getNameAsString();
5650 Result += ", 0,0\n";
5651 }
5652 else
5653 Result += ",0,0,0\n";
5654 Result += "};\n";
5655}
5656
5657void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5658 int ClsDefCount = ClassImplementation.size();
5659 int CatDefCount = CategoryImplementation.size();
5660
5661 // For each implemented class, write out all its meta data.
5662 for (int i = 0; i < ClsDefCount; i++)
5663 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5664
5665 // For each implemented category, write out all its meta data.
5666 for (int i = 0; i < CatDefCount; i++)
5667 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5668
5669 // Write objc_symtab metadata
5670 /*
5671 struct _objc_symtab
5672 {
5673 long sel_ref_cnt;
5674 SEL *refs;
5675 short cls_def_cnt;
5676 short cat_def_cnt;
5677 void *defs[cls_def_cnt + cat_def_cnt];
5678 };
5679 */
5680
5681 Result += "\nstruct _objc_symtab {\n";
5682 Result += "\tlong sel_ref_cnt;\n";
5683 Result += "\tSEL *refs;\n";
5684 Result += "\tshort cls_def_cnt;\n";
5685 Result += "\tshort cat_def_cnt;\n";
5686 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5687 Result += "};\n\n";
5688
5689 Result += "static struct _objc_symtab "
5690 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5691 Result += "\t0, 0, " + utostr(ClsDefCount)
5692 + ", " + utostr(CatDefCount) + "\n";
5693 for (int i = 0; i < ClsDefCount; i++) {
5694 Result += "\t,&_OBJC_CLASS_";
5695 Result += ClassImplementation[i]->getNameAsString();
5696 Result += "\n";
5697 }
5698
5699 for (int i = 0; i < CatDefCount; i++) {
5700 Result += "\t,&_OBJC_CATEGORY_";
5701 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5702 Result += "_";
5703 Result += CategoryImplementation[i]->getNameAsString();
5704 Result += "\n";
5705 }
5706
5707 Result += "};\n\n";
5708
5709 // Write objc_module metadata
5710
5711 /*
5712 struct _objc_module {
5713 long version;
5714 long size;
5715 const char *name;
5716 struct _objc_symtab *symtab;
5717 }
5718 */
5719
5720 Result += "\nstruct _objc_module {\n";
5721 Result += "\tlong version;\n";
5722 Result += "\tlong size;\n";
5723 Result += "\tconst char *name;\n";
5724 Result += "\tstruct _objc_symtab *symtab;\n";
5725 Result += "};\n\n";
5726 Result += "static struct _objc_module "
5727 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5728 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5729 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5730 Result += "};\n\n";
5731
5732 if (LangOpts.MicrosoftExt) {
5733 if (ProtocolExprDecls.size()) {
5734 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5735 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5736 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5737 E = ProtocolExprDecls.end(); I != E; ++I) {
5738 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5739 Result += (*I)->getNameAsString();
5740 Result += " = &_OBJC_PROTOCOL_";
5741 Result += (*I)->getNameAsString();
5742 Result += ";\n";
5743 }
5744 Result += "#pragma data_seg(pop)\n\n";
5745 }
5746 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5747 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5748 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5749 Result += "&_OBJC_MODULES;\n";
5750 Result += "#pragma data_seg(pop)\n\n";
5751 }
5752}
5753
5754/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5755/// implementation.
5756void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5757 std::string &Result) {
5758 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5759 // Find category declaration for this implementation.
5760 ObjCCategoryDecl *CDecl;
5761 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5762 CDecl = CDecl->getNextClassCategory())
5763 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5764 break;
5765
5766 std::string FullCategoryName = ClassDecl->getNameAsString();
5767 FullCategoryName += '_';
5768 FullCategoryName += IDecl->getNameAsString();
5769
5770 // Build _objc_method_list for class's instance methods if needed
5771 SmallVector<ObjCMethodDecl *, 32>
5772 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5773
5774 // If any of our property implementations have associated getters or
5775 // setters, produce metadata for them as well.
5776 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5777 PropEnd = IDecl->propimpl_end();
5778 Prop != PropEnd; ++Prop) {
5779 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5780 continue;
5781 if (!(*Prop)->getPropertyIvarDecl())
5782 continue;
5783 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5784 if (!PD)
5785 continue;
5786 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5787 InstanceMethods.push_back(Getter);
5788 if (PD->isReadOnly())
5789 continue;
5790 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5791 InstanceMethods.push_back(Setter);
5792 }
5793 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5794 true, "CATEGORY_", FullCategoryName.c_str(),
5795 Result);
5796
5797 // Build _objc_method_list for class's class methods if needed
5798 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5799 false, "CATEGORY_", FullCategoryName.c_str(),
5800 Result);
5801
5802 // Protocols referenced in class declaration?
5803 // Null CDecl is case of a category implementation with no category interface
5804 if (CDecl)
5805 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5806 FullCategoryName, Result);
5807 /* struct _objc_category {
5808 char *category_name;
5809 char *class_name;
5810 struct _objc_method_list *instance_methods;
5811 struct _objc_method_list *class_methods;
5812 struct _objc_protocol_list *protocols;
5813 // Objective-C 1.0 extensions
5814 uint32_t size; // sizeof (struct _objc_category)
5815 struct _objc_property_list *instance_properties; // category's own
5816 // @property decl.
5817 };
5818 */
5819
5820 static bool objc_category = false;
5821 if (!objc_category) {
5822 Result += "\nstruct _objc_category {\n";
5823 Result += "\tchar *category_name;\n";
5824 Result += "\tchar *class_name;\n";
5825 Result += "\tstruct _objc_method_list *instance_methods;\n";
5826 Result += "\tstruct _objc_method_list *class_methods;\n";
5827 Result += "\tstruct _objc_protocol_list *protocols;\n";
5828 Result += "\tunsigned int size;\n";
5829 Result += "\tstruct _objc_property_list *instance_properties;\n";
5830 Result += "};\n";
5831 objc_category = true;
5832 }
5833 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5834 Result += FullCategoryName;
5835 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5836 Result += IDecl->getNameAsString();
5837 Result += "\"\n\t, \"";
5838 Result += ClassDecl->getNameAsString();
5839 Result += "\"\n";
5840
5841 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5842 Result += "\t, (struct _objc_method_list *)"
5843 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5844 Result += FullCategoryName;
5845 Result += "\n";
5846 }
5847 else
5848 Result += "\t, 0\n";
5849 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5850 Result += "\t, (struct _objc_method_list *)"
5851 "&_OBJC_CATEGORY_CLASS_METHODS_";
5852 Result += FullCategoryName;
5853 Result += "\n";
5854 }
5855 else
5856 Result += "\t, 0\n";
5857
5858 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5859 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5860 Result += FullCategoryName;
5861 Result += "\n";
5862 }
5863 else
5864 Result += "\t, 0\n";
5865 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5866}
5867
5868// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5869/// class methods.
5870template<typename MethodIterator>
5871void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5872 MethodIterator MethodEnd,
5873 bool IsInstanceMethod,
5874 StringRef prefix,
5875 StringRef ClassName,
5876 std::string &Result) {
5877 if (MethodBegin == MethodEnd) return;
5878
5879 if (!objc_impl_method) {
5880 /* struct _objc_method {
5881 SEL _cmd;
5882 char *method_types;
5883 void *_imp;
5884 }
5885 */
5886 Result += "\nstruct _objc_method {\n";
5887 Result += "\tSEL _cmd;\n";
5888 Result += "\tchar *method_types;\n";
5889 Result += "\tvoid *_imp;\n";
5890 Result += "};\n";
5891
5892 objc_impl_method = true;
5893 }
5894
5895 // Build _objc_method_list for class's methods if needed
5896
5897 /* struct {
5898 struct _objc_method_list *next_method;
5899 int method_count;
5900 struct _objc_method method_list[];
5901 }
5902 */
5903 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5904 Result += "\nstatic struct {\n";
5905 Result += "\tstruct _objc_method_list *next_method;\n";
5906 Result += "\tint method_count;\n";
5907 Result += "\tstruct _objc_method method_list[";
5908 Result += utostr(NumMethods);
5909 Result += "];\n} _OBJC_";
5910 Result += prefix;
5911 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5912 Result += "_METHODS_";
5913 Result += ClassName;
5914 Result += " __attribute__ ((used, section (\"__OBJC, __";
5915 Result += IsInstanceMethod ? "inst" : "cls";
5916 Result += "_meth\")))= ";
5917 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5918
5919 Result += "\t,{{(SEL)\"";
5920 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5921 std::string MethodTypeString;
5922 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5923 Result += "\", \"";
5924 Result += MethodTypeString;
5925 Result += "\", (void *)";
5926 Result += MethodInternalNames[*MethodBegin];
5927 Result += "}\n";
5928 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5929 Result += "\t ,{(SEL)\"";
5930 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5931 std::string MethodTypeString;
5932 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5933 Result += "\", \"";
5934 Result += MethodTypeString;
5935 Result += "\", (void *)";
5936 Result += MethodInternalNames[*MethodBegin];
5937 Result += "}\n";
5938 }
5939 Result += "\t }\n};\n";
5940}
5941
5942Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5943 SourceRange OldRange = IV->getSourceRange();
5944 Expr *BaseExpr = IV->getBase();
5945
5946 // Rewrite the base, but without actually doing replaces.
5947 {
5948 DisableReplaceStmtScope S(*this);
5949 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5950 IV->setBase(BaseExpr);
5951 }
5952
5953 ObjCIvarDecl *D = IV->getDecl();
5954
5955 Expr *Replacement = IV;
5956 if (CurMethodDef) {
5957 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5958 const ObjCInterfaceType *iFaceDecl =
5959 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5960 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5961 // lookup which class implements the instance variable.
5962 ObjCInterfaceDecl *clsDeclared = 0;
5963 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5964 clsDeclared);
5965 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5966
5967 // Synthesize an explicit cast to gain access to the ivar.
5968 std::string RecName = clsDeclared->getIdentifier()->getName();
5969 RecName += "_IMPL";
5970 IdentifierInfo *II = &Context->Idents.get(RecName);
5971 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5972 SourceLocation(), SourceLocation(),
5973 II);
5974 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5975 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5976 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5977 CK_BitCast,
5978 IV->getBase());
5979 // Don't forget the parens to enforce the proper binding.
5980 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5981 OldRange.getEnd(),
5982 castExpr);
5983 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005984 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005985 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5986 IV->getLocation(),
5987 D->getType(),
5988 VK_LValue, OK_Ordinary);
5989 Replacement = ME;
5990 } else {
5991 IV->setBase(PE);
5992 }
5993 }
5994 } else { // we are outside a method.
5995 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5996
5997 // Explicit ivar refs need to have a cast inserted.
5998 // FIXME: consider sharing some of this code with the code above.
5999 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6000 const ObjCInterfaceType *iFaceDecl =
6001 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6002 // lookup which class implements the instance variable.
6003 ObjCInterfaceDecl *clsDeclared = 0;
6004 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6005 clsDeclared);
6006 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6007
6008 // Synthesize an explicit cast to gain access to the ivar.
6009 std::string RecName = clsDeclared->getIdentifier()->getName();
6010 RecName += "_IMPL";
6011 IdentifierInfo *II = &Context->Idents.get(RecName);
6012 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6013 SourceLocation(), SourceLocation(),
6014 II);
6015 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6016 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6017 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6018 CK_BitCast,
6019 IV->getBase());
6020 // Don't forget the parens to enforce the proper binding.
6021 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6022 IV->getBase()->getLocEnd(), castExpr);
6023 // Cannot delete IV->getBase(), since PE points to it.
6024 // Replace the old base with the cast. This is important when doing
6025 // embedded rewrites. For example, [newInv->_container addObject:0].
6026 IV->setBase(PE);
6027 }
6028 }
6029
6030 ReplaceStmtWithRange(IV, Replacement, OldRange);
6031 return Replacement;
6032}
6033