blob: 4b41e5a445034416f76a9665d6ce2a92ed2cb732 [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
Chris Lattner682bf922009-03-29 16:50:03 +0000175 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000176 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000177 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000178 }
179 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000180 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000181 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000182 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000183 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000184
185 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000187 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000189 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000190 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Steve Naroff4c3580e2008-12-04 23:50:32 +0000192 if (ReplacingStmt)
193 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000194
Steve Naroffb619d952008-12-09 12:56:34 +0000195 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000196 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000197
Steve Naroff4c3580e2008-12-04 23:50:32 +0000198 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000199 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000200 ReplacedNodes[Old] = New;
201 return;
202 }
203 if (SilenceRewriteMacroWarning)
204 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000205 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
206 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000207 }
Steve Naroffb619d952008-12-09 12:56:34 +0000208
209 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000210 if (DisableReplaceStmt)
211 return;
212
Nick Lewycky7e749242010-10-31 21:07:24 +0000213 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000214 int Size = Rewrite.getRangeSize(SrcRange);
215 if (Size == -1) {
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 return;
219 }
220 // Get the new text.
221 std::string SStr;
222 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000223 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000224 const std::string &Str = S.str();
225
226 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000227 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000228 ReplacedNodes[Old] = New;
229 return;
230 }
231 if (SilenceRewriteMacroWarning)
232 return;
233 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
234 << Old->getSourceRange();
235 }
236
Chris Lattner5f9e2722011-07-23 10:55:15 +0000237 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000238 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000244 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000249 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000250 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000251 SilenceRewriteMacroWarning)
252 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattnerf04da132007-10-24 17:06:59 +0000257 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000258 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000259 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000260 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000261 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000262 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000263 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000264 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000265 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
266 ObjCImplementationDecl *IMD,
267 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000269 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000270 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
271 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000272 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
273 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000274 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000275 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000276 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
277 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
278 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
279 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000280 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000281 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000282 void RewriteBlockPointerType(std::string& Str, QualType Type);
283 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000284 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000285 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000286 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000287 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000288
Chris Lattnerf04da132007-10-24 17:06:59 +0000289 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000290 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000291 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000292 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
293 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000294 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000295 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000296 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000297 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000298 void RewriteTryReturnStmts(Stmt *S);
299 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000300 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000301 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000302 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000303 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
304 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000305 Stmt *RewriteBreakStmt(BreakStmt *S);
306 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000307 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000308
Steve Naroff54055232008-10-27 17:20:55 +0000309 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000310 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000311
Mike Stump1eb44332009-09-09 15:08:12 +0000312 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000313 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000314 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000315 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000316 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000317 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000318
319 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
320 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000321
322 virtual void Initialize(ASTContext &context) = 0;
323
324 // Metadata Rewriting.
325 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
326 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
327 StringRef prefix,
328 StringRef ClassName,
329 std::string &Result) = 0;
330 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
331 std::string &Result) = 0;
332 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
333 StringRef prefix,
334 StringRef ClassName,
335 std::string &Result) = 0;
336 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
337 std::string &Result) = 0;
338
339 // Rewriting ivar access
340 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
341 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
342 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000343
344 // Misc. AST transformation routines. Somtimes they end up calling
345 // rewriting routines on the new ASTs.
346 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
347 Expr **args, unsigned nargs,
348 SourceLocation StartLoc=SourceLocation(),
349 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
352 SourceLocation StartLoc=SourceLocation(),
353 SourceLocation EndLoc=SourceLocation());
354
355 void SynthCountByEnumWithState(std::string &buf);
356 void SynthMsgSendFunctionDecl();
357 void SynthMsgSendSuperFunctionDecl();
358 void SynthMsgSendStretFunctionDecl();
359 void SynthMsgSendFpretFunctionDecl();
360 void SynthMsgSendSuperStretFunctionDecl();
361 void SynthGetClassFunctionDecl();
362 void SynthGetMetaClassFunctionDecl();
363 void SynthGetSuperClassFunctionDecl();
364 void SynthSelGetUidFunctionDecl();
365 void SynthSuperContructorFunctionDecl();
366
367 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000368 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000369 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000370 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000371 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000372 std::string SynthesizeBlockImpl(BlockExpr *CE,
373 std::string Tag, std::string Desc);
374 std::string SynthesizeBlockDescriptor(std::string DescTag,
375 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000376 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000377 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000378 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000379 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000381 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
382 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
383 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Fariborz Jahanian58457172011-12-05 18:43:13 +0000385 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000386 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000387 void WarnAboutReturnGotoStmts(Stmt *S);
388 void HasReturnStmts(Stmt *S, bool &hasReturns);
389 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
390 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
391 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
392
393 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000397 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000406 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
407 /// to a function pointer type and upon success, returns true; false
408 /// otherwise.
409 bool convertBlockPointerToFunctionPointer(QualType &T) {
410 if (isTopLevelBlockPointerType(T)) {
411 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
412 T = Context->getPointerType(BPT->getPointeeType());
413 return true;
414 }
415 return false;
416 }
417
Fariborz Jahanian58457172011-12-05 18:43:13 +0000418 bool needToScanForQualifiers(QualType T);
419 QualType getSuperStructType();
420 QualType getConstantStringStructType();
421 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
422 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
423
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000424 void convertToUnqualifiedObjCType(QualType &T) {
425 if (T->isObjCQualifiedIdType())
426 T = Context->getObjCIdType();
427 else if (T->isObjCQualifiedClassType())
428 T = Context->getObjCClassType();
429 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000430 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
431 if (const ObjCObjectPointerType * OBJPT =
432 T->getAsObjCInterfacePointerType()) {
433 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
434 T = QualType(IFaceT, 0);
435 T = Context->getPointerType(T);
436 }
437 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000438 }
439
Steve Naroff54055232008-10-27 17:20:55 +0000440 // FIXME: This predicate seems like it would be useful to add to ASTContext.
441 bool isObjCType(QualType T) {
442 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
443 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Steve Naroff54055232008-10-27 17:20:55 +0000445 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Steve Naroff54055232008-10-27 17:20:55 +0000447 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
448 OCT == Context->getCanonicalType(Context->getObjCClassType()))
449 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Ted Kremenek6217b802009-07-29 21:53:49 +0000451 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000452 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000453 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000454 return true;
455 }
456 return false;
457 }
458 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000459 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000460 void GetExtentOfArgList(const char *Name, const char *&LParen,
461 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000462
Steve Naroff621edce2009-04-29 16:37:50 +0000463 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000464 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000465 if (From[i] == '"')
466 To += "\\\"";
467 else
468 To += From[i];
469 }
470 }
John McCalle23cf432010-12-14 08:05:40 +0000471
472 QualType getSimpleFunctionType(QualType result,
473 const QualType *args,
474 unsigned numArgs,
475 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000476 if (result == Context->getObjCInstanceType())
477 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000478 FunctionProtoType::ExtProtoInfo fpi;
479 fpi.Variadic = variadic;
480 return Context->getFunctionType(result, args, numArgs, fpi);
481 }
John McCall9d125032010-01-15 18:39:57 +0000482
Fariborz Jahanian58457172011-12-05 18:43:13 +0000483 // Helper function: create a CStyleCastExpr with trivial type source info.
484 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
485 CastKind Kind, Expr *E) {
486 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
487 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
488 SourceLocation(), SourceLocation());
489 }
490 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000491
492 class RewriteObjCFragileABI : public RewriteObjC {
493 public:
494
495 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
496 DiagnosticsEngine &D, const LangOptions &LOpts,
497 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
498 D, LOpts,
499 silenceMacroWarn) {}
500
501 ~RewriteObjCFragileABI() {}
502 virtual void Initialize(ASTContext &context);
503
504 // Rewriting metadata
505 template<typename MethodIterator>
506 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
507 MethodIterator MethodEnd,
508 bool IsInstanceMethod,
509 StringRef prefix,
510 StringRef ClassName,
511 std::string &Result);
512 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
513 StringRef prefix,
514 StringRef ClassName,
515 std::string &Result);
516 virtual void RewriteObjCProtocolListMetaData(
517 const ObjCList<ObjCProtocolDecl> &Prots,
518 StringRef prefix, StringRef ClassName, std::string &Result);
519 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
520 std::string &Result);
521 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
522 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
523 std::string &Result);
524
525 // Rewriting ivar
526 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
527 std::string &Result);
528 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
529 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000530}
531
Mike Stump1eb44332009-09-09 15:08:12 +0000532void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
533 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000534 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000535 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000536 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000537 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000538 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000539 // All the args are checked/rewritten. Don't call twice!
540 RewriteBlockPointerDecl(D);
541 break;
542 }
543 }
544}
545
546void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000547 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000548 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000549 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000550}
551
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000552static bool IsHeaderFile(const std::string &Filename) {
553 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000555 if (DotPos == std::string::npos) {
556 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000557 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000558 }
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000560 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
561 // C header: .h
562 // C++ header: .hh or .H;
563 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000564}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000565
Chris Lattner5f9e2722011-07-23 10:55:15 +0000566RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000567 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000568 bool silenceMacroWarn)
569 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
570 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000571 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000572 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000573 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000574 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
575 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000576 "rewriter doesn't support user-specified control flow semantics "
577 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000578}
579
Eli Friedmanbce831b2009-05-18 22:29:17 +0000580ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000581 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000582 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000583 const LangOptions &LOpts,
584 bool SilenceRewriteMacroWarning) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000585 if (true /*!LOpts.ObjCNonFragileABI*/)
586 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
587 else {
588 assert(false && "objective-C rewriter for nonfragile ABI = NYI");
589 return 0;
590 }
Chris Lattnere365c502007-11-30 22:25:36 +0000591}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000592
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000593void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000594 Context = &context;
595 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000596 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000597 MsgSendFunctionDecl = 0;
598 MsgSendSuperFunctionDecl = 0;
599 MsgSendStretFunctionDecl = 0;
600 MsgSendSuperStretFunctionDecl = 0;
601 MsgSendFpretFunctionDecl = 0;
602 GetClassFunctionDecl = 0;
603 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000604 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000605 SelGetUidFunctionDecl = 0;
606 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000607 ConstantStringClassReference = 0;
608 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000609 CurMethodDef = 0;
610 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000611 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000612 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000613 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000614 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000615 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000616 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000617 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000618 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000619 PropParentMap = 0;
620 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000621 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000622 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000624 // Get the ID and start/end of the main file.
625 MainFileID = SM->getMainFileID();
626 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
627 MainFileStart = MainBuf->getBufferStart();
628 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Chris Lattner2c78b872009-04-14 23:22:57 +0000630 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000631}
632
Chris Lattnerf04da132007-10-24 17:06:59 +0000633//===----------------------------------------------------------------------===//
634// Top Level Driver Code
635//===----------------------------------------------------------------------===//
636
Chris Lattner682bf922009-03-29 16:50:03 +0000637void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000638 if (Diags.hasErrorOccurred())
639 return;
640
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000641 // Two cases: either the decl could be in the main file, or it could be in a
642 // #included file. If the former, rewrite it now. If the later, check to see
643 // if we rewrote the #include/#import.
644 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000645 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000647 // If this is for a builtin, ignore it.
648 if (Loc.isInvalid()) return;
649
Steve Naroffebf2b562007-10-23 23:50:29 +0000650 // Look for built-in declarations that we need to refer during the rewrite.
651 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000652 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000653 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000654 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000655 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000656 ConstantStringClassReference = FVD;
657 return;
658 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000659 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
660 if (ID->isThisDeclarationADefinition())
661 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000663 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000664 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000665 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000666 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000667 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000668 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000669 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
670 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000671 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
672 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000673 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000674 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
675 if (!IFace->isThisDeclarationADefinition()) {
676 SmallVector<Decl *, 8> DG;
677 SourceLocation StartLoc = IFace->getLocStart();
678 do {
679 if (isa<ObjCInterfaceDecl>(*DI) &&
680 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
681 StartLoc == (*DI)->getLocStart())
682 DG.push_back(*DI);
683 else
684 break;
685
Douglas Gregor7723fec2011-12-15 20:29:51 +0000686 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000687 } while (DI != DIEnd);
688 RewriteForwardClassDecl(DG);
689 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000690 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000691 }
Chris Lattner682bf922009-03-29 16:50:03 +0000692 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000693 ++DI;
694 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000695 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000696 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000697 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000698 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000699}
700
Chris Lattnerf04da132007-10-24 17:06:59 +0000701//===----------------------------------------------------------------------===//
702// Syntactic (non-AST) Rewriting Code
703//===----------------------------------------------------------------------===//
704
Steve Naroffb29b4272008-04-14 22:03:09 +0000705void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000706 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000707 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000708 const char *MainBufStart = MainBuf.begin();
709 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000710 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000712 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000713 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
714 if (*BufPtr == '#') {
715 if (++BufPtr == MainBufEnd)
716 return;
717 while (*BufPtr == ' ' || *BufPtr == '\t')
718 if (++BufPtr == MainBufEnd)
719 return;
720 if (!strncmp(BufPtr, "import", ImportLen)) {
721 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000722 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000723 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000724 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000725 BufPtr += ImportLen;
726 }
727 }
728 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000729}
730
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000731static std::string getIvarAccessString(ObjCIvarDecl *OID) {
732 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000733 std::string S;
734 S = "((struct ";
735 S += ClassDecl->getIdentifier()->getName();
736 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000737 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000738 return S;
739}
740
Steve Naroffa0876e82008-12-02 17:36:43 +0000741void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
742 ObjCImplementationDecl *IMD,
743 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000744 static bool objcGetPropertyDefined = false;
745 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000746 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000747 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000748 const char *startBuf = SM->getCharacterData(startLoc);
749 assert((*startBuf == '@') && "bogus @synthesize location");
750 const char *semiBuf = strchr(startBuf, ';');
751 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000752 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000753 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754
755 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
756 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000762 if (!OID)
763 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000764 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000765 if (!PD->getGetterMethodDecl()->isDefined()) {
766 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
767 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
768 ObjCPropertyDecl::OBJC_PR_copy));
769 std::string Getr;
770 if (GenGetProperty && !objcGetPropertyDefined) {
771 objcGetPropertyDefined = true;
772 // FIXME. Is this attribute correct in all cases?
773 Getr = "\nextern \"C\" __declspec(dllimport) "
774 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000775 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000776 RewriteObjCMethodDecl(OID->getContainingInterface(),
777 PD->getGetterMethodDecl(), Getr);
778 Getr += "{ ";
779 // Synthesize an explicit cast to gain access to the ivar.
780 // See objc-act.c:objc_synthesize_new_getter() for details.
781 if (GenGetProperty) {
782 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
783 Getr += "typedef ";
784 const FunctionType *FPRetType = 0;
785 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
786 FPRetType);
787 Getr += " _TYPE";
788 if (FPRetType) {
789 Getr += ")"; // close the precedence "scope" for "*".
790
791 // Now, emit the argument types (if any).
792 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
793 Getr += "(";
794 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
795 if (i) Getr += ", ";
796 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000797 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000798 Getr += ParamStr;
799 }
800 if (FT->isVariadic()) {
801 if (FT->getNumArgs()) Getr += ", ";
802 Getr += "...";
803 }
804 Getr += ")";
805 } else
806 Getr += "()";
807 }
808 Getr += ";\n";
809 Getr += "return (_TYPE)";
810 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000811 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000812 Getr += ", 1)";
813 }
814 else
815 Getr += "return " + getIvarAccessString(OID);
816 Getr += "; }";
817 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000818 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000819
820 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000821 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Steve Naroffeb0646c2008-12-02 15:48:25 +0000823 // Generate the 'setter' function.
824 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000825 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
826 ObjCPropertyDecl::OBJC_PR_copy);
827 if (GenSetProperty && !objcSetPropertyDefined) {
828 objcSetPropertyDefined = true;
829 // FIXME. Is this attribute correct in all cases?
830 Setr = "\nextern \"C\" __declspec(dllimport) "
831 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
832 }
833
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000834 RewriteObjCMethodDecl(OID->getContainingInterface(),
835 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000836 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000837 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000838 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000839 if (GenSetProperty) {
840 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000841 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000842 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000843 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000844 Setr += ", ";
845 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
846 Setr += "0, ";
847 else
848 Setr += "1, ";
849 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
850 Setr += "1)";
851 else
852 Setr += "0)";
853 }
854 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000855 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000856 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000857 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000858 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000859 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000860}
Chris Lattner8a12c272007-10-11 18:38:32 +0000861
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000862static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
863 std::string &typedefString) {
864 typedefString += "#ifndef _REWRITER_typedef_";
865 typedefString += ForwardDecl->getNameAsString();
866 typedefString += "\n";
867 typedefString += "#define _REWRITER_typedef_";
868 typedefString += ForwardDecl->getNameAsString();
869 typedefString += "\n";
870 typedefString += "typedef struct objc_object ";
871 typedefString += ForwardDecl->getNameAsString();
872 typedefString += ";\n#endif\n";
873}
874
Douglas Gregor375bb142011-12-27 22:43:10 +0000875void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000876 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000877 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000878 const char *startBuf = SM->getCharacterData(startLoc);
879 const char *semiPtr = strchr(startBuf, ';');
880 // Replace the @class with typedefs corresponding to the classes.
881 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
882}
883
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000884void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000885 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000886 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000887 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000888 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000889 // Translate to typedef's that forward reference structs with the same name
890 // as the class. As a convenience, we include the original declaration
891 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000892 typedefString += "// @class ";
893 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000894 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000895 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000896 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000897 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000898 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000899 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000900}
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000902void RewriteObjC::RewriteForwardClassDecl(
903 const llvm::SmallVector<Decl*, 8> &D) {
904 std::string typedefString;
905 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000906 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000907 if (i == 0) {
908 typedefString += "// @class ";
909 typedefString += ForwardDecl->getNameAsString();
910 typedefString += ";\n";
911 }
912 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
913 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000914 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000915}
916
Steve Naroffb29b4272008-04-14 22:03:09 +0000917void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000918 // When method is a synthesized one, such as a getter/setter there is
919 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000920 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000921 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000922 SourceLocation LocStart = Method->getLocStart();
923 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000924
Chandler Carruth64211622011-07-25 21:09:52 +0000925 if (SM->getExpansionLineNumber(LocEnd) >
926 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 InsertText(LocStart, "#if 0\n");
928 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000929 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000931 }
932}
933
Mike Stump1eb44332009-09-09 15:08:12 +0000934void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000935 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Benjamin Kramerd999b372010-02-14 14:14:16 +0000937 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000938 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000939}
940
Steve Naroffb29b4272008-04-14 22:03:09 +0000941void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000942 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Steve Naroff423cb562007-10-30 13:30:57 +0000944 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000945 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000947 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
948 E = CatDecl->prop_end(); I != E; ++I)
949 RewriteProperty(*I);
950
Mike Stump1eb44332009-09-09 15:08:12 +0000951 for (ObjCCategoryDecl::instmeth_iterator
952 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000953 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000954 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000955 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000956 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000957 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000958 RewriteMethodDeclaration(*I);
959
Steve Naroff423cb562007-10-30 13:30:57 +0000960 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000961 ReplaceText(CatDecl->getAtEndRange().getBegin(),
962 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000963}
964
Steve Naroffb29b4272008-04-14 22:03:09 +0000965void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000966 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Steve Naroff752d6ef2007-10-30 16:42:30 +0000968 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000969 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000970
971 for (ObjCProtocolDecl::instmeth_iterator
972 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000973 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000974 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000975 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000976 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000977 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000978 RewriteMethodDeclaration(*I);
979
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000980 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
981 E = PDecl->prop_end(); I != E; ++I)
982 RewriteProperty(*I);
983
Steve Naroff752d6ef2007-10-30 16:42:30 +0000984 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000985 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000986 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000987
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000988 // Must comment out @optional/@required
989 const char *startBuf = SM->getCharacterData(LocStart);
990 const char *endBuf = SM->getCharacterData(LocEnd);
991 for (const char *p = startBuf; p < endBuf; p++) {
992 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000993 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 }
997 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000998 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001001 }
1002 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001003}
1004
Steve Naroffb29b4272008-04-14 22:03:09 +00001005void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001006 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001007 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001008 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001009 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001010 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001011}
1012
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001013void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001016 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001022 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001023 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001024 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001026 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001028 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001029 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001031 }
1032 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001033 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001034}
1035
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001036void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001043 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001045 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001046 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001048 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001053 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001054 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001055
1056 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001058 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001059 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001062 {
1063 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001068 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001073
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 // Rewrite arguments
1075 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001078 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001081 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001086 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001087 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 }
1089 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001091 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001093 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001094 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001101 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001104 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001105 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001106 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001110 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001111 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001112 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001113 ResultStr += Name;
1114 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001118 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Steve Naroff76e429d2008-07-16 14:40:40 +00001120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Steve Naroff76e429d2008-07-16 14:40:40 +00001123 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001128 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001129 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001142void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001151 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001157
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 }
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001163 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001166 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001167 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001176 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001177 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001180 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001181 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 }
1183
Benjamin Kramerd999b372010-02-14 14:14:16 +00001184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001185}
1186
Steve Naroffb29b4272008-04-14 22:03:09 +00001187void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001188 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001189 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001190 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001191 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001192 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001195 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001196 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001197 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001198 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001199 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001200 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001201 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001202 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001203 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001206 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001207 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001208 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001210 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001211 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001214 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001215 RewriteMethodDeclaration(*I);
1216
Steve Naroff2feac5e2007-10-30 03:43:13 +00001217 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001220}
1221
John McCall4b9c2d22011-11-06 09:01:30 +00001222Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1223 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001224
John McCall4b9c2d22011-11-06 09:01:30 +00001225 // We just magically know some things about the structure of this
1226 // expression.
1227 ObjCMessageExpr *OldMsg =
1228 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1229 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001230
John McCall4b9c2d22011-11-06 09:01:30 +00001231 // Because the rewriter doesn't allow us to rewrite rewritten code,
1232 // we need to suppress rewriting the sub-statements.
1233 Expr *Base, *RHS;
1234 {
1235 DisableReplaceStmtScope S(*this);
1236
1237 // Rebuild the base expression if we have one.
1238 Base = 0;
1239 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1240 Base = OldMsg->getInstanceReceiver();
1241 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1242 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1243 }
1244
1245 // Rebuild the RHS.
1246 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1247 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1248 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1249 }
1250
1251 // TODO: avoid this copy.
1252 SmallVector<SourceLocation, 1> SelLocs;
1253 OldMsg->getSelectorLocs(SelLocs);
1254
1255 ObjCMessageExpr *NewMsg;
1256 switch (OldMsg->getReceiverKind()) {
1257 case ObjCMessageExpr::Class:
1258 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1259 OldMsg->getValueKind(),
1260 OldMsg->getLeftLoc(),
1261 OldMsg->getClassReceiverTypeInfo(),
1262 OldMsg->getSelector(),
1263 SelLocs,
1264 OldMsg->getMethodDecl(),
1265 RHS,
1266 OldMsg->getRightLoc());
1267 break;
1268
1269 case ObjCMessageExpr::Instance:
1270 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1271 OldMsg->getValueKind(),
1272 OldMsg->getLeftLoc(),
1273 Base,
1274 OldMsg->getSelector(),
1275 SelLocs,
1276 OldMsg->getMethodDecl(),
1277 RHS,
1278 OldMsg->getRightLoc());
1279 break;
1280
1281 case ObjCMessageExpr::SuperClass:
1282 case ObjCMessageExpr::SuperInstance:
1283 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1284 OldMsg->getValueKind(),
1285 OldMsg->getLeftLoc(),
1286 OldMsg->getSuperLoc(),
1287 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1288 OldMsg->getSuperType(),
1289 OldMsg->getSelector(),
1290 SelLocs,
1291 OldMsg->getMethodDecl(),
1292 RHS,
1293 OldMsg->getRightLoc());
1294 break;
1295 }
1296
1297 Stmt *Replacement = SynthMessageExpr(NewMsg);
1298 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1299 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001300}
1301
John McCall4b9c2d22011-11-06 09:01:30 +00001302Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1303 SourceRange OldRange = PseudoOp->getSourceRange();
1304
1305 // We just magically know some things about the structure of this
1306 // expression.
1307 ObjCMessageExpr *OldMsg =
1308 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1309
1310 // Because the rewriter doesn't allow us to rewrite rewritten code,
1311 // we need to suppress rewriting the sub-statements.
1312 Expr *Base = 0;
1313 {
1314 DisableReplaceStmtScope S(*this);
1315
1316 // Rebuild the base expression if we have one.
1317 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1318 Base = OldMsg->getInstanceReceiver();
1319 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1320 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001321 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001322 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001323
John McCall4b9c2d22011-11-06 09:01:30 +00001324 // Intentionally empty.
1325 SmallVector<SourceLocation, 1> SelLocs;
1326 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001327
John McCall4b9c2d22011-11-06 09:01:30 +00001328 ObjCMessageExpr *NewMsg;
1329 switch (OldMsg->getReceiverKind()) {
1330 case ObjCMessageExpr::Class:
1331 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1332 OldMsg->getValueKind(),
1333 OldMsg->getLeftLoc(),
1334 OldMsg->getClassReceiverTypeInfo(),
1335 OldMsg->getSelector(),
1336 SelLocs,
1337 OldMsg->getMethodDecl(),
1338 Args,
1339 OldMsg->getRightLoc());
1340 break;
1341
1342 case ObjCMessageExpr::Instance:
1343 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1344 OldMsg->getValueKind(),
1345 OldMsg->getLeftLoc(),
1346 Base,
1347 OldMsg->getSelector(),
1348 SelLocs,
1349 OldMsg->getMethodDecl(),
1350 Args,
1351 OldMsg->getRightLoc());
1352 break;
1353
1354 case ObjCMessageExpr::SuperClass:
1355 case ObjCMessageExpr::SuperInstance:
1356 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1357 OldMsg->getValueKind(),
1358 OldMsg->getLeftLoc(),
1359 OldMsg->getSuperLoc(),
1360 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1361 OldMsg->getSuperType(),
1362 OldMsg->getSelector(),
1363 SelLocs,
1364 OldMsg->getMethodDecl(),
1365 Args,
1366 OldMsg->getRightLoc());
1367 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001368 }
John McCall4b9c2d22011-11-06 09:01:30 +00001369
1370 Stmt *Replacement = SynthMessageExpr(NewMsg);
1371 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1372 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001373}
1374
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001375/// SynthCountByEnumWithState - To print:
1376/// ((unsigned int (*)
1377/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001378/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001379/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001380/// "countByEnumeratingWithState:objects:count:"),
1381/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001382/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001383///
Steve Naroffb29b4272008-04-14 22:03:09 +00001384void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001385 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1386 "id *, unsigned int))(void *)objc_msgSend)";
1387 buf += "\n\t\t";
1388 buf += "((id)l_collection,\n\t\t";
1389 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1390 buf += "\n\t\t";
1391 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001392 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001393}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001394
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001395/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1396/// statement to exit to its outer synthesized loop.
1397///
Steve Naroffb29b4272008-04-14 22:03:09 +00001398Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001399 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1400 return S;
1401 // replace break with goto __break_label
1402 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001404 SourceLocation startLoc = S->getLocStart();
1405 buf = "goto __break_label_";
1406 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001407 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001408
1409 return 0;
1410}
1411
1412/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1413/// statement to continue with its inner synthesized loop.
1414///
Steve Naroffb29b4272008-04-14 22:03:09 +00001415Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001416 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1417 return S;
1418 // replace continue with goto __continue_label
1419 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001421 SourceLocation startLoc = S->getLocStart();
1422 buf = "goto __continue_label_";
1423 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001424 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001426 return 0;
1427}
1428
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001429/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001430/// It rewrites:
1431/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001433/// Into:
1434/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001435/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001436/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001437/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001438/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001439/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001440/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001441/// if (limit) {
1442/// unsigned long startMutations = *enumState.mutationsPtr;
1443/// do {
1444/// unsigned long counter = 0;
1445/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001446/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001448/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001449/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001450/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001451/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001453/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001455/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001456/// }
1457/// else
1458/// elem = nil;
1459/// }
1460///
Steve Naroffb29b4272008-04-14 22:03:09 +00001461Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001462 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001463 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001464 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001465 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001466 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001467 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001469 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001470 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001471 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001472 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473 std::string buf;
1474 buf = "\n{\n\t";
1475 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1476 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001477 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001478 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001479 if (ElementType->isObjCQualifiedIdType() ||
1480 ElementType->isObjCQualifiedInterfaceType())
1481 // Simply use 'id' for all qualified types.
1482 elementTypeAsString = "id";
1483 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001484 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001485 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001486 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001487 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488 buf += elementName;
1489 buf += ";\n\t";
1490 }
Chris Lattner06767512008-04-08 05:52:18 +00001491 else {
1492 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001493 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001494 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1495 if (VD->getType()->isObjCQualifiedIdType() ||
1496 VD->getType()->isObjCQualifiedInterfaceType())
1497 // Simply use 'id' for all qualified types.
1498 elementTypeAsString = "id";
1499 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001500 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503 // struct __objcFastEnumerationState enumState = { 0 };
1504 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001505 // id __rw_items[16];
1506 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001507 // id l_collection = (id)
1508 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001509 // Find start location of 'collection' the hard way!
1510 const char *startCollectionBuf = startBuf;
1511 startCollectionBuf += 3; // skip 'for'
1512 startCollectionBuf = strchr(startCollectionBuf, '(');
1513 startCollectionBuf++; // skip '('
1514 // find 'in' and skip it.
1515 while (*startCollectionBuf != ' ' ||
1516 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1517 (*(startCollectionBuf+3) != ' ' &&
1518 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1519 startCollectionBuf++;
1520 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001521
1522 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001523 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001524 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001525 SourceLocation rightParenLoc = S->getRParenLoc();
1526 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001527 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001528 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001530 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001531 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001532 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001533 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001534 // ((unsigned int (*)
1535 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001536 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001537 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001538 // "countByEnumeratingWithState:objects:count:"),
1539 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001540 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001541 buf += "unsigned long limit =\n\t\t";
1542 SynthCountByEnumWithState(buf);
1543 buf += ";\n\t";
1544 /// if (limit) {
1545 /// unsigned long startMutations = *enumState.mutationsPtr;
1546 /// do {
1547 /// unsigned long counter = 0;
1548 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001549 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001550 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001551 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001552 buf += "if (limit) {\n\t";
1553 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1554 buf += "do {\n\t\t";
1555 buf += "unsigned long counter = 0;\n\t\t";
1556 buf += "do {\n\t\t\t";
1557 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1558 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1559 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001560 buf += " = (";
1561 buf += elementTypeAsString;
1562 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001564 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001566 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001568 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001569 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001571 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 /// }
1573 /// else
1574 /// elem = nil;
1575 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001576 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001577 buf = ";\n\t";
1578 buf += "__continue_label_";
1579 buf += utostr(ObjCBcLabelNo.back());
1580 buf += ": ;";
1581 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001582 buf += "} while (counter < limit);\n\t";
1583 buf += "} while (limit = ";
1584 SynthCountByEnumWithState(buf);
1585 buf += ");\n\t";
1586 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001587 buf += " = ((";
1588 buf += elementTypeAsString;
1589 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001590 buf += "__break_label_";
1591 buf += utostr(ObjCBcLabelNo.back());
1592 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001593 buf += "}\n\t";
1594 buf += "else\n\t\t";
1595 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001596 buf += " = ((";
1597 buf += elementTypeAsString;
1598 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001599 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001601 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001602 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001603 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001604 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001605 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001606 } else {
1607 /* Need to treat single statements specially. For example:
1608 *
1609 * for (A *a in b) if (stuff()) break;
1610 * for (A *a in b) xxxyy;
1611 *
1612 * The following code simply scans ahead to the semi to find the actual end.
1613 */
1614 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1615 const char *semiBuf = strchr(stmtBuf, ';');
1616 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001617 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001618 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001619 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001620 Stmts.pop_back();
1621 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001622 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001623}
1624
Mike Stump1eb44332009-09-09 15:08:12 +00001625/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001626/// This routine rewrites @synchronized(expr) stmt;
1627/// into:
1628/// objc_sync_enter(expr);
1629/// @try stmt @finally { objc_sync_exit(expr); }
1630///
Steve Naroffb29b4272008-04-14 22:03:09 +00001631Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001632 // Get the start location and compute the semi location.
1633 SourceLocation startLoc = S->getLocStart();
1634 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001636 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001637
1638 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001639 buf = "objc_sync_enter((id)";
1640 const char *lparenBuf = startBuf;
1641 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001642 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001643 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1644 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001645 // been rewritten! (which implies the SourceLocation's are invalid).
1646 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001647 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001648 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001649 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001650 buf = ");\n";
1651 // declare a new scope with two variables, _stack and _rethrow.
1652 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1653 buf += "int buf[18/*32-bit i386*/];\n";
1654 buf += "char *pointers[4];} _stack;\n";
1655 buf += "id volatile _rethrow = 0;\n";
1656 buf += "objc_exception_try_enter(&_stack);\n";
1657 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001658 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001659 startLoc = S->getSynchBody()->getLocEnd();
1660 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Steve Naroffc7089f12008-08-19 13:04:19 +00001662 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001663 SourceLocation lastCurlyLoc = startLoc;
1664 buf = "}\nelse {\n";
1665 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001666 buf += "}\n";
1667 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001668 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001669
1670 std::string syncBuf;
1671 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001672
1673 Expr *syncExpr = S->getSynchExpr();
1674 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1675 ? CK_BitCast :
1676 syncExpr->getType()->isBlockPointerType()
1677 ? CK_BlockPointerToObjCPointerCast
1678 : CK_CPointerToObjCPointerCast;
1679 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1680 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001681 std::string syncExprBufS;
1682 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001683 syncExpr->printPretty(syncExprBuf, *Context, 0,
1684 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001685 syncBuf += syncExprBuf.str();
1686 syncBuf += ");";
1687
1688 buf += syncBuf;
1689 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001690 buf += "}\n";
1691 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Benjamin Kramerd999b372010-02-14 14:14:16 +00001693 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001694
1695 bool hasReturns = false;
1696 HasReturnStmts(S->getSynchBody(), hasReturns);
1697 if (hasReturns)
1698 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1699
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 return 0;
1701}
1702
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1704{
Steve Naroff8c565152008-12-05 17:03:39 +00001705 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001706 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001707 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001708 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001709
Steve Naroffb85e77a2009-12-05 21:43:12 +00001710 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001711 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001712 TryFinallyContainsReturnDiag);
1713 }
1714 return;
1715}
1716
Steve Naroffb85e77a2009-12-05 21:43:12 +00001717void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1718{
1719 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001720 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001721 if (*CI)
1722 HasReturnStmts(*CI, hasReturns);
1723
1724 if (isa<ReturnStmt>(S))
1725 hasReturns = true;
1726 return;
1727}
1728
1729void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1730 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001731 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001732 if (*CI) {
1733 RewriteTryReturnStmts(*CI);
1734 }
1735 if (isa<ReturnStmt>(S)) {
1736 SourceLocation startLoc = S->getLocStart();
1737 const char *startBuf = SM->getCharacterData(startLoc);
1738
1739 const char *semiBuf = strchr(startBuf, ';');
1740 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001741 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001742
1743 std::string buf;
1744 buf = "{ objc_exception_try_exit(&_stack); return";
1745
Benjamin Kramerd999b372010-02-14 14:14:16 +00001746 ReplaceText(startLoc, 6, buf);
1747 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001748 }
1749 return;
1750}
1751
1752void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1753 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001754 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001755 if (*CI) {
1756 RewriteSyncReturnStmts(*CI, syncExitBuf);
1757 }
1758 if (isa<ReturnStmt>(S)) {
1759 SourceLocation startLoc = S->getLocStart();
1760 const char *startBuf = SM->getCharacterData(startLoc);
1761
1762 const char *semiBuf = strchr(startBuf, ';');
1763 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001764 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001765
1766 std::string buf;
1767 buf = "{ objc_exception_try_exit(&_stack);";
1768 buf += syncExitBuf;
1769 buf += " return";
1770
Benjamin Kramerd999b372010-02-14 14:14:16 +00001771 ReplaceText(startLoc, 6, buf);
1772 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001773 }
1774 return;
1775}
1776
Steve Naroffb29b4272008-04-14 22:03:09 +00001777Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001778 // Get the start location and compute the semi location.
1779 SourceLocation startLoc = S->getLocStart();
1780 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001781
Steve Naroff75730982007-11-07 04:08:17 +00001782 assert((*startBuf == '@') && "bogus @try location");
1783
1784 std::string buf;
1785 // declare a new scope with two variables, _stack and _rethrow.
1786 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1787 buf += "int buf[18/*32-bit i386*/];\n";
1788 buf += "char *pointers[4];} _stack;\n";
1789 buf += "id volatile _rethrow = 0;\n";
1790 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001791 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001792
Benjamin Kramerd999b372010-02-14 14:14:16 +00001793 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Steve Naroff75730982007-11-07 04:08:17 +00001795 startLoc = S->getTryBody()->getLocEnd();
1796 startBuf = SM->getCharacterData(startLoc);
1797
1798 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Steve Naroff75730982007-11-07 04:08:17 +00001800 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001801 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001802 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001803 buf = " /* @catch begin */ else {\n";
1804 buf += " id _caught = objc_exception_extract(&_stack);\n";
1805 buf += " objc_exception_try_enter (&_stack);\n";
1806 buf += " if (_setjmp(_stack.buf))\n";
1807 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1808 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001809
Benjamin Kramerd999b372010-02-14 14:14:16 +00001810 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001811 } else { /* no catch list */
1812 buf = "}\nelse {\n";
1813 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1814 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001815 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001816 }
Steve Naroff75730982007-11-07 04:08:17 +00001817 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001818 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1819 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001820 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001821
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001822 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001823 buf = "if ("; // we are generating code for the first catch clause
1824 else
1825 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001826 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001827 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Steve Naroff75730982007-11-07 04:08:17 +00001829 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001830
Steve Naroff75730982007-11-07 04:08:17 +00001831 const char *lParenLoc = strchr(startBuf, '(');
1832
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001833 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001834 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001835 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001836 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1837 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001838 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001839 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001840 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Steve Naroffe12e6922008-02-01 20:02:07 +00001842 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001843 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001844 } else if (catchDecl) {
1845 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001846 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001847 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001848 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001849 } else if (const ObjCObjectPointerType *Ptr =
1850 t->getAs<ObjCObjectPointerType>()) {
1851 // Should be a pointer to a class.
1852 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1853 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001854 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001855 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001856 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001857 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001858 }
1859 }
1860 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001861 lastCatchBody = Catch->getCatchBody();
1862 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001863 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1864 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1865 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1866 assert((*rParenBuf == ')') && "bogus @catch paren location");
1867 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Mike Stump1eb44332009-09-09 15:08:12 +00001869 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001870 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001871 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001872 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001873 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001874 }
Steve Naroff75730982007-11-07 04:08:17 +00001875 }
1876 // Complete the catch list...
1877 if (lastCatchBody) {
1878 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001879 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1880 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Steve Naroff378f47a2008-09-11 15:29:03 +00001882 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001883 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001884 buf = "} /* last catch end */\n";
1885 buf += "else {\n";
1886 buf += " _rethrow = _caught;\n";
1887 buf += " objc_exception_try_exit(&_stack);\n";
1888 buf += "} } /* @catch end */\n";
1889 if (!S->getFinallyStmt())
1890 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001891 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Steve Naroff75730982007-11-07 04:08:17 +00001893 // Set lastCurlyLoc
1894 lastCurlyLoc = lastCatchBody->getLocEnd();
1895 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001896 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001897 startLoc = finalStmt->getLocStart();
1898 startBuf = SM->getCharacterData(startLoc);
1899 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Benjamin Kramerd999b372010-02-14 14:14:16 +00001901 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Steve Naroff75730982007-11-07 04:08:17 +00001903 Stmt *body = finalStmt->getFinallyBody();
1904 SourceLocation startLoc = body->getLocStart();
1905 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001906 assert(*SM->getCharacterData(startLoc) == '{' &&
1907 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001908 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001909 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001911 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001912 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001913 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001914 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001915
Steve Naroff75730982007-11-07 04:08:17 +00001916 // Set lastCurlyLoc
1917 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff8c565152008-12-05 17:03:39 +00001919 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001920 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001921 } else { /* no finally clause - make sure we synthesize an implicit one */
1922 buf = "{ /* implicit finally clause */\n";
1923 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1924 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1925 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001926 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001927
1928 // Now check for any return/continue/go statements within the @try.
1929 // The implicit finally clause won't called if the @try contains any
1930 // jump statements.
1931 bool hasReturns = false;
1932 HasReturnStmts(S->getTryBody(), hasReturns);
1933 if (hasReturns)
1934 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001935 }
1936 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001937 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001939 return 0;
1940}
1941
Mike Stump1eb44332009-09-09 15:08:12 +00001942// This can't be done with ReplaceStmt(S, ThrowExpr), since
1943// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001944// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001945Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001946 // Get the start location and compute the semi location.
1947 SourceLocation startLoc = S->getLocStart();
1948 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Steve Naroff2bd03922007-11-07 15:32:26 +00001950 assert((*startBuf == '@') && "bogus @throw location");
1951
1952 std::string buf;
1953 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001954 if (S->getThrowExpr())
1955 buf = "objc_exception_throw(";
1956 else // add an implicit argument
1957 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001959 // handle "@ throw" correctly.
1960 const char *wBuf = strchr(startBuf, 'w');
1961 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001962 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Steve Naroff2bd03922007-11-07 15:32:26 +00001964 const char *semiBuf = strchr(startBuf, ';');
1965 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001966 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001967 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001968 return 0;
1969}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001970
Steve Naroffb29b4272008-04-14 22:03:09 +00001971Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001972 // Create a new string expression.
1973 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001974 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001975 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00001976 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00001977 StringLiteral::Ascii, false,
1978 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001979 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001980
Chris Lattner07506182007-11-30 22:53:43 +00001981 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001982 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001983 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001984}
1985
Steve Naroffb29b4272008-04-14 22:03:09 +00001986Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001987 if (!SelGetUidFunctionDecl)
1988 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001989 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1990 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00001991 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00001992 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001993 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00001994 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001995 StringLiteral::Ascii, false,
1996 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001997 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1998 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001999 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002000 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002001 return SelExp;
2002}
2003
Steve Naroffb29b4272008-04-14 22:03:09 +00002004CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002005 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2006 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002007 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002008 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Steve Naroffebf2b562007-10-23 23:50:29 +00002010 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002011 DeclRefExpr *DRE =
2012 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Steve Naroffebf2b562007-10-23 23:50:29 +00002014 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002015 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002016 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002017 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002018 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002019
John McCall183700f2009-09-21 23:43:11 +00002020 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002022 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002023 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002024 FT->getCallResultType(*Context),
2025 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002026 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002027}
2028
Steve Naroffd5255f52007-11-01 13:24:47 +00002029static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2030 const char *&startRef, const char *&endRef) {
2031 while (startBuf < endBuf) {
2032 if (*startBuf == '<')
2033 startRef = startBuf; // mark the start.
2034 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002035 if (startRef && *startRef == '<') {
2036 endRef = startBuf; // mark the end.
2037 return true;
2038 }
2039 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002040 }
2041 startBuf++;
2042 }
2043 return false;
2044}
2045
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002046static void scanToNextArgument(const char *&argRef) {
2047 int angle = 0;
2048 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2049 if (*argRef == '<')
2050 angle++;
2051 else if (*argRef == '>')
2052 angle--;
2053 argRef++;
2054 }
2055 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2056}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002057
Steve Naroffb29b4272008-04-14 22:03:09 +00002058bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002059 if (T->isObjCQualifiedIdType())
2060 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002061 if (const PointerType *PT = T->getAs<PointerType>()) {
2062 if (PT->getPointeeType()->isObjCQualifiedIdType())
2063 return true;
2064 }
2065 if (T->isObjCObjectPointerType()) {
2066 T = T->getPointeeType();
2067 return T->isObjCQualifiedInterfaceType();
2068 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002069 if (T->isArrayType()) {
2070 QualType ElemTy = Context->getBaseElementType(T);
2071 return needToScanForQualifiers(ElemTy);
2072 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002073 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002074}
2075
Steve Naroff4f95b752008-07-29 18:15:38 +00002076void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2077 QualType Type = E->getType();
2078 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002079 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002080
Steve Naroffcda658e2008-11-19 21:15:47 +00002081 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2082 Loc = ECE->getLParenLoc();
2083 EndLoc = ECE->getRParenLoc();
2084 } else {
2085 Loc = E->getLocStart();
2086 EndLoc = E->getLocEnd();
2087 }
2088 // This will defend against trying to rewrite synthesized expressions.
2089 if (Loc.isInvalid() || EndLoc.isInvalid())
2090 return;
2091
Steve Naroff4f95b752008-07-29 18:15:38 +00002092 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002093 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002094 const char *startRef = 0, *endRef = 0;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002097 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2098 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002099 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002100 InsertText(LessLoc, "/*");
2101 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002102 }
2103 }
2104}
2105
Steve Naroffb29b4272008-04-14 22:03:09 +00002106void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002107 SourceLocation Loc;
2108 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002109 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002110 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2111 Loc = VD->getLocation();
2112 Type = VD->getType();
2113 }
2114 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2115 Loc = FD->getLocation();
2116 // Check for ObjC 'id' and class types that have been adorned with protocol
2117 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002118 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002119 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002120 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002121 if (!proto)
2122 return;
2123 Type = proto->getResultType();
2124 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002125 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2126 Loc = FD->getLocation();
2127 Type = FD->getType();
2128 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002129 else
2130 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002132 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002133 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Steve Naroffd5255f52007-11-01 13:24:47 +00002135 const char *endBuf = SM->getCharacterData(Loc);
2136 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002137 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002138 startBuf--; // scan backward (from the decl location) for return type.
2139 const char *startRef = 0, *endRef = 0;
2140 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2141 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002142 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2143 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002144 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002145 InsertText(LessLoc, "/*");
2146 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002147 }
2148 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002149 if (!proto)
2150 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002151 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002152 const char *startBuf = SM->getCharacterData(Loc);
2153 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002154 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2155 if (needToScanForQualifiers(proto->getArgType(i))) {
2156 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Steve Naroffd5255f52007-11-01 13:24:47 +00002158 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002159 // scan forward (from the decl location) for argument types.
2160 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002161 const char *startRef = 0, *endRef = 0;
2162 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2163 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002164 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002165 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002166 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002167 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002168 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002169 InsertText(LessLoc, "/*");
2170 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002171 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002172 startBuf = ++endBuf;
2173 }
2174 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002175 // If the function name is derived from a macro expansion, then the
2176 // argument buffer will not follow the name. Need to speak with Chris.
2177 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002178 startBuf++; // scan forward (from the decl location) for argument types.
2179 startBuf++;
2180 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002181 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002182}
2183
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002184void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2185 QualType QT = ND->getType();
2186 const Type* TypePtr = QT->getAs<Type>();
2187 if (!isa<TypeOfExprType>(TypePtr))
2188 return;
2189 while (isa<TypeOfExprType>(TypePtr)) {
2190 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2191 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2192 TypePtr = QT->getAs<Type>();
2193 }
2194 // FIXME. This will not work for multiple declarators; as in:
2195 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002196 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002197 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2198 const char *startBuf = SM->getCharacterData(DeclLoc);
2199 if (ND->getInit()) {
2200 std::string Name(ND->getNameAsString());
2201 TypeAsString += " " + Name + " = ";
2202 Expr *E = ND->getInit();
2203 SourceLocation startLoc;
2204 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2205 startLoc = ECE->getLParenLoc();
2206 else
2207 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002208 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002209 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002210 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002211 }
2212 else {
2213 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002214 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002215 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002216 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002217 }
2218}
2219
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002220// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002221void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002222 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002223 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002224 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002225 QualType getFuncType =
2226 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002227 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002228 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002229 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002230 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002231 SC_Extern,
2232 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002233}
2234
Steve Naroffb29b4272008-04-14 22:03:09 +00002235void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002236 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002237 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002238 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002239 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002240 return;
2241 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002242 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002243}
2244
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002245void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002246 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002247 const char *argPtr = TypeString.c_str();
2248 if (!strchr(argPtr, '^')) {
2249 Str += TypeString;
2250 return;
2251 }
2252 while (*argPtr) {
2253 Str += (*argPtr == '^' ? '*' : *argPtr);
2254 argPtr++;
2255 }
2256}
2257
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002258// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002259void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2260 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002261 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002262 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002263 const char *argPtr = TypeString.c_str();
2264 int paren = 0;
2265 while (*argPtr) {
2266 switch (*argPtr) {
2267 case '(':
2268 Str += *argPtr;
2269 paren++;
2270 break;
2271 case ')':
2272 Str += *argPtr;
2273 paren--;
2274 break;
2275 case '^':
2276 Str += '*';
2277 if (paren == 1)
2278 Str += VD->getNameAsString();
2279 break;
2280 default:
2281 Str += *argPtr;
2282 break;
2283 }
2284 argPtr++;
2285 }
2286}
2287
2288
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002289void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2290 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2291 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2292 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2293 if (!proto)
2294 return;
2295 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002296 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002297 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002298 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002299 FdStr += "(";
2300 unsigned numArgs = proto->getNumArgs();
2301 for (unsigned i = 0; i < numArgs; i++) {
2302 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002303 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002304 if (i+1 < numArgs)
2305 FdStr += ", ";
2306 }
2307 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002308 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002309 CurFunctionDeclToDeclareForBlock = 0;
2310}
2311
Steve Naroffc0a123c2008-03-11 17:37:02 +00002312// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002313void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002314 if (SuperContructorFunctionDecl)
2315 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002316 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002317 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002318 QualType argT = Context->getObjCIdType();
2319 assert(!argT.isNull() && "Can't find 'id' type");
2320 ArgTys.push_back(argT);
2321 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002322 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2323 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002324 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002325 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002326 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002327 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002328 SC_Extern,
2329 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002330}
2331
Steve Naroff09b266e2007-10-30 23:14:51 +00002332// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002333void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002334 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002335 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002336 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002337 assert(!argT.isNull() && "Can't find 'id' type");
2338 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002339 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002340 assert(!argT.isNull() && "Can't find 'SEL' type");
2341 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002342 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2343 &ArgTys[0], ArgTys.size(),
2344 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002345 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002346 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002347 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002348 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002349 SC_Extern,
2350 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002351}
2352
Steve Naroff874e2322007-11-15 10:28:18 +00002353// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002354void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002355 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002356 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002357 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002358 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002359 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002360 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2361 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2362 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002363 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002364 assert(!argT.isNull() && "Can't find 'SEL' type");
2365 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002366 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2367 &ArgTys[0], ArgTys.size(),
2368 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002369 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002370 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002371 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002372 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002373 SC_Extern,
2374 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002375}
2376
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002377// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002378void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002379 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002380 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002381 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002382 assert(!argT.isNull() && "Can't find 'id' type");
2383 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002384 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002385 assert(!argT.isNull() && "Can't find 'SEL' type");
2386 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002387 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002388 &ArgTys[0], ArgTys.size(),
2389 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002390 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002391 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002392 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002393 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002394 SC_Extern,
2395 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002396}
2397
Mike Stump1eb44332009-09-09 15:08:12 +00002398// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002399// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002400void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002401 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002402 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002403 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002404 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002405 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002406 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002407 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2408 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2409 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002410 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002411 assert(!argT.isNull() && "Can't find 'SEL' type");
2412 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002413 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002414 &ArgTys[0], ArgTys.size(),
2415 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002416 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002417 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002418 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002419 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002420 SC_Extern,
2421 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422}
2423
Steve Naroff1284db82008-05-08 22:02:18 +00002424// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002425void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002426 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002427 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002428 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002429 assert(!argT.isNull() && "Can't find 'id' type");
2430 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002431 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002432 assert(!argT.isNull() && "Can't find 'SEL' type");
2433 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002434 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2435 &ArgTys[0], ArgTys.size(),
2436 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002437 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002438 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002439 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002440 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002441 SC_Extern,
2442 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002443}
2444
Steve Naroff09b266e2007-10-30 23:14:51 +00002445// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002446void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002447 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002448 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002449 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002450 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2451 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002452 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002453 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002454 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002455 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002456 SC_Extern,
2457 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002458}
2459
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002460// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2461void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2462 IdentifierInfo *getSuperClassIdent =
2463 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002465 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002466 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2467 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002468 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002469 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002470 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002471 getSuperClassIdent,
2472 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002473 SC_Extern,
2474 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002475 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002476}
2477
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002478// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002479void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002480 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002481 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002482 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002483 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2484 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002485 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002486 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002487 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002488 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002489 SC_Extern,
2490 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002491}
2492
Steve Naroffb29b4272008-04-14 22:03:09 +00002493Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002494 QualType strType = getConstantStringStructType();
2495
2496 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002497
2498 std::string tmpName = InFileName;
2499 unsigned i;
2500 for (i=0; i < tmpName.length(); i++) {
2501 char c = tmpName.at(i);
2502 // replace any non alphanumeric characters with '_'.
2503 if (!isalpha(c) && (c < '0' || c > '9'))
2504 tmpName[i] = '_';
2505 }
2506 S += tmpName;
2507 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002508 S += utostr(NumObjCStringLiterals++);
2509
Steve Naroffba92b2e2008-03-27 22:29:16 +00002510 Preamble += "static __NSConstantStringImpl " + S;
2511 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2512 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002513 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002514 std::string prettyBufS;
2515 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002516 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2517 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002518 Preamble += prettyBuf.str();
2519 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002520 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002521
2522 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002523 SourceLocation(), &Context->Idents.get(S),
2524 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002525 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2526 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002527 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002528 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002529 VK_RValue, OK_Ordinary,
2530 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002531 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002532 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002533 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002534 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002535 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002536 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002537}
2538
Steve Naroff874e2322007-11-15 10:28:18 +00002539// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002540QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002541 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002542 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002543 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002544 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002545 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Steve Naroff874e2322007-11-15 10:28:18 +00002547 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002548 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002549 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002550 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002551
Steve Naroff874e2322007-11-15 10:28:18 +00002552 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002553 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002554 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002555 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002556 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002557 FieldTypes[i], 0,
2558 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002559 /*Mutable=*/false,
2560 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregor838db382010-02-11 01:19:42 +00002563 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002564 }
2565 return Context->getTagDeclType(SuperStructDecl);
2566}
2567
Steve Naroffb29b4272008-04-14 22:03:09 +00002568QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002569 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002570 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002571 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002572 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002573 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002575 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002576 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002577 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002578 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002579 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002580 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002581 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002582 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002583
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002584 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002585 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002586 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2587 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002588 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002589 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002590 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002591 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002592 /*Mutable=*/true,
2593 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002594 }
2595
Douglas Gregor838db382010-02-11 01:19:42 +00002596 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002597 }
2598 return Context->getTagDeclType(ConstantStringDecl);
2599}
2600
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002601Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2602 SourceLocation StartLoc,
2603 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002604 if (!SelGetUidFunctionDecl)
2605 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002606 if (!MsgSendFunctionDecl)
2607 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002608 if (!MsgSendSuperFunctionDecl)
2609 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002610 if (!MsgSendStretFunctionDecl)
2611 SynthMsgSendStretFunctionDecl();
2612 if (!MsgSendSuperStretFunctionDecl)
2613 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002614 if (!MsgSendFpretFunctionDecl)
2615 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002616 if (!GetClassFunctionDecl)
2617 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002618 if (!GetSuperClassFunctionDecl)
2619 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002620 if (!GetMetaClassFunctionDecl)
2621 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Steve Naroff874e2322007-11-15 10:28:18 +00002623 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002624 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2625 // May need to use objc_msgSend_stret() as well.
2626 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002627 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2628 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002629 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002630 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002631 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002632 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002633 }
Mike Stump1eb44332009-09-09 15:08:12 +00002634
Steve Naroff934f2762007-10-24 22:48:43 +00002635 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002636 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002637 switch (Exp->getReceiverKind()) {
2638 case ObjCMessageExpr::SuperClass: {
2639 MsgSendFlavor = MsgSendSuperFunctionDecl;
2640 if (MsgSendStretFlavor)
2641 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2642 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002643
Douglas Gregor04badcf2010-04-21 00:45:42 +00002644 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002645
Chris Lattner5f9e2722011-07-23 10:55:15 +00002646 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002647
Douglas Gregor04badcf2010-04-21 00:45:42 +00002648 // set the receiver to self, the first argument to all methods.
2649 InitExprs.push_back(
2650 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002651 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002652 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002653 Context->getObjCIdType(),
2654 VK_RValue,
2655 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002656 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Douglas Gregor04badcf2010-04-21 00:45:42 +00002658 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002659 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002660 QualType argType = Context->getPointerType(Context->CharTy);
2661 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002662 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002663 StringLiteral::Ascii, false,
2664 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002665 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2666 &ClsExprs[0],
2667 ClsExprs.size(),
2668 StartLoc,
2669 EndLoc);
2670 // (Class)objc_getClass("CurrentClass")
2671 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2672 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002673 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002674 ClsExprs.clear();
2675 ClsExprs.push_back(ArgExpr);
2676 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2677 &ClsExprs[0], ClsExprs.size(),
2678 StartLoc, EndLoc);
2679
2680 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2681 // To turn off a warning, type-cast to 'id'
2682 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2683 NoTypeInfoCStyleCastExpr(Context,
2684 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002685 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002686 // struct objc_super
2687 QualType superType = getSuperStructType();
2688 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002689
Francois Pichet62ec1f22011-09-17 17:15:52 +00002690 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002691 SynthSuperContructorFunctionDecl();
2692 // Simulate a contructor call...
2693 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002694 superType, VK_LValue,
2695 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002696 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2697 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002698 superType, VK_LValue,
2699 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002700 // The code for super is a little tricky to prevent collision with
2701 // the structure definition in the header. The rewriter has it's own
2702 // internal definition (__rw_objc_super) that is uses. This is why
2703 // we need the cast below. For example:
2704 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2705 //
John McCall2de56d12010-08-25 11:45:40 +00002706 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002707 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002708 VK_RValue, OK_Ordinary,
2709 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002710 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2711 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002712 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002713 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002714 // (struct objc_super) { <exprs from above> }
2715 InitListExpr *ILE =
2716 new (Context) InitListExpr(*Context, SourceLocation(),
2717 &InitExprs[0], InitExprs.size(),
2718 SourceLocation());
2719 TypeSourceInfo *superTInfo
2720 = Context->getTrivialTypeSourceInfo(superType);
2721 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002722 superType, VK_LValue,
2723 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002724 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002725 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002727 VK_RValue, OK_Ordinary,
2728 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002729 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002730 MsgExprs.push_back(SuperRep);
2731 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002732 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002733
2734 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002735 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736 QualType argType = Context->getPointerType(Context->CharTy);
2737 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002738 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002739 IdentifierInfo *clsName = Class->getIdentifier();
2740 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002741 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002742 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002743 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002744 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2745 &ClsExprs[0],
2746 ClsExprs.size(),
2747 StartLoc, EndLoc);
2748 MsgExprs.push_back(Cls);
2749 break;
2750 }
2751
2752 case ObjCMessageExpr::SuperInstance:{
2753 MsgSendFlavor = MsgSendSuperFunctionDecl;
2754 if (MsgSendStretFlavor)
2755 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2756 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2757 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002758 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002759
2760 InitExprs.push_back(
2761 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002762 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002763 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002764 Context->getObjCIdType(),
2765 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 ); // set the 'receiver'.
2767
2768 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002769 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002770 QualType argType = Context->getPointerType(Context->CharTy);
2771 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002772 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002773 StringLiteral::Ascii, false, argType,
2774 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2776 &ClsExprs[0],
2777 ClsExprs.size(),
2778 StartLoc, EndLoc);
2779 // (Class)objc_getClass("CurrentClass")
2780 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2781 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002782 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002783 ClsExprs.clear();
2784 ClsExprs.push_back(ArgExpr);
2785 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2786 &ClsExprs[0], ClsExprs.size(),
2787 StartLoc, EndLoc);
2788
2789 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2790 // To turn off a warning, type-cast to 'id'
2791 InitExprs.push_back(
2792 // set 'super class', using class_getSuperclass().
2793 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002794 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795 // struct objc_super
2796 QualType superType = getSuperStructType();
2797 Expr *SuperRep;
2798
Francois Pichet62ec1f22011-09-17 17:15:52 +00002799 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002800 SynthSuperContructorFunctionDecl();
2801 // Simulate a contructor call...
2802 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002803 superType, VK_LValue,
2804 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2806 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002807 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 // The code for super is a little tricky to prevent collision with
2809 // the structure definition in the header. The rewriter has it's own
2810 // internal definition (__rw_objc_super) that is uses. This is why
2811 // we need the cast below. For example:
2812 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2813 //
John McCall2de56d12010-08-25 11:45:40 +00002814 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002815 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002816 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002817 SourceLocation());
2818 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2819 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002820 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002821 } else {
2822 // (struct objc_super) { <exprs from above> }
2823 InitListExpr *ILE =
2824 new (Context) InitListExpr(*Context, SourceLocation(),
2825 &InitExprs[0], InitExprs.size(),
2826 SourceLocation());
2827 TypeSourceInfo *superTInfo
2828 = Context->getTrivialTypeSourceInfo(superType);
2829 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002830 superType, VK_RValue, ILE,
2831 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 }
2833 MsgExprs.push_back(SuperRep);
2834 break;
2835 }
2836
2837 case ObjCMessageExpr::Instance: {
2838 // Remove all type-casts because it may contain objc-style types; e.g.
2839 // Foo<Proto> *.
2840 Expr *recExpr = Exp->getInstanceReceiver();
2841 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2842 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002843 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2844 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2845 ? CK_BlockPointerToObjCPointerCast
2846 : CK_CPointerToObjCPointerCast;
2847
Douglas Gregor04badcf2010-04-21 00:45:42 +00002848 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002849 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 MsgExprs.push_back(recExpr);
2851 break;
2852 }
2853 }
2854
Steve Naroffbeaf2992007-11-03 11:27:19 +00002855 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002856 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002857 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002858 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002859 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002860 StringLiteral::Ascii, false,
2861 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002862 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002863 &SelExprs[0], SelExprs.size(),
2864 StartLoc,
2865 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002866 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002867
Steve Naroff934f2762007-10-24 22:48:43 +00002868 // Now push any user supplied arguments.
2869 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002870 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002871 // Make all implicit casts explicit...ICE comes in handy:-)
2872 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2873 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002874 QualType type = ICE->getType();
2875 if (needToScanForQualifiers(type))
2876 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002877 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002878 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002879 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002880 CastKind CK;
2881 if (SubExpr->getType()->isIntegralType(*Context) &&
2882 type->isBooleanType()) {
2883 CK = CK_IntegralToBoolean;
2884 } else if (type->isObjCObjectPointerType()) {
2885 if (SubExpr->getType()->isBlockPointerType()) {
2886 CK = CK_BlockPointerToObjCPointerCast;
2887 } else if (SubExpr->getType()->isPointerType()) {
2888 CK = CK_CPointerToObjCPointerCast;
2889 } else {
2890 CK = CK_BitCast;
2891 }
2892 } else {
2893 CK = CK_BitCast;
2894 }
2895
2896 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002897 }
2898 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002899 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002900 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002901 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002902 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002903 CastKind CK;
2904 if (userExpr->getType()->isIntegralType(*Context)) {
2905 CK = CK_IntegralToPointer;
2906 } else if (userExpr->getType()->isBlockPointerType()) {
2907 CK = CK_BlockPointerToObjCPointerCast;
2908 } else if (userExpr->getType()->isPointerType()) {
2909 CK = CK_CPointerToObjCPointerCast;
2910 } else {
2911 CK = CK_BitCast;
2912 }
John McCall9d125032010-01-15 18:39:57 +00002913 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002914 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002915 }
Mike Stump1eb44332009-09-09 15:08:12 +00002916 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002917 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002918 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2919 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002920 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002921 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002922 }
Steve Naroffab972d32007-11-04 22:37:50 +00002923 // Generate the funky cast.
2924 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002925 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002926 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002927
Steve Naroffab972d32007-11-04 22:37:50 +00002928 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002929 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2930 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2931 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002932 ArgTypes.push_back(Context->getObjCIdType());
2933 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002934 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002935 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002936 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2937 E = OMD->param_end(); PI != E; ++PI) {
2938 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002939 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002940 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002941 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002942 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002943 ArgTypes.push_back(t);
2944 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002945 returnType = Exp->getType();
2946 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002947 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002948 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002949 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002950 }
2951 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002952 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Steve Naroffab972d32007-11-04 22:37:50 +00002954 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002955 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002956 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002957
Mike Stump1eb44332009-09-09 15:08:12 +00002958 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002959 // If we don't do this cast, we get the following bizarre warning/note:
2960 // xx.m:13: warning: function called through a non-compatible type
2961 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002962 cast = NoTypeInfoCStyleCastExpr(Context,
2963 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002964 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Steve Naroffab972d32007-11-04 22:37:50 +00002966 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00002967 QualType castType =
2968 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2969 // If we don't have a method decl, force a variadic cast.
2970 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002971 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002972 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002973 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002974
2975 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002976 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002977
John McCall183700f2009-09-21 23:43:11 +00002978 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002979 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002980 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002981 FT->getResultType(), VK_RValue,
2982 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002983 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002984 if (MsgSendStretFlavor) {
2985 // We have the method which returns a struct/union. Must also generate
2986 // call to objc_msgSend_stret and hang both varieties on a conditional
2987 // expression which dictate which one to envoke depending on size of
2988 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002989
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002990 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002991 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002992 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002993 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002994 cast = NoTypeInfoCStyleCastExpr(Context,
2995 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002996 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002997 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00002998 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2999 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003000 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003001 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003002 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003004 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003005 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003006
John McCall183700f2009-09-21 23:43:11 +00003007 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003008 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003009 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003010 FT->getResultType(), VK_RValue,
3011 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003012
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003013 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003014 UnaryExprOrTypeTraitExpr *sizeofExpr =
3015 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3016 Context->getTrivialTypeSourceInfo(returnType),
3017 Context->getSizeType(), SourceLocation(),
3018 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003019 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3020 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3021 // For X86 it is more complicated and some kind of target specific routine
3022 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003023 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003024 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003025 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3026 llvm::APInt(IntSize, 8),
3027 Context->IntTy,
3028 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003029 BinaryOperator *lessThanExpr =
3030 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3031 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003032 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003033 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003034 new (Context) ConditionalOperator(lessThanExpr,
3035 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003036 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003037 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003038 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3039 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003041 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003042 return ReplacingStmt;
3043}
3044
Steve Naroffb29b4272008-04-14 22:03:09 +00003045Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003046 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3047 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Steve Naroff934f2762007-10-24 22:48:43 +00003049 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003050 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003052 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003053 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003054}
3055
Steve Naroff621edce2009-04-29 16:37:50 +00003056// typedef struct objc_object Protocol;
3057QualType RewriteObjC::getProtocolType() {
3058 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003059 TypeSourceInfo *TInfo
3060 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003061 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003062 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003063 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003064 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003065 }
3066 return Context->getTypeDeclType(ProtocolTypeDecl);
3067}
3068
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003069/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003070/// a synthesized/forward data reference (to the protocol's metadata).
3071/// The forward references (and metadata) are generated in
3072/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003073Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003074 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3075 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003076 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003077 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003078 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003079 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3080 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003081 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003082 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003083 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003084 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003085 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003086 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003087 ReplaceStmt(Exp, castExpr);
3088 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003089 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003090 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003092}
3093
Mike Stump1eb44332009-09-09 15:08:12 +00003094bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003095 const char *endBuf) {
3096 while (startBuf < endBuf) {
3097 if (*startBuf == '#') {
3098 // Skip whitespace.
3099 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3100 ;
3101 if (!strncmp(startBuf, "if", strlen("if")) ||
3102 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3103 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3104 !strncmp(startBuf, "define", strlen("define")) ||
3105 !strncmp(startBuf, "undef", strlen("undef")) ||
3106 !strncmp(startBuf, "else", strlen("else")) ||
3107 !strncmp(startBuf, "elif", strlen("elif")) ||
3108 !strncmp(startBuf, "endif", strlen("endif")) ||
3109 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3110 !strncmp(startBuf, "include", strlen("include")) ||
3111 !strncmp(startBuf, "import", strlen("import")) ||
3112 !strncmp(startBuf, "include_next", strlen("include_next")))
3113 return true;
3114 }
3115 startBuf++;
3116 }
3117 return false;
3118}
3119
Fariborz Jahanian58457172011-12-05 18:43:13 +00003120/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003121/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003122void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003123 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003124 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003125 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003126 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003127 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003129 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003130 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003131 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003132 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003133 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003134
Steve Narofffea763e82007-11-14 19:25:57 +00003135 const char *startBuf = SM->getCharacterData(LocStart);
3136 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003137
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003138 // If no ivars and no root or if its root, directly or indirectly,
3139 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003140 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003141 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003142 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003143 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003144 return;
3145 }
Mike Stump1eb44332009-09-09 15:08:12 +00003146
3147 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003148 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003149 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003150 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003151 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003152 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003153
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003154 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003155 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003156 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003157 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003158 // If the buffer contains preprocessor directives, we do more fine-grained
3159 // rewrites. This is intended to fix code that looks like (which occurs in
3160 // NSURL.h, for example):
3161 //
3162 // #ifdef XYZ
3163 // @interface Foo : NSObject
3164 // #else
3165 // @interface FooBar : NSObject
3166 // #endif
3167 // {
3168 // int i;
3169 // }
3170 // @end
3171 //
3172 // This clause is segregated to avoid breaking the common case.
3173 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003174 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003175 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003176 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003177 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003178
Chris Lattnercafeb352009-02-20 18:18:36 +00003179 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003180 // advance to the end of the referenced protocols.
3181 while (endHeader < cursor && *endHeader != '>') endHeader++;
3182 endHeader++;
3183 }
3184 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003185 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003186 } else {
3187 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003188 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003189 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003190 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003191 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003193 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003194 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003195 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003196
Steve Narofffea763e82007-11-14 19:25:57 +00003197 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003198 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003199 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003200 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003201 }
3202 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003203
Steve Narofffea763e82007-11-14 19:25:57 +00003204 // Now comment out any visibility specifiers.
3205 while (cursor < endBuf) {
3206 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003207 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003208 // Skip whitespace.
3209 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3210 /*scan*/;
3211
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003212 // FIXME: presence of @public, etc. inside comment results in
3213 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003214 if (!strncmp(cursor, "public", strlen("public")) ||
3215 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003216 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003217 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003218 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003219 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003220 // FIXME: If there are cases where '<' is used in ivar declaration part
3221 // of user code, then scan the ivar list and use needToScanForQualifiers
3222 // for type checking.
3223 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003224 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003225 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003226 cursor = strchr(cursor, '>');
3227 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003228 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003229 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003230 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003231 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003232 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003233 }
Steve Narofffea763e82007-11-14 19:25:57 +00003234 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003235 }
Steve Narofffea763e82007-11-14 19:25:57 +00003236 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003237 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003238 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003239 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003240 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003242 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003243 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003244 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003245 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003246 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003247 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003248 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003249 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003250}
3251
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003252//===----------------------------------------------------------------------===//
3253// Meta Data Emission
3254//===----------------------------------------------------------------------===//
3255
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003256
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003257/// RewriteImplementations - This routine rewrites all method implementations
3258/// and emits meta-data.
3259
Steve Narofface66252008-11-13 20:07:04 +00003260void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003261 int ClsDefCount = ClassImplementation.size();
3262 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003264 // Rewrite implemented methods
3265 for (int i = 0; i < ClsDefCount; i++)
3266 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003268 for (int i = 0; i < CatDefCount; i++)
3269 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003270}
Mike Stump1eb44332009-09-09 15:08:12 +00003271
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003272void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3273 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003274 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003275 assert(BlockByRefDeclNo.count(VD) &&
3276 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003277 if (def)
3278 ResultStr += "struct ";
3279 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003280 "_" + utostr(BlockByRefDeclNo[VD]) ;
3281}
3282
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003283static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3284 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3285 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3286 return false;
3287}
3288
Steve Naroff54055232008-10-27 17:20:55 +00003289std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003290 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003291 std::string Tag) {
3292 const FunctionType *AFT = CE->getFunctionType();
3293 QualType RT = AFT->getResultType();
3294 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003295 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003296 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003297
Steve Naroff54055232008-10-27 17:20:55 +00003298 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003299
Douglas Gregor72564e72009-02-26 23:50:07 +00003300 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003301 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003302 // block (to reference imported block decl refs).
3303 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003304 } else if (BD->param_empty()) {
3305 S += "(" + StructRef + " *__cself)";
3306 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003307 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003308 assert(FT && "SynthesizeBlockFunc: No function proto");
3309 S += '(';
3310 // first add the implicit argument.
3311 S += StructRef + " *__cself, ";
3312 std::string ParamStr;
3313 for (BlockDecl::param_iterator AI = BD->param_begin(),
3314 E = BD->param_end(); AI != E; ++AI) {
3315 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003316 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003317 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003318 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003319 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003320 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003321 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003322 S += ParamStr;
3323 }
3324 if (FT->isVariadic()) {
3325 if (!BD->param_empty()) S += ", ";
3326 S += "...";
3327 }
3328 S += ')';
3329 }
3330 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Steve Naroff54055232008-10-27 17:20:55 +00003332 // Create local declarations to avoid rewriting all closure decl ref exprs.
3333 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003334 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003335 E = BlockByRefDecls.end(); I != E; ++I) {
3336 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003337 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003338 std::string TypeString;
3339 RewriteByRefString(TypeString, Name, (*I));
3340 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003341 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003342 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003343 }
Steve Naroff54055232008-10-27 17:20:55 +00003344 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003345 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003346 E = BlockByCopyDecls.end(); I != E; ++I) {
3347 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003348 // Handle nested closure invocation. For example:
3349 //
3350 // void (^myImportedClosure)(void);
3351 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003352 //
Steve Naroff54055232008-10-27 17:20:55 +00003353 // void (^anotherClosure)(void);
3354 // anotherClosure = ^(void) {
3355 // myImportedClosure(); // import and invoke the closure
3356 // };
3357 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003358 if (isTopLevelBlockPointerType((*I)->getType())) {
3359 RewriteBlockPointerTypeVariable(S, (*I));
3360 S += " = (";
3361 RewriteBlockPointerType(S, (*I)->getType());
3362 S += ")";
3363 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3364 }
3365 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003366 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003367 QualType QT = (*I)->getType();
3368 if (HasLocalVariableExternalStorage(*I))
3369 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003370 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003371 S += Name + " = __cself->" +
3372 (*I)->getNameAsString() + "; // bound by copy\n";
3373 }
Steve Naroff54055232008-10-27 17:20:55 +00003374 }
3375 std::string RewrittenStr = RewrittenBlockExprs[CE];
3376 const char *cstr = RewrittenStr.c_str();
3377 while (*cstr++ != '{') ;
3378 S += cstr;
3379 S += "\n";
3380 return S;
3381}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003382
Steve Naroff54055232008-10-27 17:20:55 +00003383std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003384 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003385 std::string Tag) {
3386 std::string StructRef = "struct " + Tag;
3387 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Steve Naroff54055232008-10-27 17:20:55 +00003389 S += funcName;
3390 S += "_block_copy_" + utostr(i);
3391 S += "(" + StructRef;
3392 S += "*dst, " + StructRef;
3393 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003394 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003395 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003396 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003397 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003398 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003399 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003400 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003401 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003402 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003403 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003404 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003405 else
3406 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003407 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003408 S += "}\n";
3409
Steve Naroff54055232008-10-27 17:20:55 +00003410 S += "\nstatic void __";
3411 S += funcName;
3412 S += "_block_dispose_" + utostr(i);
3413 S += "(" + StructRef;
3414 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003415 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003416 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003417 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003418 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003419 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003420 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003421 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003422 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003423 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003424 else
3425 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003426 }
Mike Stump1eb44332009-09-09 15:08:12 +00003427 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003428 return S;
3429}
3430
Steve Naroff01aec112009-12-06 21:14:13 +00003431std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3432 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003433 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003434 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Steve Naroff54055232008-10-27 17:20:55 +00003436 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003437 S += " struct " + Desc;
3438 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003439
Steve Naroff01aec112009-12-06 21:14:13 +00003440 Constructor += "(void *fp, "; // Invoke function pointer.
3441 Constructor += "struct " + Desc; // Descriptor pointer.
3442 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Steve Naroff54055232008-10-27 17:20:55 +00003444 if (BlockDeclRefs.size()) {
3445 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003446 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003447 E = BlockByCopyDecls.end(); I != E; ++I) {
3448 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003449 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003450 std::string ArgName = "_" + FieldName;
3451 // Handle nested closure invocation. For example:
3452 //
3453 // void (^myImportedBlock)(void);
3454 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003455 //
Steve Naroff54055232008-10-27 17:20:55 +00003456 // void (^anotherBlock)(void);
3457 // anotherBlock = ^(void) {
3458 // myImportedBlock(); // import and invoke the closure
3459 // };
3460 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003461 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003462 S += "struct __block_impl *";
3463 Constructor += ", void *" + ArgName;
3464 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003465 QualType QT = (*I)->getType();
3466 if (HasLocalVariableExternalStorage(*I))
3467 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003468 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3469 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003470 Constructor += ", " + ArgName;
3471 }
3472 S += FieldName + ";\n";
3473 }
3474 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003475 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003476 E = BlockByRefDecls.end(); I != E; ++I) {
3477 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003478 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003479 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003480 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003481 std::string TypeString;
3482 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003483 TypeString += " *";
3484 FieldName = TypeString + FieldName;
3485 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003486 Constructor += ", " + ArgName;
3487 }
3488 S += FieldName + "; // by ref\n";
3489 }
3490 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003491 Constructor += ", int flags=0)";
3492 // Initialize all "by copy" arguments.
3493 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003494 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003495 E = BlockByCopyDecls.end(); I != E; ++I) {
3496 std::string Name = (*I)->getNameAsString();
3497 if (firsTime) {
3498 Constructor += " : ";
3499 firsTime = false;
3500 }
3501 else
3502 Constructor += ", ";
3503 if (isTopLevelBlockPointerType((*I)->getType()))
3504 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3505 else
3506 Constructor += Name + "(_" + Name + ")";
3507 }
3508 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003509 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003510 E = BlockByRefDecls.end(); I != E; ++I) {
3511 std::string Name = (*I)->getNameAsString();
3512 if (firsTime) {
3513 Constructor += " : ";
3514 firsTime = false;
3515 }
3516 else
3517 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003518 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003519 }
3520
3521 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003522 if (GlobalVarDecl)
3523 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3524 else
3525 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003526 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Steve Naroff01aec112009-12-06 21:14:13 +00003528 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003529 } else {
3530 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003531 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003532 if (GlobalVarDecl)
3533 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3534 else
3535 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003536 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3537 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003538 }
3539 Constructor += " ";
3540 Constructor += "}\n";
3541 S += Constructor;
3542 S += "};\n";
3543 return S;
3544}
3545
Steve Naroff01aec112009-12-06 21:14:13 +00003546std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3547 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003548 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003549 unsigned hasCopy) {
3550 std::string S = "\nstatic struct " + DescTag;
3551
3552 S += " {\n unsigned long reserved;\n";
3553 S += " unsigned long Block_size;\n";
3554 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003555 S += " void (*copy)(struct ";
3556 S += ImplTag; S += "*, struct ";
3557 S += ImplTag; S += "*);\n";
3558
3559 S += " void (*dispose)(struct ";
3560 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003561 }
3562 S += "} ";
3563
3564 S += DescTag + "_DATA = { 0, sizeof(struct ";
3565 S += ImplTag + ")";
3566 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003567 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3568 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003569 }
3570 S += "};\n";
3571 return S;
3572}
3573
Steve Naroff54055232008-10-27 17:20:55 +00003574void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003575 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003576 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003577 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003578 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003579 bool RewriteSC = (GlobalVarDecl &&
3580 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003581 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003582 GlobalVarDecl->getType().getCVRQualifiers());
3583 if (RewriteSC) {
3584 std::string SC(" void __");
3585 SC += GlobalVarDecl->getNameAsString();
3586 SC += "() {}";
3587 InsertText(FunLocStart, SC);
3588 }
3589
Steve Naroff54055232008-10-27 17:20:55 +00003590 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003591 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3592 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003593 // Need to copy-in the inner copied-in variables not actually used in this
3594 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003595 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3596 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3597 ValueDecl *VD = Exp->getDecl();
3598 BlockDeclRefs.push_back(Exp);
3599 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3600 BlockByCopyDeclsPtrSet.insert(VD);
3601 BlockByCopyDecls.push_back(VD);
3602 }
3603 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3604 BlockByRefDeclsPtrSet.insert(VD);
3605 BlockByRefDecls.push_back(VD);
3606 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003607 // imported objects in the inner blocks not used in the outer
3608 // blocks must be copied/disposed in the outer block as well.
3609 if (Exp->isByRef() ||
3610 VD->getType()->isObjCObjectPointerType() ||
3611 VD->getType()->isBlockPointerType())
3612 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003613 }
Steve Naroff54055232008-10-27 17:20:55 +00003614
Daniel Dunbar4087f272010-08-17 22:39:59 +00003615 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3616 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Steve Naroff01aec112009-12-06 21:14:13 +00003618 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003619
Benjamin Kramerd999b372010-02-14 14:14:16 +00003620 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003621
Steve Naroff01aec112009-12-06 21:14:13 +00003622 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Benjamin Kramerd999b372010-02-14 14:14:16 +00003624 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003625
3626 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003627 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003628 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003629 }
Steve Naroff01aec112009-12-06 21:14:13 +00003630 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3631 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003632 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Steve Naroff54055232008-10-27 17:20:55 +00003634 BlockDeclRefs.clear();
3635 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003636 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003637 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003638 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003639 ImportedBlockDecls.clear();
3640 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003641 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003642 // Must insert any 'const/volatile/static here. Since it has been
3643 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003644 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003645 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003646 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003647 if (GlobalVarDecl->getType().isConstQualified())
3648 SC += "const ";
3649 if (GlobalVarDecl->getType().isVolatileQualified())
3650 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003651 if (GlobalVarDecl->getType().isRestrictQualified())
3652 SC += "restrict ";
3653 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003654 }
3655
Steve Naroff54055232008-10-27 17:20:55 +00003656 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003657 InnerDeclRefsCount.clear();
3658 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003659 RewrittenBlockExprs.clear();
3660}
3661
3662void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3663 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003664 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Steve Naroff54055232008-10-27 17:20:55 +00003666 SynthesizeBlockLiterals(FunLocStart, FuncName);
3667}
3668
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003669static void BuildUniqueMethodName(std::string &Name,
3670 ObjCMethodDecl *MD) {
3671 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003672 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003673 Name += "__" + MD->getSelector().getAsString();
3674 // Convert colons to underscores.
3675 std::string::size_type loc = 0;
3676 while ((loc = Name.find(":", loc)) != std::string::npos)
3677 Name.replace(loc, 1, "_");
3678}
3679
Steve Naroff54055232008-10-27 17:20:55 +00003680void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003681 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3682 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003683 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003684 std::string FuncName;
3685 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003686 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003687}
3688
3689void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003690 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003691 if (*CI) {
3692 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3693 GetBlockDeclRefExprs(CBE->getBody());
3694 else
3695 GetBlockDeclRefExprs(*CI);
3696 }
3697 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003698 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003699 // FIXME: Handle enums.
3700 if (!isa<FunctionDecl>(CDRE->getDecl()))
3701 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003702 }
3703 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3704 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3705 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003706 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3707 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003708 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003709 BlockDeclRefs.push_back(BDRE);
3710 }
3711
Steve Naroff54055232008-10-27 17:20:55 +00003712 return;
3713}
3714
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003715void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003716 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003717 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003718 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003719 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003720 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3721 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003722 GetInnerBlockDeclRefExprs(CBE->getBody(),
3723 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003724 InnerContexts);
3725 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003726 else
3727 GetInnerBlockDeclRefExprs(*CI,
3728 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003729 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003730
3731 }
3732 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003733 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003734 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003735 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003736 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003737 }
3738 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3739 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3740 if (Var->isFunctionOrMethodVarDecl())
3741 ImportedLocalExternalDecls.insert(Var);
3742 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003743
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003744 return;
3745}
3746
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003747/// convertFunctionTypeOfBlocks - This routine converts a function type
3748/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003749/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003750/// all block pointers to function pointers.
3751QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3752 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3753 // FTP will be null for closures that don't take arguments.
3754 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003755 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003756 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003757 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003758
3759 if (FTP) {
3760 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3761 E = FTP->arg_type_end(); I && (I != E); ++I) {
3762 QualType t = *I;
3763 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003764 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003765 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003766 ArgTypes.push_back(t);
3767 }
3768 }
3769 QualType FuncType;
3770 // FIXME. Does this work if block takes no argument but has a return type
3771 // which is of block type?
3772 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003773 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003774 else FuncType = QualType(FT, 0);
3775 return FuncType;
3776}
3777
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003778Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003779 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003780 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003782 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003784 } else if (const BlockDeclRefExpr *CDRE =
3785 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003786 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003787 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003788 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003789 }
3790 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3791 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3792 }
3793 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3794 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3795 else if (const ConditionalOperator *CEXPR =
3796 dyn_cast<ConditionalOperator>(BlockExp)) {
3797 Expr *LHSExp = CEXPR->getLHS();
3798 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3799 Expr *RHSExp = CEXPR->getRHS();
3800 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3801 Expr *CONDExp = CEXPR->getCond();
3802 ConditionalOperator *CondExpr =
3803 new (Context) ConditionalOperator(CONDExp,
3804 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003805 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003806 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003807 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003808 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3809 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003810 } else if (const PseudoObjectExpr *POE
3811 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3812 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003813 } else {
3814 assert(1 && "RewriteBlockClass: Bad type");
3815 }
3816 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003817 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003818 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003819 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003820 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003821
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003822 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003823 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003824 &Context->Idents.get("__block_impl"));
3825 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003826
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003827 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003828 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003829
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003830 // Push the block argument type.
3831 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003832 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003833 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003834 E = FTP->arg_type_end(); I && (I != E); ++I) {
3835 QualType t = *I;
3836 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003837 if (!convertBlockPointerToFunctionPointer(t))
3838 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003839 ArgTypes.push_back(t);
3840 }
Steve Naroff54055232008-10-27 17:20:55 +00003841 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003842 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003843 QualType PtrToFuncCastType
3844 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003845
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003846 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003847
John McCall9d125032010-01-15 18:39:57 +00003848 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003849 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003850 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003851 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003852 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3853 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003854 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003855
Douglas Gregor44b43212008-12-11 16:49:14 +00003856 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003857 SourceLocation(),
3858 &Context->Idents.get("FuncPtr"),
3859 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003860 /*BitWidth=*/0, /*Mutable=*/true,
3861 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003862 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003863 FD->getType(), VK_LValue,
3864 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003866
John McCall9d125032010-01-15 18:39:57 +00003867 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003868 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003869 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003870
Chris Lattner5f9e2722011-07-23 10:55:15 +00003871 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003872 // Add the implicit argument.
3873 BlkExprs.push_back(BlkCast);
3874 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003875 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003876 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003877 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003878 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003879 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3880 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003881 Exp->getType(), VK_RValue,
3882 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003883 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003884}
3885
Steve Naroff621edce2009-04-29 16:37:50 +00003886// We need to return the rewritten expression to handle cases where the
3887// BlockDeclRefExpr is embedded in another expression being rewritten.
3888// For example:
3889//
3890// int main() {
3891// __block Foo *f;
3892// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003893//
Steve Naroff621edce2009-04-29 16:37:50 +00003894// void (^myblock)() = ^() {
3895// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3896// i = 77;
3897// };
3898//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003899Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003900 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003901 // for each DeclRefExp where BYREFVAR is name of the variable.
3902 ValueDecl *VD;
3903 bool isArrow = true;
3904 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3905 VD = BDRE->getDecl();
3906 else {
3907 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3908 isArrow = false;
3909 }
3910
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003911 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003912 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003913 &Context->Idents.get("__forwarding"),
3914 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003915 /*BitWidth=*/0, /*Mutable=*/true,
3916 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003917 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3918 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003919 FD->getType(), VK_LValue,
3920 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003921
Chris Lattner5f9e2722011-07-23 10:55:15 +00003922 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003923 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003924 &Context->Idents.get(Name),
3925 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003926 /*BitWidth=*/0, /*Mutable=*/true,
3927 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003928 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003929 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003930
3931
3932
Steve Naroffdf8570d2009-02-02 17:19:26 +00003933 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003934 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3935 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003936 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003937 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003938 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003939}
3940
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003941// Rewrites the imported local variable V with external storage
3942// (static, extern, etc.) as *V
3943//
3944Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3945 ValueDecl *VD = DRE->getDecl();
3946 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3947 if (!ImportedLocalExternalDecls.count(Var))
3948 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003949 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3950 VK_LValue, OK_Ordinary,
3951 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003952 // Need parens to enforce precedence.
3953 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3954 Exp);
3955 ReplaceStmt(DRE, PE);
3956 return PE;
3957}
3958
Steve Naroffb2f9e512008-11-03 23:29:32 +00003959void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3960 SourceLocation LocStart = CE->getLParenLoc();
3961 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003962
3963 // Need to avoid trying to rewrite synthesized casts.
3964 if (LocStart.isInvalid())
3965 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003966 // Need to avoid trying to rewrite casts contained in macros.
3967 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3968 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Steve Naroff54055232008-10-27 17:20:55 +00003970 const char *startBuf = SM->getCharacterData(LocStart);
3971 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003972 QualType QT = CE->getType();
3973 const Type* TypePtr = QT->getAs<Type>();
3974 if (isa<TypeOfExprType>(TypePtr)) {
3975 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3976 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3977 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003978 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003979 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003980 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003981 return;
3982 }
Steve Naroff54055232008-10-27 17:20:55 +00003983 // advance the location to startArgList.
3984 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003985
Steve Naroff54055232008-10-27 17:20:55 +00003986 while (*argPtr++ && (argPtr < endBuf)) {
3987 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003988 case '^':
3989 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003990 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003991 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003992 break;
Steve Naroff54055232008-10-27 17:20:55 +00003993 }
3994 }
3995 return;
3996}
3997
3998void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3999 SourceLocation DeclLoc = FD->getLocation();
4000 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Steve Naroff54055232008-10-27 17:20:55 +00004002 // We have 1 or more arguments that have closure pointers.
4003 const char *startBuf = SM->getCharacterData(DeclLoc);
4004 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Steve Naroff54055232008-10-27 17:20:55 +00004006 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Steve Naroff54055232008-10-27 17:20:55 +00004008 parenCount++;
4009 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004010 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004011 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Steve Naroff54055232008-10-27 17:20:55 +00004013 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Steve Naroff54055232008-10-27 17:20:55 +00004015 while (*argPtr++ && parenCount) {
4016 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004017 case '^':
4018 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004019 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004020 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004021 break;
4022 case '(':
4023 parenCount++;
4024 break;
4025 case ')':
4026 parenCount--;
4027 break;
Steve Naroff54055232008-10-27 17:20:55 +00004028 }
4029 }
4030 return;
4031}
4032
4033bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004034 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004035 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004036 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004037 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004038 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004039 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004040 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004041 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004042 }
4043 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004044 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004045 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004046 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004047 return true;
4048 }
4049 return false;
4050}
4051
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004052bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4053 const FunctionProtoType *FTP;
4054 const PointerType *PT = QT->getAs<PointerType>();
4055 if (PT) {
4056 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4057 } else {
4058 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4059 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4060 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4061 }
4062 if (FTP) {
4063 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004064 E = FTP->arg_type_end(); I != E; ++I) {
4065 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004066 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004067 if ((*I)->isObjCObjectPointerType() &&
4068 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4069 return true;
4070 }
4071
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004072 }
4073 return false;
4074}
4075
Ted Kremenek8189cde2009-02-07 01:47:29 +00004076void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4077 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004078 const char *argPtr = strchr(Name, '(');
4079 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Steve Naroff54055232008-10-27 17:20:55 +00004081 LParen = argPtr; // output the start.
4082 argPtr++; // skip past the left paren.
4083 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Steve Naroff54055232008-10-27 17:20:55 +00004085 while (*argPtr && parenCount) {
4086 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004087 case '(': parenCount++; break;
4088 case ')': parenCount--; break;
4089 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004090 }
4091 if (parenCount) argPtr++;
4092 }
4093 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4094 RParen = argPtr; // output the end
4095}
4096
4097void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4098 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4099 RewriteBlockPointerFunctionArgs(FD);
4100 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004101 }
Steve Naroff54055232008-10-27 17:20:55 +00004102 // Handle Variables and Typedefs.
4103 SourceLocation DeclLoc = ND->getLocation();
4104 QualType DeclT;
4105 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4106 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004107 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004108 DeclT = TDD->getUnderlyingType();
4109 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4110 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004111 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004112 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Steve Naroff54055232008-10-27 17:20:55 +00004114 const char *startBuf = SM->getCharacterData(DeclLoc);
4115 const char *endBuf = startBuf;
4116 // scan backward (from the decl location) for the end of the previous decl.
4117 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4118 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004119 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004120 std::string buf;
4121 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004122 // *startBuf != '^' if we are dealing with a pointer to function that
4123 // may take block argument types (which will be handled below).
4124 if (*startBuf == '^') {
4125 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004126 buf = '*';
4127 startBuf++;
4128 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004129 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004130 while (*startBuf != ')') {
4131 buf += *startBuf;
4132 startBuf++;
4133 OrigLength++;
4134 }
4135 buf += ')';
4136 OrigLength++;
4137
4138 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4139 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004140 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004141 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004142 DeclLoc = ND->getLocation();
4143 startBuf = SM->getCharacterData(DeclLoc);
4144 const char *argListBegin, *argListEnd;
4145 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4146 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004147 if (*argListBegin == '^')
4148 buf += '*';
4149 else if (*argListBegin == '<') {
4150 buf += "/*";
4151 buf += *argListBegin++;
4152 OrigLength++;;
4153 while (*argListBegin != '>') {
4154 buf += *argListBegin++;
4155 OrigLength++;
4156 }
4157 buf += *argListBegin;
4158 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004159 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004160 else
4161 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004162 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004163 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004164 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004165 buf += ')';
4166 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004167 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004168 ReplaceText(Start, OrigLength, buf);
4169
Steve Naroff54055232008-10-27 17:20:55 +00004170 return;
4171}
4172
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004173
4174/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4175/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4176/// struct Block_byref_id_object *src) {
4177/// _Block_object_assign (&_dest->object, _src->object,
4178/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4179/// [|BLOCK_FIELD_IS_WEAK]) // object
4180/// _Block_object_assign(&_dest->object, _src->object,
4181/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4182/// [|BLOCK_FIELD_IS_WEAK]) // block
4183/// }
4184/// And:
4185/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4186/// _Block_object_dispose(_src->object,
4187/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4188/// [|BLOCK_FIELD_IS_WEAK]) // object
4189/// _Block_object_dispose(_src->object,
4190/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4191/// [|BLOCK_FIELD_IS_WEAK]) // block
4192/// }
4193
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004194std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4195 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004196 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004197 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004198 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004199 CopyDestroyCache.insert(flag);
4200 S = "static void __Block_byref_id_object_copy_";
4201 S += utostr(flag);
4202 S += "(void *dst, void *src) {\n";
4203
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004204 // offset into the object pointer is computed as:
4205 // void * + void* + int + int + void* + void *
4206 unsigned IntSize =
4207 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4208 unsigned VoidPtrSize =
4209 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4210
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004211 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004212 S += " _Block_object_assign((char*)dst + ";
4213 S += utostr(offset);
4214 S += ", *(void * *) ((char*)src + ";
4215 S += utostr(offset);
4216 S += "), ";
4217 S += utostr(flag);
4218 S += ");\n}\n";
4219
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004220 S += "static void __Block_byref_id_object_dispose_";
4221 S += utostr(flag);
4222 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004223 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4224 S += utostr(offset);
4225 S += "), ";
4226 S += utostr(flag);
4227 S += ");\n}\n";
4228 return S;
4229}
4230
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004231/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4232/// the declaration into:
4233/// struct __Block_byref_ND {
4234/// void *__isa; // NULL for everything except __weak pointers
4235/// struct __Block_byref_ND *__forwarding;
4236/// int32_t __flags;
4237/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004238/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4239/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004240/// typex ND;
4241/// };
4242///
4243/// It then replaces declaration of ND variable with:
4244/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4245/// __size=sizeof(struct __Block_byref_ND),
4246/// ND=initializer-if-any};
4247///
4248///
4249void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004250 // Insert declaration for the function in which block literal is
4251 // used.
4252 if (CurFunctionDeclToDeclareForBlock)
4253 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004254 int flag = 0;
4255 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004256 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004257 if (DeclLoc.isInvalid())
4258 // If type location is missing, it is because of missing type (a warning).
4259 // Use variable's location which is good for this case.
4260 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004261 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004262 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004263 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004264 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004265 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004266 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004267 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004268 ByrefType += " {\n";
4269 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004270 RewriteByRefString(ByrefType, Name, ND);
4271 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004272 ByrefType += " int __flags;\n";
4273 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004274 // Add void *__Block_byref_id_object_copy;
4275 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004276 QualType Ty = ND->getType();
4277 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4278 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004279 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4280 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004281 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004282
4283 QualType T = Ty;
4284 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004285 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004286
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004287 ByrefType += " " + Name + ";\n";
4288 ByrefType += "};\n";
4289 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004290 SourceLocation FunLocStart;
4291 if (CurFunctionDef)
4292 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4293 else {
4294 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4295 FunLocStart = CurMethodDef->getLocStart();
4296 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004297 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004298 if (Ty.isObjCGCWeak()) {
4299 flag |= BLOCK_FIELD_IS_WEAK;
4300 isa = 1;
4301 }
4302
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004303 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004304 flag = BLOCK_BYREF_CALLER;
4305 QualType Ty = ND->getType();
4306 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4307 if (Ty->isBlockPointerType())
4308 flag |= BLOCK_FIELD_IS_BLOCK;
4309 else
4310 flag |= BLOCK_FIELD_IS_OBJECT;
4311 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004312 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004313 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004314 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004315
4316 // struct __Block_byref_ND ND =
4317 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4318 // initializer-if-any};
4319 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004320 unsigned flags = 0;
4321 if (HasCopyAndDispose)
4322 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004323 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004324 ByrefType.clear();
4325 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004326 std::string ForwardingCastType("(");
4327 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004328 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004329 ByrefType += " " + Name + " = {(void*)";
4330 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004331 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004332 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004333 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004334 ByrefType += "sizeof(";
4335 RewriteByRefString(ByrefType, Name, ND);
4336 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004337 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004338 ByrefType += ", __Block_byref_id_object_copy_";
4339 ByrefType += utostr(flag);
4340 ByrefType += ", __Block_byref_id_object_dispose_";
4341 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004342 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004343 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004344 unsigned nameSize = Name.size();
4345 // for block or function pointer declaration. Name is aleady
4346 // part of the declaration.
4347 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4348 nameSize = 1;
4349 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004350 }
4351 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004352 SourceLocation startLoc;
4353 Expr *E = ND->getInit();
4354 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4355 startLoc = ECE->getLParenLoc();
4356 else
4357 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004358 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004359 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004360 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004361 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004362 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004363 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004364 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004365 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004366 ByrefType += "sizeof(";
4367 RewriteByRefString(ByrefType, Name, ND);
4368 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004369 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004370 ByrefType += "__Block_byref_id_object_copy_";
4371 ByrefType += utostr(flag);
4372 ByrefType += ", __Block_byref_id_object_dispose_";
4373 ByrefType += utostr(flag);
4374 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004375 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004376 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004377
4378 // Complete the newly synthesized compound expression by inserting a right
4379 // curly brace before the end of the declaration.
4380 // FIXME: This approach avoids rewriting the initializer expression. It
4381 // also assumes there is only one declarator. For example, the following
4382 // isn't currently supported by this routine (in general):
4383 //
4384 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4385 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004386 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4387 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004388 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4389 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004390 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004391
Benjamin Kramerd999b372010-02-14 14:14:16 +00004392 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004393 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004394 return;
4395}
4396
Mike Stump1eb44332009-09-09 15:08:12 +00004397void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004398 // Add initializers for any closure decl refs.
4399 GetBlockDeclRefExprs(Exp->getBody());
4400 if (BlockDeclRefs.size()) {
4401 // Unique all "by copy" declarations.
4402 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004403 if (!BlockDeclRefs[i]->isByRef()) {
4404 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4405 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4406 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4407 }
4408 }
Steve Naroff54055232008-10-27 17:20:55 +00004409 // Unique all "by ref" declarations.
4410 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4411 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004412 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4413 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4414 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4415 }
Steve Naroff54055232008-10-27 17:20:55 +00004416 }
4417 // Find any imported blocks...they will need special attention.
4418 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004419 if (BlockDeclRefs[i]->isByRef() ||
4420 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004421 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004422 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004423 }
4424}
4425
Chris Lattner5f9e2722011-07-23 10:55:15 +00004426FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004427 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004428 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004429 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4430 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004431 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004432}
4433
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004434Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004435 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004436 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004437 Blocks.push_back(Exp);
4438
4439 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004440
4441 // Add inner imported variables now used in current block.
4442 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004443 if (!InnerBlockDeclRefs.empty()) {
4444 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4445 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4446 ValueDecl *VD = Exp->getDecl();
4447 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004448 // We need to save the copied-in variables in nested
4449 // blocks because it is needed at the end for some of the API generations.
4450 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004451 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4452 BlockDeclRefs.push_back(Exp);
4453 BlockByCopyDeclsPtrSet.insert(VD);
4454 BlockByCopyDecls.push_back(VD);
4455 }
4456 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4457 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4458 BlockDeclRefs.push_back(Exp);
4459 BlockByRefDeclsPtrSet.insert(VD);
4460 BlockByRefDecls.push_back(VD);
4461 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004462 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004463 // Find any imported blocks...they will need special attention.
4464 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4465 if (InnerBlockDeclRefs[i]->isByRef() ||
4466 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4467 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4468 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004469 }
4470 InnerDeclRefsCount.push_back(countOfInnerDecls);
4471
Steve Narofffa15fd92008-10-28 20:29:00 +00004472 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Steve Narofffa15fd92008-10-28 20:29:00 +00004474 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004475 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004476 else if (CurMethodDef)
4477 BuildUniqueMethodName(FuncName, CurMethodDef);
4478 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004479 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004480
Steve Narofffa15fd92008-10-28 20:29:00 +00004481 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004482
Steve Narofffa15fd92008-10-28 20:29:00 +00004483 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4484 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004485
Steve Narofffa15fd92008-10-28 20:29:00 +00004486 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004487 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4488 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004489
4490 FunctionDecl *FD;
4491 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004492
Steve Narofffa15fd92008-10-28 20:29:00 +00004493 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004494 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004495 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4496 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Chris Lattner5f9e2722011-07-23 10:55:15 +00004498 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004499
Steve Narofffdc03722008-10-29 21:23:59 +00004500 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004501 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004502 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004503 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004504 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004505 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004506 InitExprs.push_back(castExpr);
4507
Steve Naroff01aec112009-12-06 21:14:13 +00004508 // Initialize the block descriptor.
4509 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004510
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004511 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4512 SourceLocation(), SourceLocation(),
4513 &Context->Idents.get(DescData.c_str()),
4514 Context->VoidPtrTy, 0,
4515 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004516 UnaryOperator *DescRefExpr =
4517 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4518 Context->VoidPtrTy,
4519 VK_LValue,
4520 SourceLocation()),
4521 UO_AddrOf,
4522 Context->getPointerType(Context->VoidPtrTy),
4523 VK_RValue, OK_Ordinary,
4524 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004525 InitExprs.push_back(DescRefExpr);
4526
Steve Narofffa15fd92008-10-28 20:29:00 +00004527 // Add initializers for any closure decl refs.
4528 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004529 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004530 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004531 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004532 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004533 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004534 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004535 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004536 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4537 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004538 if (HasLocalVariableExternalStorage(*I)) {
4539 QualType QT = (*I)->getType();
4540 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004541 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4542 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004543 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004544 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004545 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004546 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4547 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004548 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004549 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004550 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004551 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004552 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4553 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004554 if (HasLocalVariableExternalStorage(*I)) {
4555 QualType QT = (*I)->getType();
4556 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004557 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4558 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004559 }
4560
Steve Narofffa15fd92008-10-28 20:29:00 +00004561 }
Mike Stump1eb44332009-09-09 15:08:12 +00004562 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004563 }
4564 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004565 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004566 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004567 ValueDecl *ND = (*I);
4568 std::string Name(ND->getNameAsString());
4569 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004570 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004571 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4572 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004573 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004574 SourceLocation(), SourceLocation(),
4575 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004576 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4577 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4578
Daniel Dunbar4087f272010-08-17 22:39:59 +00004579 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004580 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4581 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004582 bool isNestedCapturedVar = false;
4583 if (block)
4584 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4585 ce = block->capture_end(); ci != ce; ++ci) {
4586 const VarDecl *variable = ci->getVariable();
4587 if (variable == ND && ci->isNested()) {
4588 assert (ci->isByRef() &&
4589 "SynthBlockInitExpr - captured block variable is not byref");
4590 isNestedCapturedVar = true;
4591 break;
4592 }
4593 }
4594 // captured nested byref variable has its address passed. Do not take
4595 // its address again.
4596 if (!isNestedCapturedVar)
4597 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004598 Context->getPointerType(Exp->getType()),
4599 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004600 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004601 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004602 }
4603 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004604 if (ImportedBlockDecls.size()) {
4605 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4606 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004607 unsigned IntSize =
4608 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004609 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4610 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004611 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004612 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004613 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004614 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004615 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004616 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004617 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004618 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004619 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004620 BlockDeclRefs.clear();
4621 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004622 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004623 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004624 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004625 ImportedBlockDecls.clear();
4626 return NewRep;
4627}
4628
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004629bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4630 if (const ObjCForCollectionStmt * CS =
4631 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4632 return CS->getElement() == DS;
4633 return false;
4634}
4635
Steve Narofffa15fd92008-10-28 20:29:00 +00004636//===----------------------------------------------------------------------===//
4637// Function Body / Expression rewriting
4638//===----------------------------------------------------------------------===//
4639
4640Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004641 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004642 isa<DoStmt>(S) || isa<ForStmt>(S))
4643 Stmts.push_back(S);
4644 else if (isa<ObjCForCollectionStmt>(S)) {
4645 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004646 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004647 }
Mike Stump1eb44332009-09-09 15:08:12 +00004648
John McCall4b9c2d22011-11-06 09:01:30 +00004649 // Pseudo-object operations and ivar references need special
4650 // treatment because we're going to recursively rewrite them.
4651 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4652 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4653 return RewritePropertyOrImplicitSetter(PseudoOp);
4654 } else {
4655 return RewritePropertyOrImplicitGetter(PseudoOp);
4656 }
4657 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4658 return RewriteObjCIvarRefExpr(IvarRefExpr);
4659 }
4660
Steve Narofffa15fd92008-10-28 20:29:00 +00004661 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004662
Steve Narofffa15fd92008-10-28 20:29:00 +00004663 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004664 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004665 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004666 Stmt *childStmt = (*CI);
4667 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004668 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004669 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004670 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004671 }
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004674 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004675 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4676 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004677 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004678 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004679 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004680 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004681 Stmt *SaveCurrentBody = CurrentBody;
4682 CurrentBody = BE->getBody();
4683 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004684 // block literal on rhs of a property-dot-sytax assignment
4685 // must be replaced by its synthesize ast so getRewrittenText
4686 // works as expected. In this case, what actually ends up on RHS
4687 // is the blockTranscribed which is the helper function for the
4688 // block literal; as in: self.c = ^() {[ace ARR];};
4689 bool saveDisableReplaceStmt = DisableReplaceStmt;
4690 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004691 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004692 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004693 CurrentBody = SaveCurrentBody;
4694 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004695 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004697 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004698 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004700 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4701
Steve Narofffa15fd92008-10-28 20:29:00 +00004702 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004703 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004704 return blockTranscribed;
4705 }
4706 // Handle specific things.
4707 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4708 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Steve Narofffa15fd92008-10-28 20:29:00 +00004710 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4711 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Steve Narofffa15fd92008-10-28 20:29:00 +00004713 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4714 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Steve Narofffa15fd92008-10-28 20:29:00 +00004716 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004717#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004718 // Before we rewrite it, put the original message expression in a comment.
4719 SourceLocation startLoc = MessExpr->getLocStart();
4720 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004721
Steve Narofffa15fd92008-10-28 20:29:00 +00004722 const char *startBuf = SM->getCharacterData(startLoc);
4723 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 std::string messString;
4726 messString += "// ";
4727 messString.append(startBuf, endBuf-startBuf+1);
4728 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004729
4730 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004731 // InsertText(clang::SourceLocation, char const*, unsigned int).
4732 // InsertText(startLoc, messString.c_str(), messString.size());
4733 // Tried this, but it didn't work either...
4734 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004735#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004736 return RewriteMessageExpr(MessExpr);
4737 }
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4740 return RewriteObjCTryStmt(StmtTry);
4741
4742 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4743 return RewriteObjCSynchronizedStmt(StmtTry);
4744
4745 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4746 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4749 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004750
4751 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004752 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004753 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 OrigStmtRange.getEnd());
4755 if (BreakStmt *StmtBreakStmt =
4756 dyn_cast<BreakStmt>(S))
4757 return RewriteBreakStmt(StmtBreakStmt);
4758 if (ContinueStmt *StmtContinueStmt =
4759 dyn_cast<ContinueStmt>(S))
4760 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004761
4762 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004763 // and cast exprs.
4764 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4765 // FIXME: What we're doing here is modifying the type-specifier that
4766 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004767 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004768 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4769 // the context of an ObjCForCollectionStmt. For example:
4770 // NSArray *someArray;
4771 // for (id <FooProtocol> index in someArray) ;
4772 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4773 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004774 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004775 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004776
Steve Narofffa15fd92008-10-28 20:29:00 +00004777 // Blocks rewrite rules.
4778 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4779 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004780 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004781 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004782 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004783 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004784 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004785 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004786 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004787 if (VD->hasAttr<BlocksAttr>()) {
4788 static unsigned uniqueByrefDeclCount = 0;
4789 assert(!BlockByRefDeclNo.count(ND) &&
4790 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4791 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004792 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004793 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004794 else
4795 RewriteTypeOfDecl(VD);
4796 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004797 }
Richard Smith162e1c12011-04-15 14:24:37 +00004798 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004799 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004801 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004802 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4803 }
4804 }
4805 }
Mike Stump1eb44332009-09-09 15:08:12 +00004806
Steve Narofffa15fd92008-10-28 20:29:00 +00004807 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4808 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004809
4810 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004811 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4812 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004813 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4814 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004815 && "Statement stack mismatch");
4816 Stmts.pop_back();
4817 }
4818 // Handle blocks rewriting.
4819 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4820 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004821 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004822 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004823 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4824 ValueDecl *VD = DRE->getDecl();
4825 if (VD->hasAttr<BlocksAttr>())
4826 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004827 if (HasLocalVariableExternalStorage(VD))
4828 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004829 }
4830
Steve Narofffa15fd92008-10-28 20:29:00 +00004831 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004832 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004833 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004834 ReplaceStmt(S, BlockCall);
4835 return BlockCall;
4836 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004837 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004838 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004839 RewriteCastExpr(CE);
4840 }
4841#if 0
4842 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004843 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4844 ICE->getSubExpr(),
4845 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004846 // Get the new text.
4847 std::string SStr;
4848 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004849 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004850 const std::string &Str = Buf.str();
4851
4852 printf("CAST = %s\n", &Str[0]);
4853 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4854 delete S;
4855 return Replacement;
4856 }
4857#endif
4858 // Return this stmt unmodified.
4859 return S;
4860}
4861
Steve Naroff3d7e7862009-12-05 15:55:59 +00004862void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4863 for (RecordDecl::field_iterator i = RD->field_begin(),
4864 e = RD->field_end(); i != e; ++i) {
4865 FieldDecl *FD = *i;
4866 if (isTopLevelBlockPointerType(FD->getType()))
4867 RewriteBlockPointerDecl(FD);
4868 if (FD->getType()->isObjCQualifiedIdType() ||
4869 FD->getType()->isObjCQualifiedInterfaceType())
4870 RewriteObjCQualifiedInterfaceTypes(FD);
4871 }
4872}
4873
Steve Narofffa15fd92008-10-28 20:29:00 +00004874/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4875/// main file of the input.
4876void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004877 switch (D->getKind()) {
4878 case Decl::Function: {
4879 FunctionDecl *FD = cast<FunctionDecl>(D);
4880 if (FD->isOverloadedOperator())
4881 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004883 // Since function prototypes don't have ParmDecl's, we check the function
4884 // prototype. This enables us to rewrite function declarations and
4885 // definitions using the same code.
4886 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004887
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004888 // FIXME: If this should support Obj-C++, support CXXTryStmt
4889 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4890 CurFunctionDef = FD;
4891 CurFunctionDeclToDeclareForBlock = FD;
4892 CurrentBody = Body;
4893 Body =
4894 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4895 FD->setBody(Body);
4896 CurrentBody = 0;
4897 if (PropParentMap) {
4898 delete PropParentMap;
4899 PropParentMap = 0;
4900 }
4901 // This synthesizes and inserts the block "impl" struct, invoke function,
4902 // and any copy/dispose helper functions.
4903 InsertBlockLiteralsWithinFunction(FD);
4904 CurFunctionDef = 0;
4905 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004906 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004907 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004908 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004909 case Decl::ObjCMethod: {
4910 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4911 if (CompoundStmt *Body = MD->getCompoundBody()) {
4912 CurMethodDef = MD;
4913 CurrentBody = Body;
4914 Body =
4915 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4916 MD->setBody(Body);
4917 CurrentBody = 0;
4918 if (PropParentMap) {
4919 delete PropParentMap;
4920 PropParentMap = 0;
4921 }
4922 InsertBlockLiteralsWithinMethod(MD);
4923 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004924 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004925 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004926 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004927 case Decl::ObjCImplementation: {
4928 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4929 ClassImplementation.push_back(CI);
4930 break;
4931 }
4932 case Decl::ObjCCategoryImpl: {
4933 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4934 CategoryImplementation.push_back(CI);
4935 break;
4936 }
4937 case Decl::Var: {
4938 VarDecl *VD = cast<VarDecl>(D);
4939 RewriteObjCQualifiedInterfaceTypes(VD);
4940 if (isTopLevelBlockPointerType(VD->getType()))
4941 RewriteBlockPointerDecl(VD);
4942 else if (VD->getType()->isFunctionPointerType()) {
4943 CheckFunctionPointerDecl(VD->getType(), VD);
4944 if (VD->getInit()) {
4945 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4946 RewriteCastExpr(CE);
4947 }
4948 }
4949 } else if (VD->getType()->isRecordType()) {
4950 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4951 if (RD->isCompleteDefinition())
4952 RewriteRecordBody(RD);
4953 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004954 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004955 GlobalVarDecl = VD;
4956 CurrentBody = VD->getInit();
4957 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4958 CurrentBody = 0;
4959 if (PropParentMap) {
4960 delete PropParentMap;
4961 PropParentMap = 0;
4962 }
4963 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4964 GlobalVarDecl = 0;
4965
4966 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004967 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004968 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004969 }
4970 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004971 break;
4972 }
4973 case Decl::TypeAlias:
4974 case Decl::Typedef: {
4975 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4976 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4977 RewriteBlockPointerDecl(TD);
4978 else if (TD->getUnderlyingType()->isFunctionPointerType())
4979 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4980 }
4981 break;
4982 }
4983 case Decl::CXXRecord:
4984 case Decl::Record: {
4985 RecordDecl *RD = cast<RecordDecl>(D);
4986 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004987 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004988 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004990 default:
4991 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004992 }
4993 // Nothing yet.
4994}
4995
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004996void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004997 if (Diags.hasErrorOccurred())
4998 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Steve Narofffa15fd92008-10-28 20:29:00 +00005000 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005001
Steve Naroff621edce2009-04-29 16:37:50 +00005002 // Here's a great place to add any extra declarations that may be needed.
5003 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005004 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005005 E = ProtocolExprDecls.end(); I != E; ++I)
5006 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5007
Benjamin Kramerd999b372010-02-14 14:14:16 +00005008 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005009 if (ClassImplementation.size() || CategoryImplementation.size())
5010 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005011
Steve Narofffa15fd92008-10-28 20:29:00 +00005012 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5013 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005014 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005015 Rewrite.getRewriteBufferFor(MainFileID)) {
5016 //printf("Changed:\n");
5017 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5018 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005019 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005020 }
Steve Narofface66252008-11-13 20:07:04 +00005021
Steve Naroff621edce2009-04-29 16:37:50 +00005022 if (ClassImplementation.size() || CategoryImplementation.size() ||
5023 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005024 // Rewrite Objective-c meta data*
5025 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005026 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005027 // Emit metadata.
5028 *OutFile << ResultStr;
5029 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005030 OutFile->flush();
5031}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005032
5033void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5034 InitializeCommon(context);
5035
5036 // declaring objc_selector outside the parameter list removes a silly
5037 // scope related warning...
5038 if (IsHeader)
5039 Preamble = "#pragma once\n";
5040 Preamble += "struct objc_selector; struct objc_class;\n";
5041 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5042 Preamble += "struct objc_object *superClass; ";
5043 if (LangOpts.MicrosoftExt) {
5044 // Add a constructor for creating temporary objects.
5045 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5046 ": ";
5047 Preamble += "object(o), superClass(s) {} ";
5048 }
5049 Preamble += "};\n";
5050 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5051 Preamble += "typedef struct objc_object Protocol;\n";
5052 Preamble += "#define _REWRITER_typedef_Protocol\n";
5053 Preamble += "#endif\n";
5054 if (LangOpts.MicrosoftExt) {
5055 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5056 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5057 } else
5058 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5059 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5060 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5061 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5062 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5063 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5064 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5065 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5066 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5067 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5068 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5069 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5070 Preamble += "(const char *);\n";
5071 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5072 Preamble += "(struct objc_class *);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5074 Preamble += "(const char *);\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5077 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5078 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5079 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5080 Preamble += "(struct objc_class *, struct objc_object *);\n";
5081 // @synchronized hooks.
5082 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5085 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5086 Preamble += "struct __objcFastEnumerationState {\n\t";
5087 Preamble += "unsigned long state;\n\t";
5088 Preamble += "void **itemsPtr;\n\t";
5089 Preamble += "unsigned long *mutationsPtr;\n\t";
5090 Preamble += "unsigned long extra[5];\n};\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5092 Preamble += "#define __FASTENUMERATIONSTATE\n";
5093 Preamble += "#endif\n";
5094 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5095 Preamble += "struct __NSConstantStringImpl {\n";
5096 Preamble += " int *isa;\n";
5097 Preamble += " int flags;\n";
5098 Preamble += " char *str;\n";
5099 Preamble += " long length;\n";
5100 Preamble += "};\n";
5101 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5102 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5103 Preamble += "#else\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5105 Preamble += "#endif\n";
5106 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5107 Preamble += "#endif\n";
5108 // Blocks preamble.
5109 Preamble += "#ifndef BLOCK_IMPL\n";
5110 Preamble += "#define BLOCK_IMPL\n";
5111 Preamble += "struct __block_impl {\n";
5112 Preamble += " void *isa;\n";
5113 Preamble += " int Flags;\n";
5114 Preamble += " int Reserved;\n";
5115 Preamble += " void *FuncPtr;\n";
5116 Preamble += "};\n";
5117 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5118 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5119 Preamble += "extern \"C\" __declspec(dllexport) "
5120 "void _Block_object_assign(void *, const void *, const int);\n";
5121 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5122 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5123 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5124 Preamble += "#else\n";
5125 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5126 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5127 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5128 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5129 Preamble += "#endif\n";
5130 Preamble += "#endif\n";
5131 if (LangOpts.MicrosoftExt) {
5132 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5133 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5134 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5135 Preamble += "#define __attribute__(X)\n";
5136 Preamble += "#endif\n";
5137 Preamble += "#define __weak\n";
5138 }
5139 else {
5140 Preamble += "#define __block\n";
5141 Preamble += "#define __weak\n";
5142 }
5143 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5144 // as this avoids warning in any 64bit/32bit compilation model.
5145 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5146}
5147
5148/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5149/// ivar offset.
5150void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5151 std::string &Result) {
5152 if (ivar->isBitField()) {
5153 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5154 // place all bitfields at offset 0.
5155 Result += "0";
5156 } else {
5157 Result += "__OFFSETOFIVAR__(struct ";
5158 Result += ivar->getContainingInterface()->getNameAsString();
5159 if (LangOpts.MicrosoftExt)
5160 Result += "_IMPL";
5161 Result += ", ";
5162 Result += ivar->getNameAsString();
5163 Result += ")";
5164 }
5165}
5166
5167/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5168void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5169 ObjCProtocolDecl *PDecl, StringRef prefix,
5170 StringRef ClassName, std::string &Result) {
5171 static bool objc_protocol_methods = false;
5172
5173 // Output struct protocol_methods holder of method selector and type.
5174 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
5175 /* struct protocol_methods {
5176 SEL _cmd;
5177 char *method_types;
5178 }
5179 */
5180 Result += "\nstruct _protocol_methods {\n";
5181 Result += "\tstruct objc_selector *_cmd;\n";
5182 Result += "\tchar *method_types;\n";
5183 Result += "};\n";
5184
5185 objc_protocol_methods = true;
5186 }
5187 // Do not synthesize the protocol more than once.
5188 if (ObjCSynthesizedProtocols.count(PDecl))
5189 return;
5190
5191 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5192 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5193 PDecl->instmeth_end());
5194 /* struct _objc_protocol_method_list {
5195 int protocol_method_count;
5196 struct protocol_methods protocols[];
5197 }
5198 */
5199 Result += "\nstatic struct {\n";
5200 Result += "\tint protocol_method_count;\n";
5201 Result += "\tstruct _protocol_methods protocol_methods[";
5202 Result += utostr(NumMethods);
5203 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5204 Result += PDecl->getNameAsString();
5205 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5206 "{\n\t" + utostr(NumMethods) + "\n";
5207
5208 // Output instance methods declared in this protocol.
5209 for (ObjCProtocolDecl::instmeth_iterator
5210 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5211 I != E; ++I) {
5212 if (I == PDecl->instmeth_begin())
5213 Result += "\t ,{{(struct objc_selector *)\"";
5214 else
5215 Result += "\t ,{(struct objc_selector *)\"";
5216 Result += (*I)->getSelector().getAsString();
5217 std::string MethodTypeString;
5218 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5219 Result += "\", \"";
5220 Result += MethodTypeString;
5221 Result += "\"}\n";
5222 }
5223 Result += "\t }\n};\n";
5224 }
5225
5226 // Output class methods declared in this protocol.
5227 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5228 PDecl->classmeth_end());
5229 if (NumMethods > 0) {
5230 /* struct _objc_protocol_method_list {
5231 int protocol_method_count;
5232 struct protocol_methods protocols[];
5233 }
5234 */
5235 Result += "\nstatic struct {\n";
5236 Result += "\tint protocol_method_count;\n";
5237 Result += "\tstruct _protocol_methods protocol_methods[";
5238 Result += utostr(NumMethods);
5239 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5240 Result += PDecl->getNameAsString();
5241 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5242 "{\n\t";
5243 Result += utostr(NumMethods);
5244 Result += "\n";
5245
5246 // Output instance methods declared in this protocol.
5247 for (ObjCProtocolDecl::classmeth_iterator
5248 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5249 I != E; ++I) {
5250 if (I == PDecl->classmeth_begin())
5251 Result += "\t ,{{(struct objc_selector *)\"";
5252 else
5253 Result += "\t ,{(struct objc_selector *)\"";
5254 Result += (*I)->getSelector().getAsString();
5255 std::string MethodTypeString;
5256 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5257 Result += "\", \"";
5258 Result += MethodTypeString;
5259 Result += "\"}\n";
5260 }
5261 Result += "\t }\n};\n";
5262 }
5263
5264 // Output:
5265 /* struct _objc_protocol {
5266 // Objective-C 1.0 extensions
5267 struct _objc_protocol_extension *isa;
5268 char *protocol_name;
5269 struct _objc_protocol **protocol_list;
5270 struct _objc_protocol_method_list *instance_methods;
5271 struct _objc_protocol_method_list *class_methods;
5272 };
5273 */
5274 static bool objc_protocol = false;
5275 if (!objc_protocol) {
5276 Result += "\nstruct _objc_protocol {\n";
5277 Result += "\tstruct _objc_protocol_extension *isa;\n";
5278 Result += "\tchar *protocol_name;\n";
5279 Result += "\tstruct _objc_protocol **protocol_list;\n";
5280 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5281 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5282 Result += "};\n";
5283
5284 objc_protocol = true;
5285 }
5286
5287 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5288 Result += PDecl->getNameAsString();
5289 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5290 "{\n\t0, \"";
5291 Result += PDecl->getNameAsString();
5292 Result += "\", 0, ";
5293 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5294 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5295 Result += PDecl->getNameAsString();
5296 Result += ", ";
5297 }
5298 else
5299 Result += "0, ";
5300 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5301 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5302 Result += PDecl->getNameAsString();
5303 Result += "\n";
5304 }
5305 else
5306 Result += "0\n";
5307 Result += "};\n";
5308
5309 // Mark this protocol as having been generated.
5310 if (!ObjCSynthesizedProtocols.insert(PDecl))
5311 llvm_unreachable("protocol already synthesized");
5312
5313}
5314
5315void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5316 const ObjCList<ObjCProtocolDecl> &Protocols,
5317 StringRef prefix, StringRef ClassName,
5318 std::string &Result) {
5319 if (Protocols.empty()) return;
5320
5321 for (unsigned i = 0; i != Protocols.size(); i++)
5322 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5323
5324 // Output the top lovel protocol meta-data for the class.
5325 /* struct _objc_protocol_list {
5326 struct _objc_protocol_list *next;
5327 int protocol_count;
5328 struct _objc_protocol *class_protocols[];
5329 }
5330 */
5331 Result += "\nstatic struct {\n";
5332 Result += "\tstruct _objc_protocol_list *next;\n";
5333 Result += "\tint protocol_count;\n";
5334 Result += "\tstruct _objc_protocol *class_protocols[";
5335 Result += utostr(Protocols.size());
5336 Result += "];\n} _OBJC_";
5337 Result += prefix;
5338 Result += "_PROTOCOLS_";
5339 Result += ClassName;
5340 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5341 "{\n\t0, ";
5342 Result += utostr(Protocols.size());
5343 Result += "\n";
5344
5345 Result += "\t,{&_OBJC_PROTOCOL_";
5346 Result += Protocols[0]->getNameAsString();
5347 Result += " \n";
5348
5349 for (unsigned i = 1; i != Protocols.size(); i++) {
5350 Result += "\t ,&_OBJC_PROTOCOL_";
5351 Result += Protocols[i]->getNameAsString();
5352 Result += "\n";
5353 }
5354 Result += "\t }\n};\n";
5355}
5356
5357void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5358 std::string &Result) {
5359 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5360
5361 // Explicitly declared @interface's are already synthesized.
5362 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005363 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005364 // produce correct synthesis as yet.
5365 RewriteObjCInternalStruct(CDecl, Result);
5366 }
5367
5368 // Build _objc_ivar_list metadata for classes ivars if needed
5369 unsigned NumIvars = !IDecl->ivar_empty()
5370 ? IDecl->ivar_size()
5371 : (CDecl ? CDecl->ivar_size() : 0);
5372 if (NumIvars > 0) {
5373 static bool objc_ivar = false;
5374 if (!objc_ivar) {
5375 /* struct _objc_ivar {
5376 char *ivar_name;
5377 char *ivar_type;
5378 int ivar_offset;
5379 };
5380 */
5381 Result += "\nstruct _objc_ivar {\n";
5382 Result += "\tchar *ivar_name;\n";
5383 Result += "\tchar *ivar_type;\n";
5384 Result += "\tint ivar_offset;\n";
5385 Result += "};\n";
5386
5387 objc_ivar = true;
5388 }
5389
5390 /* struct {
5391 int ivar_count;
5392 struct _objc_ivar ivar_list[nIvars];
5393 };
5394 */
5395 Result += "\nstatic struct {\n";
5396 Result += "\tint ivar_count;\n";
5397 Result += "\tstruct _objc_ivar ivar_list[";
5398 Result += utostr(NumIvars);
5399 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5400 Result += IDecl->getNameAsString();
5401 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5402 "{\n\t";
5403 Result += utostr(NumIvars);
5404 Result += "\n";
5405
5406 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5407 SmallVector<ObjCIvarDecl *, 8> IVars;
5408 if (!IDecl->ivar_empty()) {
5409 for (ObjCInterfaceDecl::ivar_iterator
5410 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5411 IV != IVEnd; ++IV)
5412 IVars.push_back(*IV);
5413 IVI = IDecl->ivar_begin();
5414 IVE = IDecl->ivar_end();
5415 } else {
5416 IVI = CDecl->ivar_begin();
5417 IVE = CDecl->ivar_end();
5418 }
5419 Result += "\t,{{\"";
5420 Result += (*IVI)->getNameAsString();
5421 Result += "\", \"";
5422 std::string TmpString, StrEncoding;
5423 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5424 QuoteDoublequotes(TmpString, StrEncoding);
5425 Result += StrEncoding;
5426 Result += "\", ";
5427 RewriteIvarOffsetComputation(*IVI, Result);
5428 Result += "}\n";
5429 for (++IVI; IVI != IVE; ++IVI) {
5430 Result += "\t ,{\"";
5431 Result += (*IVI)->getNameAsString();
5432 Result += "\", \"";
5433 std::string TmpString, StrEncoding;
5434 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5435 QuoteDoublequotes(TmpString, StrEncoding);
5436 Result += StrEncoding;
5437 Result += "\", ";
5438 RewriteIvarOffsetComputation((*IVI), Result);
5439 Result += "}\n";
5440 }
5441
5442 Result += "\t }\n};\n";
5443 }
5444
5445 // Build _objc_method_list for class's instance methods if needed
5446 SmallVector<ObjCMethodDecl *, 32>
5447 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5448
5449 // If any of our property implementations have associated getters or
5450 // setters, produce metadata for them as well.
5451 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5452 PropEnd = IDecl->propimpl_end();
5453 Prop != PropEnd; ++Prop) {
5454 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5455 continue;
5456 if (!(*Prop)->getPropertyIvarDecl())
5457 continue;
5458 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5459 if (!PD)
5460 continue;
5461 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5462 if (!Getter->isDefined())
5463 InstanceMethods.push_back(Getter);
5464 if (PD->isReadOnly())
5465 continue;
5466 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5467 if (!Setter->isDefined())
5468 InstanceMethods.push_back(Setter);
5469 }
5470 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5471 true, "", IDecl->getName(), Result);
5472
5473 // Build _objc_method_list for class's class methods if needed
5474 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5475 false, "", IDecl->getName(), Result);
5476
5477 // Protocols referenced in class declaration?
5478 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5479 "CLASS", CDecl->getName(), Result);
5480
5481 // Declaration of class/meta-class metadata
5482 /* struct _objc_class {
5483 struct _objc_class *isa; // or const char *root_class_name when metadata
5484 const char *super_class_name;
5485 char *name;
5486 long version;
5487 long info;
5488 long instance_size;
5489 struct _objc_ivar_list *ivars;
5490 struct _objc_method_list *methods;
5491 struct objc_cache *cache;
5492 struct objc_protocol_list *protocols;
5493 const char *ivar_layout;
5494 struct _objc_class_ext *ext;
5495 };
5496 */
5497 static bool objc_class = false;
5498 if (!objc_class) {
5499 Result += "\nstruct _objc_class {\n";
5500 Result += "\tstruct _objc_class *isa;\n";
5501 Result += "\tconst char *super_class_name;\n";
5502 Result += "\tchar *name;\n";
5503 Result += "\tlong version;\n";
5504 Result += "\tlong info;\n";
5505 Result += "\tlong instance_size;\n";
5506 Result += "\tstruct _objc_ivar_list *ivars;\n";
5507 Result += "\tstruct _objc_method_list *methods;\n";
5508 Result += "\tstruct objc_cache *cache;\n";
5509 Result += "\tstruct _objc_protocol_list *protocols;\n";
5510 Result += "\tconst char *ivar_layout;\n";
5511 Result += "\tstruct _objc_class_ext *ext;\n";
5512 Result += "};\n";
5513 objc_class = true;
5514 }
5515
5516 // Meta-class metadata generation.
5517 ObjCInterfaceDecl *RootClass = 0;
5518 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5519 while (SuperClass) {
5520 RootClass = SuperClass;
5521 SuperClass = SuperClass->getSuperClass();
5522 }
5523 SuperClass = CDecl->getSuperClass();
5524
5525 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5526 Result += CDecl->getNameAsString();
5527 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5528 "{\n\t(struct _objc_class *)\"";
5529 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5530 Result += "\"";
5531
5532 if (SuperClass) {
5533 Result += ", \"";
5534 Result += SuperClass->getNameAsString();
5535 Result += "\", \"";
5536 Result += CDecl->getNameAsString();
5537 Result += "\"";
5538 }
5539 else {
5540 Result += ", 0, \"";
5541 Result += CDecl->getNameAsString();
5542 Result += "\"";
5543 }
5544 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5545 // 'info' field is initialized to CLS_META(2) for metaclass
5546 Result += ", 0,2, sizeof(struct _objc_class), 0";
5547 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5548 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5549 Result += IDecl->getNameAsString();
5550 Result += "\n";
5551 }
5552 else
5553 Result += ", 0\n";
5554 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5555 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5556 Result += CDecl->getNameAsString();
5557 Result += ",0,0\n";
5558 }
5559 else
5560 Result += "\t,0,0,0,0\n";
5561 Result += "};\n";
5562
5563 // class metadata generation.
5564 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5565 Result += CDecl->getNameAsString();
5566 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5567 "{\n\t&_OBJC_METACLASS_";
5568 Result += CDecl->getNameAsString();
5569 if (SuperClass) {
5570 Result += ", \"";
5571 Result += SuperClass->getNameAsString();
5572 Result += "\", \"";
5573 Result += CDecl->getNameAsString();
5574 Result += "\"";
5575 }
5576 else {
5577 Result += ", 0, \"";
5578 Result += CDecl->getNameAsString();
5579 Result += "\"";
5580 }
5581 // 'info' field is initialized to CLS_CLASS(1) for class
5582 Result += ", 0,1";
5583 if (!ObjCSynthesizedStructs.count(CDecl))
5584 Result += ",0";
5585 else {
5586 // class has size. Must synthesize its size.
5587 Result += ",sizeof(struct ";
5588 Result += CDecl->getNameAsString();
5589 if (LangOpts.MicrosoftExt)
5590 Result += "_IMPL";
5591 Result += ")";
5592 }
5593 if (NumIvars > 0) {
5594 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5595 Result += CDecl->getNameAsString();
5596 Result += "\n\t";
5597 }
5598 else
5599 Result += ",0";
5600 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5601 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5602 Result += CDecl->getNameAsString();
5603 Result += ", 0\n\t";
5604 }
5605 else
5606 Result += ",0,0";
5607 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5608 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5609 Result += CDecl->getNameAsString();
5610 Result += ", 0,0\n";
5611 }
5612 else
5613 Result += ",0,0,0\n";
5614 Result += "};\n";
5615}
5616
5617void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5618 int ClsDefCount = ClassImplementation.size();
5619 int CatDefCount = CategoryImplementation.size();
5620
5621 // For each implemented class, write out all its meta data.
5622 for (int i = 0; i < ClsDefCount; i++)
5623 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5624
5625 // For each implemented category, write out all its meta data.
5626 for (int i = 0; i < CatDefCount; i++)
5627 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5628
5629 // Write objc_symtab metadata
5630 /*
5631 struct _objc_symtab
5632 {
5633 long sel_ref_cnt;
5634 SEL *refs;
5635 short cls_def_cnt;
5636 short cat_def_cnt;
5637 void *defs[cls_def_cnt + cat_def_cnt];
5638 };
5639 */
5640
5641 Result += "\nstruct _objc_symtab {\n";
5642 Result += "\tlong sel_ref_cnt;\n";
5643 Result += "\tSEL *refs;\n";
5644 Result += "\tshort cls_def_cnt;\n";
5645 Result += "\tshort cat_def_cnt;\n";
5646 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5647 Result += "};\n\n";
5648
5649 Result += "static struct _objc_symtab "
5650 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5651 Result += "\t0, 0, " + utostr(ClsDefCount)
5652 + ", " + utostr(CatDefCount) + "\n";
5653 for (int i = 0; i < ClsDefCount; i++) {
5654 Result += "\t,&_OBJC_CLASS_";
5655 Result += ClassImplementation[i]->getNameAsString();
5656 Result += "\n";
5657 }
5658
5659 for (int i = 0; i < CatDefCount; i++) {
5660 Result += "\t,&_OBJC_CATEGORY_";
5661 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5662 Result += "_";
5663 Result += CategoryImplementation[i]->getNameAsString();
5664 Result += "\n";
5665 }
5666
5667 Result += "};\n\n";
5668
5669 // Write objc_module metadata
5670
5671 /*
5672 struct _objc_module {
5673 long version;
5674 long size;
5675 const char *name;
5676 struct _objc_symtab *symtab;
5677 }
5678 */
5679
5680 Result += "\nstruct _objc_module {\n";
5681 Result += "\tlong version;\n";
5682 Result += "\tlong size;\n";
5683 Result += "\tconst char *name;\n";
5684 Result += "\tstruct _objc_symtab *symtab;\n";
5685 Result += "};\n\n";
5686 Result += "static struct _objc_module "
5687 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5688 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5689 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5690 Result += "};\n\n";
5691
5692 if (LangOpts.MicrosoftExt) {
5693 if (ProtocolExprDecls.size()) {
5694 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5695 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5696 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5697 E = ProtocolExprDecls.end(); I != E; ++I) {
5698 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5699 Result += (*I)->getNameAsString();
5700 Result += " = &_OBJC_PROTOCOL_";
5701 Result += (*I)->getNameAsString();
5702 Result += ";\n";
5703 }
5704 Result += "#pragma data_seg(pop)\n\n";
5705 }
5706 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5707 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5708 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5709 Result += "&_OBJC_MODULES;\n";
5710 Result += "#pragma data_seg(pop)\n\n";
5711 }
5712}
5713
5714/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5715/// implementation.
5716void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5717 std::string &Result) {
5718 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5719 // Find category declaration for this implementation.
5720 ObjCCategoryDecl *CDecl;
5721 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5722 CDecl = CDecl->getNextClassCategory())
5723 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5724 break;
5725
5726 std::string FullCategoryName = ClassDecl->getNameAsString();
5727 FullCategoryName += '_';
5728 FullCategoryName += IDecl->getNameAsString();
5729
5730 // Build _objc_method_list for class's instance methods if needed
5731 SmallVector<ObjCMethodDecl *, 32>
5732 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5733
5734 // If any of our property implementations have associated getters or
5735 // setters, produce metadata for them as well.
5736 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5737 PropEnd = IDecl->propimpl_end();
5738 Prop != PropEnd; ++Prop) {
5739 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5740 continue;
5741 if (!(*Prop)->getPropertyIvarDecl())
5742 continue;
5743 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5744 if (!PD)
5745 continue;
5746 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5747 InstanceMethods.push_back(Getter);
5748 if (PD->isReadOnly())
5749 continue;
5750 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5751 InstanceMethods.push_back(Setter);
5752 }
5753 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5754 true, "CATEGORY_", FullCategoryName.c_str(),
5755 Result);
5756
5757 // Build _objc_method_list for class's class methods if needed
5758 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5759 false, "CATEGORY_", FullCategoryName.c_str(),
5760 Result);
5761
5762 // Protocols referenced in class declaration?
5763 // Null CDecl is case of a category implementation with no category interface
5764 if (CDecl)
5765 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5766 FullCategoryName, Result);
5767 /* struct _objc_category {
5768 char *category_name;
5769 char *class_name;
5770 struct _objc_method_list *instance_methods;
5771 struct _objc_method_list *class_methods;
5772 struct _objc_protocol_list *protocols;
5773 // Objective-C 1.0 extensions
5774 uint32_t size; // sizeof (struct _objc_category)
5775 struct _objc_property_list *instance_properties; // category's own
5776 // @property decl.
5777 };
5778 */
5779
5780 static bool objc_category = false;
5781 if (!objc_category) {
5782 Result += "\nstruct _objc_category {\n";
5783 Result += "\tchar *category_name;\n";
5784 Result += "\tchar *class_name;\n";
5785 Result += "\tstruct _objc_method_list *instance_methods;\n";
5786 Result += "\tstruct _objc_method_list *class_methods;\n";
5787 Result += "\tstruct _objc_protocol_list *protocols;\n";
5788 Result += "\tunsigned int size;\n";
5789 Result += "\tstruct _objc_property_list *instance_properties;\n";
5790 Result += "};\n";
5791 objc_category = true;
5792 }
5793 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5794 Result += FullCategoryName;
5795 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5796 Result += IDecl->getNameAsString();
5797 Result += "\"\n\t, \"";
5798 Result += ClassDecl->getNameAsString();
5799 Result += "\"\n";
5800
5801 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5802 Result += "\t, (struct _objc_method_list *)"
5803 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5804 Result += FullCategoryName;
5805 Result += "\n";
5806 }
5807 else
5808 Result += "\t, 0\n";
5809 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5810 Result += "\t, (struct _objc_method_list *)"
5811 "&_OBJC_CATEGORY_CLASS_METHODS_";
5812 Result += FullCategoryName;
5813 Result += "\n";
5814 }
5815 else
5816 Result += "\t, 0\n";
5817
5818 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5819 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5820 Result += FullCategoryName;
5821 Result += "\n";
5822 }
5823 else
5824 Result += "\t, 0\n";
5825 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5826}
5827
5828// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5829/// class methods.
5830template<typename MethodIterator>
5831void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5832 MethodIterator MethodEnd,
5833 bool IsInstanceMethod,
5834 StringRef prefix,
5835 StringRef ClassName,
5836 std::string &Result) {
5837 if (MethodBegin == MethodEnd) return;
5838
5839 if (!objc_impl_method) {
5840 /* struct _objc_method {
5841 SEL _cmd;
5842 char *method_types;
5843 void *_imp;
5844 }
5845 */
5846 Result += "\nstruct _objc_method {\n";
5847 Result += "\tSEL _cmd;\n";
5848 Result += "\tchar *method_types;\n";
5849 Result += "\tvoid *_imp;\n";
5850 Result += "};\n";
5851
5852 objc_impl_method = true;
5853 }
5854
5855 // Build _objc_method_list for class's methods if needed
5856
5857 /* struct {
5858 struct _objc_method_list *next_method;
5859 int method_count;
5860 struct _objc_method method_list[];
5861 }
5862 */
5863 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5864 Result += "\nstatic struct {\n";
5865 Result += "\tstruct _objc_method_list *next_method;\n";
5866 Result += "\tint method_count;\n";
5867 Result += "\tstruct _objc_method method_list[";
5868 Result += utostr(NumMethods);
5869 Result += "];\n} _OBJC_";
5870 Result += prefix;
5871 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5872 Result += "_METHODS_";
5873 Result += ClassName;
5874 Result += " __attribute__ ((used, section (\"__OBJC, __";
5875 Result += IsInstanceMethod ? "inst" : "cls";
5876 Result += "_meth\")))= ";
5877 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5878
5879 Result += "\t,{{(SEL)\"";
5880 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5881 std::string MethodTypeString;
5882 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5883 Result += "\", \"";
5884 Result += MethodTypeString;
5885 Result += "\", (void *)";
5886 Result += MethodInternalNames[*MethodBegin];
5887 Result += "}\n";
5888 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5889 Result += "\t ,{(SEL)\"";
5890 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5891 std::string MethodTypeString;
5892 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5893 Result += "\", \"";
5894 Result += MethodTypeString;
5895 Result += "\", (void *)";
5896 Result += MethodInternalNames[*MethodBegin];
5897 Result += "}\n";
5898 }
5899 Result += "\t }\n};\n";
5900}
5901
5902Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5903 SourceRange OldRange = IV->getSourceRange();
5904 Expr *BaseExpr = IV->getBase();
5905
5906 // Rewrite the base, but without actually doing replaces.
5907 {
5908 DisableReplaceStmtScope S(*this);
5909 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5910 IV->setBase(BaseExpr);
5911 }
5912
5913 ObjCIvarDecl *D = IV->getDecl();
5914
5915 Expr *Replacement = IV;
5916 if (CurMethodDef) {
5917 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5918 const ObjCInterfaceType *iFaceDecl =
5919 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5920 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5921 // lookup which class implements the instance variable.
5922 ObjCInterfaceDecl *clsDeclared = 0;
5923 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5924 clsDeclared);
5925 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5926
5927 // Synthesize an explicit cast to gain access to the ivar.
5928 std::string RecName = clsDeclared->getIdentifier()->getName();
5929 RecName += "_IMPL";
5930 IdentifierInfo *II = &Context->Idents.get(RecName);
5931 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5932 SourceLocation(), SourceLocation(),
5933 II);
5934 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5935 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5936 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5937 CK_BitCast,
5938 IV->getBase());
5939 // Don't forget the parens to enforce the proper binding.
5940 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5941 OldRange.getEnd(),
5942 castExpr);
5943 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005944 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005945 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5946 IV->getLocation(),
5947 D->getType(),
5948 VK_LValue, OK_Ordinary);
5949 Replacement = ME;
5950 } else {
5951 IV->setBase(PE);
5952 }
5953 }
5954 } else { // we are outside a method.
5955 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5956
5957 // Explicit ivar refs need to have a cast inserted.
5958 // FIXME: consider sharing some of this code with the code above.
5959 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5960 const ObjCInterfaceType *iFaceDecl =
5961 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5962 // lookup which class implements the instance variable.
5963 ObjCInterfaceDecl *clsDeclared = 0;
5964 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5965 clsDeclared);
5966 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5967
5968 // Synthesize an explicit cast to gain access to the ivar.
5969 std::string RecName = clsDeclared->getIdentifier()->getName();
5970 RecName += "_IMPL";
5971 IdentifierInfo *II = &Context->Idents.get(RecName);
5972 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5973 SourceLocation(), SourceLocation(),
5974 II);
5975 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5976 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5977 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5978 CK_BitCast,
5979 IV->getBase());
5980 // Don't forget the parens to enforce the proper binding.
5981 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5982 IV->getBase()->getLocEnd(), castExpr);
5983 // Cannot delete IV->getBase(), since PE points to it.
5984 // Replace the old base with the cast. This is important when doing
5985 // embedded rewrites. For example, [newInv->_container addObject:0].
5986 IV->setBase(PE);
5987 }
5988 }
5989
5990 ReplaceStmtWithRange(IV, Replacement, OldRange);
5991 return Replacement;
5992}
5993