blob: b317a2fb4dc584df495fdd323aca566e8f3542d7 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000122 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
John McCallf4b88a42012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000174
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
Chris Lattner682bf922009-03-29 16:50:03 +0000182 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000183 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000184 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000185 }
186 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000187 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000188 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000189 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000190 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000191
192 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000194 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000201
Steve Naroffb619d952008-12-09 12:56:34 +0000202 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000203 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000204
Steve Naroff4c3580e2008-12-04 23:50:32 +0000205 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000206 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000214 }
Steve Naroffb619d952008-12-09 12:56:34 +0000215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000217 if (DisableReplaceStmt)
218 return;
219
Nick Lewycky7e749242010-10-31 21:07:24 +0000220 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000245 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000255 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000256 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 SilenceRewriteMacroWarning)
259 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattneraadaf782008-01-31 19:51:04 +0000261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000265 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000266 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000267 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000270 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000271 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000276 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000282 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000288 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000289 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000294 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000316
Steve Naroff54055232008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000319
Mike Stump1eb44332009-09-09 15:08:12 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000322 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000323 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000329
330 virtual void Initialize(ASTContext &context) = 0;
331
332 // Metadata Rewriting.
333 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
334 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
339 std::string &Result) = 0;
340 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
341 StringRef prefix,
342 StringRef ClassName,
343 std::string &Result) = 0;
344 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
345 std::string &Result) = 0;
346
347 // Rewriting ivar access
348 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
349 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
350 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351
352 // Misc. AST transformation routines. Somtimes they end up calling
353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Fariborz Jahanian58457172011-12-05 18:43:13 +0000359 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 void SynthCountByEnumWithState(std::string &buf);
364 void SynthMsgSendFunctionDecl();
365 void SynthMsgSendSuperFunctionDecl();
366 void SynthMsgSendStretFunctionDecl();
367 void SynthMsgSendFpretFunctionDecl();
368 void SynthMsgSendSuperStretFunctionDecl();
369 void SynthGetClassFunctionDecl();
370 void SynthGetMetaClassFunctionDecl();
371 void SynthGetSuperClassFunctionDecl();
372 void SynthSelGetUidFunctionDecl();
373 void SynthSuperContructorFunctionDecl();
374
375 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000376 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000378 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000380 std::string SynthesizeBlockImpl(BlockExpr *CE,
381 std::string Tag, std::string Desc);
382 std::string SynthesizeBlockDescriptor(std::string DescTag,
383 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000384 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000385 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000386 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000387 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000388 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000389 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000391 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Fariborz Jahanian58457172011-12-05 18:43:13 +0000393 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000394 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000395 void WarnAboutReturnGotoStmts(Stmt *S);
396 void HasReturnStmts(Stmt *S, bool &hasReturns);
397 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000402 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000403 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000404 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000405 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000406 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 // We avoid calling Type::isBlockPointerType(), since it operates on the
409 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000410 bool isTopLevelBlockPointerType(QualType T) {
411 return isa<BlockPointerType>(T);
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000414 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415 /// to a function pointer type and upon success, returns true; false
416 /// otherwise.
417 bool convertBlockPointerToFunctionPointer(QualType &T) {
418 if (isTopLevelBlockPointerType(T)) {
419 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
420 T = Context->getPointerType(BPT->getPointeeType());
421 return true;
422 }
423 return false;
424 }
425
Fariborz Jahanian58457172011-12-05 18:43:13 +0000426 bool needToScanForQualifiers(QualType T);
427 QualType getSuperStructType();
428 QualType getConstantStringStructType();
429 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000432 void convertToUnqualifiedObjCType(QualType &T) {
433 if (T->isObjCQualifiedIdType())
434 T = Context->getObjCIdType();
435 else if (T->isObjCQualifiedClassType())
436 T = Context->getObjCClassType();
437 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000438 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
439 if (const ObjCObjectPointerType * OBJPT =
440 T->getAsObjCInterfacePointerType()) {
441 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442 T = QualType(IFaceT, 0);
443 T = Context->getPointerType(T);
444 }
445 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000446 }
447
Steve Naroff54055232008-10-27 17:20:55 +0000448 // FIXME: This predicate seems like it would be useful to add to ASTContext.
449 bool isObjCType(QualType T) {
450 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
451 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Steve Naroff54055232008-10-27 17:20:55 +0000453 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff54055232008-10-27 17:20:55 +0000455 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456 OCT == Context->getCanonicalType(Context->getObjCClassType()))
457 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Ted Kremenek6217b802009-07-29 21:53:49 +0000459 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000461 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000462 return true;
463 }
464 return false;
465 }
466 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000467 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000468 void GetExtentOfArgList(const char *Name, const char *&LParen,
469 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000470
Steve Naroff621edce2009-04-29 16:37:50 +0000471 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000472 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000473 if (From[i] == '"')
474 To += "\\\"";
475 else
476 To += From[i];
477 }
478 }
John McCalle23cf432010-12-14 08:05:40 +0000479
480 QualType getSimpleFunctionType(QualType result,
481 const QualType *args,
482 unsigned numArgs,
483 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000484 if (result == Context->getObjCInstanceType())
485 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000486 FunctionProtoType::ExtProtoInfo fpi;
487 fpi.Variadic = variadic;
488 return Context->getFunctionType(result, args, numArgs, fpi);
489 }
John McCall9d125032010-01-15 18:39:57 +0000490
Fariborz Jahanian58457172011-12-05 18:43:13 +0000491 // Helper function: create a CStyleCastExpr with trivial type source info.
492 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
493 CastKind Kind, Expr *E) {
494 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
495 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
496 SourceLocation(), SourceLocation());
497 }
498 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000499
500 class RewriteObjCFragileABI : public RewriteObjC {
501 public:
502
503 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
504 DiagnosticsEngine &D, const LangOptions &LOpts,
505 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
506 D, LOpts,
507 silenceMacroWarn) {}
508
509 ~RewriteObjCFragileABI() {}
510 virtual void Initialize(ASTContext &context);
511
512 // Rewriting metadata
513 template<typename MethodIterator>
514 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
515 MethodIterator MethodEnd,
516 bool IsInstanceMethod,
517 StringRef prefix,
518 StringRef ClassName,
519 std::string &Result);
520 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
521 StringRef prefix,
522 StringRef ClassName,
523 std::string &Result);
524 virtual void RewriteObjCProtocolListMetaData(
525 const ObjCList<ObjCProtocolDecl> &Prots,
526 StringRef prefix, StringRef ClassName, std::string &Result);
527 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
528 std::string &Result);
529 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
530 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
531 std::string &Result);
532
533 // Rewriting ivar
534 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
535 std::string &Result);
536 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
537 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000538}
539
Mike Stump1eb44332009-09-09 15:08:12 +0000540void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
541 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000542 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000543 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000544 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000545 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000546 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000547 // All the args are checked/rewritten. Don't call twice!
548 RewriteBlockPointerDecl(D);
549 break;
550 }
551 }
552}
553
554void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000556 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000557 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000558}
559
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000560static bool IsHeaderFile(const std::string &Filename) {
561 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000563 if (DotPos == std::string::npos) {
564 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000565 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000566 }
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000568 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
569 // C header: .h
570 // C++ header: .hh or .H;
571 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000572}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000573
Chris Lattner5f9e2722011-07-23 10:55:15 +0000574RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000575 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000576 bool silenceMacroWarn)
577 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
578 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000579 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000580 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000581 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000582 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
583 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000584 "rewriter doesn't support user-specified control flow semantics "
585 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000586}
587
Eli Friedmanbce831b2009-05-18 22:29:17 +0000588ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000589 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000590 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000591 const LangOptions &LOpts,
592 bool SilenceRewriteMacroWarning) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000593 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000594}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000595
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000596void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000597 Context = &context;
598 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000599 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000600 MsgSendFunctionDecl = 0;
601 MsgSendSuperFunctionDecl = 0;
602 MsgSendStretFunctionDecl = 0;
603 MsgSendSuperStretFunctionDecl = 0;
604 MsgSendFpretFunctionDecl = 0;
605 GetClassFunctionDecl = 0;
606 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000607 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000608 SelGetUidFunctionDecl = 0;
609 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610 ConstantStringClassReference = 0;
611 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000612 CurMethodDef = 0;
613 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000614 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000615 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000616 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000617 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000618 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000619 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000620 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000621 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000622 PropParentMap = 0;
623 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000624 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000625 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000627 // Get the ID and start/end of the main file.
628 MainFileID = SM->getMainFileID();
629 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
630 MainFileStart = MainBuf->getBufferStart();
631 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner2c78b872009-04-14 23:22:57 +0000633 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000634}
635
Chris Lattnerf04da132007-10-24 17:06:59 +0000636//===----------------------------------------------------------------------===//
637// Top Level Driver Code
638//===----------------------------------------------------------------------===//
639
Chris Lattner682bf922009-03-29 16:50:03 +0000640void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000641 if (Diags.hasErrorOccurred())
642 return;
643
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000644 // Two cases: either the decl could be in the main file, or it could be in a
645 // #included file. If the former, rewrite it now. If the later, check to see
646 // if we rewrote the #include/#import.
647 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000648 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000649
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000650 // If this is for a builtin, ignore it.
651 if (Loc.isInvalid()) return;
652
Steve Naroffebf2b562007-10-23 23:50:29 +0000653 // Look for built-in declarations that we need to refer during the rewrite.
654 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000655 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000656 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000657 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000658 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000659 ConstantStringClassReference = FVD;
660 return;
661 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000662 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
663 if (ID->isThisDeclarationADefinition())
664 RewriteInterfaceDecl(ID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000665 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000666 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000667 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000668 if (PD->isThisDeclarationADefinition())
669 RewriteProtocolDecl(PD);
Douglas Gregord0434102009-01-09 00:49:46 +0000670 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
671 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000672 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
673 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000674 DI != DIEnd; ) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000675 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
676 if (!IFace->isThisDeclarationADefinition()) {
677 SmallVector<Decl *, 8> DG;
678 SourceLocation StartLoc = IFace->getLocStart();
679 do {
680 if (isa<ObjCInterfaceDecl>(*DI) &&
681 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
682 StartLoc == (*DI)->getLocStart())
683 DG.push_back(*DI);
684 else
685 break;
686
Douglas Gregor7723fec2011-12-15 20:29:51 +0000687 ++DI;
Douglas Gregor375bb142011-12-27 22:43:10 +0000688 } while (DI != DIEnd);
689 RewriteForwardClassDecl(DG);
690 continue;
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000691 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000692 }
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000693
694 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
695 if (!Proto->isThisDeclarationADefinition()) {
696 SmallVector<Decl *, 8> DG;
697 SourceLocation StartLoc = Proto->getLocStart();
698 do {
699 if (isa<ObjCProtocolDecl>(*DI) &&
700 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
701 StartLoc == (*DI)->getLocStart())
702 DG.push_back(*DI);
703 else
704 break;
705
706 ++DI;
707 } while (DI != DIEnd);
708 RewriteForwardProtocolDecl(DG);
709 continue;
710 }
711 }
712
Chris Lattner682bf922009-03-29 16:50:03 +0000713 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000714 ++DI;
715 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000716 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000717 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000718 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000719 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000720}
721
Chris Lattnerf04da132007-10-24 17:06:59 +0000722//===----------------------------------------------------------------------===//
723// Syntactic (non-AST) Rewriting Code
724//===----------------------------------------------------------------------===//
725
Steve Naroffb29b4272008-04-14 22:03:09 +0000726void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000727 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000728 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000729 const char *MainBufStart = MainBuf.begin();
730 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000731 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000733 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000734 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
735 if (*BufPtr == '#') {
736 if (++BufPtr == MainBufEnd)
737 return;
738 while (*BufPtr == ' ' || *BufPtr == '\t')
739 if (++BufPtr == MainBufEnd)
740 return;
741 if (!strncmp(BufPtr, "import", ImportLen)) {
742 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000743 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000744 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000745 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000746 BufPtr += ImportLen;
747 }
748 }
749 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000750}
751
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000752static std::string getIvarAccessString(ObjCIvarDecl *OID) {
753 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000754 std::string S;
755 S = "((struct ";
756 S += ClassDecl->getIdentifier()->getName();
757 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000758 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000759 return S;
760}
761
Steve Naroffa0876e82008-12-02 17:36:43 +0000762void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
763 ObjCImplementationDecl *IMD,
764 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000765 static bool objcGetPropertyDefined = false;
766 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000767 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000768 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000769 const char *startBuf = SM->getCharacterData(startLoc);
770 assert((*startBuf == '@') && "bogus @synthesize location");
771 const char *semiBuf = strchr(startBuf, ';');
772 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000773 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000774 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000775
776 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
777 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000783 if (!OID)
784 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000785 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000786 if (!PD->getGetterMethodDecl()->isDefined()) {
787 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
788 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
789 ObjCPropertyDecl::OBJC_PR_copy));
790 std::string Getr;
791 if (GenGetProperty && !objcGetPropertyDefined) {
792 objcGetPropertyDefined = true;
793 // FIXME. Is this attribute correct in all cases?
794 Getr = "\nextern \"C\" __declspec(dllimport) "
795 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000796 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000797 RewriteObjCMethodDecl(OID->getContainingInterface(),
798 PD->getGetterMethodDecl(), Getr);
799 Getr += "{ ";
800 // Synthesize an explicit cast to gain access to the ivar.
801 // See objc-act.c:objc_synthesize_new_getter() for details.
802 if (GenGetProperty) {
803 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
804 Getr += "typedef ";
805 const FunctionType *FPRetType = 0;
806 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
807 FPRetType);
808 Getr += " _TYPE";
809 if (FPRetType) {
810 Getr += ")"; // close the precedence "scope" for "*".
811
812 // Now, emit the argument types (if any).
813 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
814 Getr += "(";
815 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
816 if (i) Getr += ", ";
817 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000818 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000819 Getr += ParamStr;
820 }
821 if (FT->isVariadic()) {
822 if (FT->getNumArgs()) Getr += ", ";
823 Getr += "...";
824 }
825 Getr += ")";
826 } else
827 Getr += "()";
828 }
829 Getr += ";\n";
830 Getr += "return (_TYPE)";
831 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000832 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000833 Getr += ", 1)";
834 }
835 else
836 Getr += "return " + getIvarAccessString(OID);
837 Getr += "; }";
838 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000839 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000840
841 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000842 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Steve Naroffeb0646c2008-12-02 15:48:25 +0000844 // Generate the 'setter' function.
845 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000846 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
847 ObjCPropertyDecl::OBJC_PR_copy);
848 if (GenSetProperty && !objcSetPropertyDefined) {
849 objcSetPropertyDefined = true;
850 // FIXME. Is this attribute correct in all cases?
851 Setr = "\nextern \"C\" __declspec(dllimport) "
852 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
853 }
854
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000855 RewriteObjCMethodDecl(OID->getContainingInterface(),
856 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000857 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000858 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000859 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000860 if (GenSetProperty) {
861 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000862 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000863 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000864 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000865 Setr += ", ";
866 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
867 Setr += "0, ";
868 else
869 Setr += "1, ";
870 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
871 Setr += "1)";
872 else
873 Setr += "0)";
874 }
875 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000876 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000877 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000879 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000880 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000881}
Chris Lattner8a12c272007-10-11 18:38:32 +0000882
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000883static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
884 std::string &typedefString) {
885 typedefString += "#ifndef _REWRITER_typedef_";
886 typedefString += ForwardDecl->getNameAsString();
887 typedefString += "\n";
888 typedefString += "#define _REWRITER_typedef_";
889 typedefString += ForwardDecl->getNameAsString();
890 typedefString += "\n";
891 typedefString += "typedef struct objc_object ";
892 typedefString += ForwardDecl->getNameAsString();
893 typedefString += ";\n#endif\n";
894}
895
Douglas Gregor375bb142011-12-27 22:43:10 +0000896void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000897 const std::string &typedefString) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000898 SourceLocation startLoc = ClassDecl->getLocStart();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000899 const char *startBuf = SM->getCharacterData(startLoc);
900 const char *semiPtr = strchr(startBuf, ';');
901 // Replace the @class with typedefs corresponding to the classes.
902 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
903}
904
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000905void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000906 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000907 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000908 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000909 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000910 // Translate to typedef's that forward reference structs with the same name
911 // as the class. As a convenience, we include the original declaration
912 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000913 typedefString += "// @class ";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000915 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000916 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000917 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000918 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000919 DeclGroupRef::iterator I = D.begin();
Douglas Gregor375bb142011-12-27 22:43:10 +0000920 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000921}
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000923void RewriteObjC::RewriteForwardClassDecl(
924 const llvm::SmallVector<Decl*, 8> &D) {
925 std::string typedefString;
926 for (unsigned i = 0; i < D.size(); i++) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000927 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000928 if (i == 0) {
929 typedefString += "// @class ";
930 typedefString += ForwardDecl->getNameAsString();
931 typedefString += ";\n";
932 }
933 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
934 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000935 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000936}
937
Steve Naroffb29b4272008-04-14 22:03:09 +0000938void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000939 // When method is a synthesized one, such as a getter/setter there is
940 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000941 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000942 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000943 SourceLocation LocStart = Method->getLocStart();
944 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Chandler Carruth64211622011-07-25 21:09:52 +0000946 if (SM->getExpansionLineNumber(LocEnd) >
947 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000948 InsertText(LocStart, "#if 0\n");
949 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000950 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000951 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000952 }
953}
954
Mike Stump1eb44332009-09-09 15:08:12 +0000955void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000956 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000959 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000960}
961
Steve Naroffb29b4272008-04-14 22:03:09 +0000962void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000963 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Steve Naroff423cb562007-10-30 13:30:57 +0000965 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000966 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000968 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
969 E = CatDecl->prop_end(); I != E; ++I)
970 RewriteProperty(*I);
971
Mike Stump1eb44332009-09-09 15:08:12 +0000972 for (ObjCCategoryDecl::instmeth_iterator
973 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000974 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000975 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000976 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000977 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000978 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000979 RewriteMethodDeclaration(*I);
980
Steve Naroff423cb562007-10-30 13:30:57 +0000981 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000982 ReplaceText(CatDecl->getAtEndRange().getBegin(),
983 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000984}
985
Steve Naroffb29b4272008-04-14 22:03:09 +0000986void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000987 SourceLocation LocStart = PDecl->getLocStart();
Douglas Gregor61cc2962012-01-02 02:00:30 +0000988 assert(PDecl->isThisDeclarationADefinition());
989
Steve Naroff752d6ef2007-10-30 16:42:30 +0000990 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000991 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000992
993 for (ObjCProtocolDecl::instmeth_iterator
994 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000995 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000996 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000997 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000998 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000999 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001000 RewriteMethodDeclaration(*I);
1001
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001002 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1003 E = PDecl->prop_end(); I != E; ++I)
1004 RewriteProperty(*I);
1005
Steve Naroff752d6ef2007-10-30 16:42:30 +00001006 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001007 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001008 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001009
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001010 // Must comment out @optional/@required
1011 const char *startBuf = SM->getCharacterData(LocStart);
1012 const char *endBuf = SM->getCharacterData(LocEnd);
1013 for (const char *p = startBuf; p < endBuf; p++) {
1014 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001015 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001016 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001017
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001018 }
1019 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001020 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001021 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001023 }
1024 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001025}
1026
Douglas Gregorbd9482d2012-01-01 21:23:57 +00001027void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1028 SourceLocation LocStart = (*D.begin())->getLocStart();
1029 if (LocStart.isInvalid())
1030 llvm_unreachable("Invalid SourceLocation");
1031 // FIXME: handle forward protocol that are declared across multiple lines.
1032 ReplaceText(LocStart, 0, "// ");
1033}
1034
1035void
1036RewriteObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1037 SourceLocation LocStart = DG[0]->getLocStart();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001038 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001039 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001040 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001041 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001042}
1043
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001044void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1045 const FunctionType *&FPRetType) {
1046 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001047 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001048 else if (T->isFunctionPointerType() ||
1049 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001050 // needs special handling, since pointer-to-functions have special
1051 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001052 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001053 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001054 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001055 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001056 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001057 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001058 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001059 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001060 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001061 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001062 }
1063 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001064 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001065}
1066
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001067void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1068 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001069 std::string &ResultStr) {
1070 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1071 const FunctionType *FPRetType = 0;
1072 ResultStr += "\nstatic ";
1073 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001074 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001076 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001077 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001079 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001080 NameStr += "_I_";
1081 else
1082 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001084 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001085 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001086
1087 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001088 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001090 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001091 }
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001093 {
1094 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 int len = selString.size();
1096 for (int i = 0; i < len; i++)
1097 if (selString[i] == ':')
1098 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001099 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001101 // Remember this name for metadata emission
1102 MethodInternalNames[OMD] = NameStr;
1103 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001105 // Rewrite arguments
1106 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001109 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001110 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001111 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001112 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001113 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001114 ResultStr += "struct ";
1115 }
1116 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001117 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001118 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 }
1120 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001121 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001122 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001125 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001129 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1130 E = OMD->param_end(); PI != E; ++PI) {
1131 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001133 if (PDecl->getType()->isObjCQualifiedIdType()) {
1134 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001135 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001136 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001137 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001138 QualType QT = PDecl->getType();
1139 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1140 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001141 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001142 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001143 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001144 ResultStr += Name;
1145 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001147 if (OMD->isVariadic())
1148 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001149 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Steve Naroff76e429d2008-07-16 14:40:40 +00001151 if (FPRetType) {
1152 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001155 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001156 ResultStr += "(";
1157 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1158 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001159 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001160 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001161 ResultStr += ParamStr;
1162 }
1163 if (FT->isVariadic()) {
1164 if (FT->getNumArgs()) ResultStr += ", ";
1165 ResultStr += "...";
1166 }
1167 ResultStr += ")";
1168 } else {
1169 ResultStr += "()";
1170 }
1171 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001173void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001174 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1175 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001177 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001179 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001180 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1181 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001182 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001183 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001184 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001185 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001186 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001187 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001188
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001189 const char *startBuf = SM->getCharacterData(LocStart);
1190 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001191 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001192 }
Mike Stump1eb44332009-09-09 15:08:12 +00001193
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001195 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1196 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001197 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001198 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001199 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001200 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001201 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001202 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001204 const char *startBuf = SM->getCharacterData(LocStart);
1205 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001206 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001207 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001208 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001209 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001210 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001211 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001212 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001213 }
1214
Benjamin Kramerd999b372010-02-14 14:14:16 +00001215 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001216}
1217
Steve Naroffb29b4272008-04-14 22:03:09 +00001218void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001219 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001220 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001221 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001222 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001223 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001224 ResultStr += "\n";
1225 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001226 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001227 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001228 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001229 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001230 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001231 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001232 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001233 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001234 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
1236 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001237 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001238 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001239 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001241 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001242 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001243 for (ObjCInterfaceDecl::classmeth_iterator
1244 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001245 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001246 RewriteMethodDeclaration(*I);
1247
Steve Naroff2feac5e2007-10-30 03:43:13 +00001248 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001249 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1250 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001251}
1252
John McCall4b9c2d22011-11-06 09:01:30 +00001253Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1254 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001255
John McCall4b9c2d22011-11-06 09:01:30 +00001256 // We just magically know some things about the structure of this
1257 // expression.
1258 ObjCMessageExpr *OldMsg =
1259 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1260 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001261
John McCall4b9c2d22011-11-06 09:01:30 +00001262 // Because the rewriter doesn't allow us to rewrite rewritten code,
1263 // we need to suppress rewriting the sub-statements.
1264 Expr *Base, *RHS;
1265 {
1266 DisableReplaceStmtScope S(*this);
1267
1268 // Rebuild the base expression if we have one.
1269 Base = 0;
1270 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1271 Base = OldMsg->getInstanceReceiver();
1272 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1273 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1274 }
1275
1276 // Rebuild the RHS.
1277 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1278 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1279 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1280 }
1281
1282 // TODO: avoid this copy.
1283 SmallVector<SourceLocation, 1> SelLocs;
1284 OldMsg->getSelectorLocs(SelLocs);
1285
Chad Rosier0774ba72012-01-06 20:05:14 +00001286 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001287 switch (OldMsg->getReceiverKind()) {
1288 case ObjCMessageExpr::Class:
1289 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1290 OldMsg->getValueKind(),
1291 OldMsg->getLeftLoc(),
1292 OldMsg->getClassReceiverTypeInfo(),
1293 OldMsg->getSelector(),
1294 SelLocs,
1295 OldMsg->getMethodDecl(),
1296 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001297 OldMsg->getRightLoc(),
1298 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001299 break;
1300
1301 case ObjCMessageExpr::Instance:
1302 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1303 OldMsg->getValueKind(),
1304 OldMsg->getLeftLoc(),
1305 Base,
1306 OldMsg->getSelector(),
1307 SelLocs,
1308 OldMsg->getMethodDecl(),
1309 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001310 OldMsg->getRightLoc(),
1311 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001312 break;
1313
1314 case ObjCMessageExpr::SuperClass:
1315 case ObjCMessageExpr::SuperInstance:
1316 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1317 OldMsg->getValueKind(),
1318 OldMsg->getLeftLoc(),
1319 OldMsg->getSuperLoc(),
1320 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1321 OldMsg->getSuperType(),
1322 OldMsg->getSelector(),
1323 SelLocs,
1324 OldMsg->getMethodDecl(),
1325 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001326 OldMsg->getRightLoc(),
1327 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001328 break;
1329 }
1330
1331 Stmt *Replacement = SynthMessageExpr(NewMsg);
1332 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1333 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001334}
1335
John McCall4b9c2d22011-11-06 09:01:30 +00001336Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1337 SourceRange OldRange = PseudoOp->getSourceRange();
1338
1339 // We just magically know some things about the structure of this
1340 // expression.
1341 ObjCMessageExpr *OldMsg =
1342 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1343
1344 // Because the rewriter doesn't allow us to rewrite rewritten code,
1345 // we need to suppress rewriting the sub-statements.
1346 Expr *Base = 0;
1347 {
1348 DisableReplaceStmtScope S(*this);
1349
1350 // Rebuild the base expression if we have one.
1351 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1352 Base = OldMsg->getInstanceReceiver();
1353 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1354 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001355 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001356 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001357
John McCall4b9c2d22011-11-06 09:01:30 +00001358 // Intentionally empty.
1359 SmallVector<SourceLocation, 1> SelLocs;
1360 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001361
Chad Rosier0774ba72012-01-06 20:05:14 +00001362 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001363 switch (OldMsg->getReceiverKind()) {
1364 case ObjCMessageExpr::Class:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 OldMsg->getClassReceiverTypeInfo(),
1369 OldMsg->getSelector(),
1370 SelLocs,
1371 OldMsg->getMethodDecl(),
1372 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001373 OldMsg->getRightLoc(),
1374 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001375 break;
1376
1377 case ObjCMessageExpr::Instance:
1378 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1379 OldMsg->getValueKind(),
1380 OldMsg->getLeftLoc(),
1381 Base,
1382 OldMsg->getSelector(),
1383 SelLocs,
1384 OldMsg->getMethodDecl(),
1385 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001386 OldMsg->getRightLoc(),
1387 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001388 break;
1389
1390 case ObjCMessageExpr::SuperClass:
1391 case ObjCMessageExpr::SuperInstance:
1392 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1393 OldMsg->getValueKind(),
1394 OldMsg->getLeftLoc(),
1395 OldMsg->getSuperLoc(),
1396 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1397 OldMsg->getSuperType(),
1398 OldMsg->getSelector(),
1399 SelLocs,
1400 OldMsg->getMethodDecl(),
1401 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001402 OldMsg->getRightLoc(),
1403 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001404 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001405 }
John McCall4b9c2d22011-11-06 09:01:30 +00001406
1407 Stmt *Replacement = SynthMessageExpr(NewMsg);
1408 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1409 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001410}
1411
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001412/// SynthCountByEnumWithState - To print:
1413/// ((unsigned int (*)
1414/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001415/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001417/// "countByEnumeratingWithState:objects:count:"),
1418/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001419/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420///
Steve Naroffb29b4272008-04-14 22:03:09 +00001421void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1423 "id *, unsigned int))(void *)objc_msgSend)";
1424 buf += "\n\t\t";
1425 buf += "((id)l_collection,\n\t\t";
1426 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1427 buf += "\n\t\t";
1428 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001429 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001430}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001431
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001432/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1433/// statement to exit to its outer synthesized loop.
1434///
Steve Naroffb29b4272008-04-14 22:03:09 +00001435Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001436 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1437 return S;
1438 // replace break with goto __break_label
1439 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001441 SourceLocation startLoc = S->getLocStart();
1442 buf = "goto __break_label_";
1443 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001444 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001445
1446 return 0;
1447}
1448
1449/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1450/// statement to continue with its inner synthesized loop.
1451///
Steve Naroffb29b4272008-04-14 22:03:09 +00001452Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001453 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1454 return S;
1455 // replace continue with goto __continue_label
1456 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458 SourceLocation startLoc = S->getLocStart();
1459 buf = "goto __continue_label_";
1460 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001461 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001463 return 0;
1464}
1465
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001466/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001467/// It rewrites:
1468/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001470/// Into:
1471/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001472/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001474/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001475/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001476/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001477/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001478/// if (limit) {
1479/// unsigned long startMutations = *enumState.mutationsPtr;
1480/// do {
1481/// unsigned long counter = 0;
1482/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001483/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001484/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001485/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001486/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001487/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001488/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001489/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001490/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001492/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001493/// }
1494/// else
1495/// elem = nil;
1496/// }
1497///
Steve Naroffb29b4272008-04-14 22:03:09 +00001498Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001499 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001500 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001501 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001502 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001503 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001504 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001506 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001507 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001509 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 std::string buf;
1511 buf = "\n{\n\t";
1512 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1513 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001514 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001515 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001516 if (ElementType->isObjCQualifiedIdType() ||
1517 ElementType->isObjCQualifiedInterfaceType())
1518 // Simply use 'id' for all qualified types.
1519 elementTypeAsString = "id";
1520 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001521 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001522 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001524 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 buf += elementName;
1526 buf += ";\n\t";
1527 }
Chris Lattner06767512008-04-08 05:52:18 +00001528 else {
1529 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001530 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001531 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1532 if (VD->getType()->isObjCQualifiedIdType() ||
1533 VD->getType()->isObjCQualifiedInterfaceType())
1534 // Simply use 'id' for all qualified types.
1535 elementTypeAsString = "id";
1536 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001537 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001540 // struct __objcFastEnumerationState enumState = { 0 };
1541 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001542 // id __rw_items[16];
1543 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 // id l_collection = (id)
1545 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001546 // Find start location of 'collection' the hard way!
1547 const char *startCollectionBuf = startBuf;
1548 startCollectionBuf += 3; // skip 'for'
1549 startCollectionBuf = strchr(startCollectionBuf, '(');
1550 startCollectionBuf++; // skip '('
1551 // find 'in' and skip it.
1552 while (*startCollectionBuf != ' ' ||
1553 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1554 (*(startCollectionBuf+3) != ' ' &&
1555 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1556 startCollectionBuf++;
1557 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001558
1559 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001560 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001561 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001562 SourceLocation rightParenLoc = S->getRParenLoc();
1563 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001564 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001568 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 // ((unsigned int (*)
1572 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001575 // "countByEnumeratingWithState:objects:count:"),
1576 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001577 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001578 buf += "unsigned long limit =\n\t\t";
1579 SynthCountByEnumWithState(buf);
1580 buf += ";\n\t";
1581 /// if (limit) {
1582 /// unsigned long startMutations = *enumState.mutationsPtr;
1583 /// do {
1584 /// unsigned long counter = 0;
1585 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001586 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001588 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001589 buf += "if (limit) {\n\t";
1590 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1591 buf += "do {\n\t\t";
1592 buf += "unsigned long counter = 0;\n\t\t";
1593 buf += "do {\n\t\t\t";
1594 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1595 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1596 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001597 buf += " = (";
1598 buf += elementTypeAsString;
1599 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001601 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001603 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001604 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001605 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001606 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001609 /// }
1610 /// else
1611 /// elem = nil;
1612 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001613 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001614 buf = ";\n\t";
1615 buf += "__continue_label_";
1616 buf += utostr(ObjCBcLabelNo.back());
1617 buf += ": ;";
1618 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001619 buf += "} while (counter < limit);\n\t";
1620 buf += "} while (limit = ";
1621 SynthCountByEnumWithState(buf);
1622 buf += ");\n\t";
1623 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001624 buf += " = ((";
1625 buf += elementTypeAsString;
1626 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001627 buf += "__break_label_";
1628 buf += utostr(ObjCBcLabelNo.back());
1629 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630 buf += "}\n\t";
1631 buf += "else\n\t\t";
1632 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001633 buf += " = ((";
1634 buf += elementTypeAsString;
1635 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001636 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001638 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001639 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001640 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001641 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001642 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001643 } else {
1644 /* Need to treat single statements specially. For example:
1645 *
1646 * for (A *a in b) if (stuff()) break;
1647 * for (A *a in b) xxxyy;
1648 *
1649 * The following code simply scans ahead to the semi to find the actual end.
1650 */
1651 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1652 const char *semiBuf = strchr(stmtBuf, ';');
1653 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001654 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001655 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001656 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001657 Stmts.pop_back();
1658 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001659 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001660}
1661
Mike Stump1eb44332009-09-09 15:08:12 +00001662/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001663/// This routine rewrites @synchronized(expr) stmt;
1664/// into:
1665/// objc_sync_enter(expr);
1666/// @try stmt @finally { objc_sync_exit(expr); }
1667///
Steve Naroffb29b4272008-04-14 22:03:09 +00001668Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001669 // Get the start location and compute the semi location.
1670 SourceLocation startLoc = S->getLocStart();
1671 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001672
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001673 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001674
1675 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001676 buf = "objc_sync_enter((id)";
1677 const char *lparenBuf = startBuf;
1678 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001679 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001680 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1681 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001682 // been rewritten! (which implies the SourceLocation's are invalid).
1683 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001684 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001685 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001686 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001687 buf = ");\n";
1688 // declare a new scope with two variables, _stack and _rethrow.
1689 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1690 buf += "int buf[18/*32-bit i386*/];\n";
1691 buf += "char *pointers[4];} _stack;\n";
1692 buf += "id volatile _rethrow = 0;\n";
1693 buf += "objc_exception_try_enter(&_stack);\n";
1694 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001695 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001696 startLoc = S->getSynchBody()->getLocEnd();
1697 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Steve Naroffc7089f12008-08-19 13:04:19 +00001699 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001700 SourceLocation lastCurlyLoc = startLoc;
1701 buf = "}\nelse {\n";
1702 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001703 buf += "}\n";
1704 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001705 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001706
1707 std::string syncBuf;
1708 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001709
1710 Expr *syncExpr = S->getSynchExpr();
1711 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1712 ? CK_BitCast :
1713 syncExpr->getType()->isBlockPointerType()
1714 ? CK_BlockPointerToObjCPointerCast
1715 : CK_CPointerToObjCPointerCast;
1716 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1717 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001718 std::string syncExprBufS;
1719 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001720 syncExpr->printPretty(syncExprBuf, *Context, 0,
1721 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001722 syncBuf += syncExprBuf.str();
1723 syncBuf += ");";
1724
1725 buf += syncBuf;
1726 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001727 buf += "}\n";
1728 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001729
Benjamin Kramerd999b372010-02-14 14:14:16 +00001730 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001731
1732 bool hasReturns = false;
1733 HasReturnStmts(S->getSynchBody(), hasReturns);
1734 if (hasReturns)
1735 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1736
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001737 return 0;
1738}
1739
Steve Naroffb85e77a2009-12-05 21:43:12 +00001740void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1741{
Steve Naroff8c565152008-12-05 17:03:39 +00001742 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001743 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001744 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001745 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001746
Steve Naroffb85e77a2009-12-05 21:43:12 +00001747 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001749 TryFinallyContainsReturnDiag);
1750 }
1751 return;
1752}
1753
Steve Naroffb85e77a2009-12-05 21:43:12 +00001754void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1755{
1756 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001757 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001758 if (*CI)
1759 HasReturnStmts(*CI, hasReturns);
1760
1761 if (isa<ReturnStmt>(S))
1762 hasReturns = true;
1763 return;
1764}
1765
1766void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1767 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001768 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001769 if (*CI) {
1770 RewriteTryReturnStmts(*CI);
1771 }
1772 if (isa<ReturnStmt>(S)) {
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
1775
1776 const char *semiBuf = strchr(startBuf, ';');
1777 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001778 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001779
1780 std::string buf;
1781 buf = "{ objc_exception_try_exit(&_stack); return";
1782
Benjamin Kramerd999b372010-02-14 14:14:16 +00001783 ReplaceText(startLoc, 6, buf);
1784 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001785 }
1786 return;
1787}
1788
1789void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1790 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001791 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001792 if (*CI) {
1793 RewriteSyncReturnStmts(*CI, syncExitBuf);
1794 }
1795 if (isa<ReturnStmt>(S)) {
1796 SourceLocation startLoc = S->getLocStart();
1797 const char *startBuf = SM->getCharacterData(startLoc);
1798
1799 const char *semiBuf = strchr(startBuf, ';');
1800 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001801 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001802
1803 std::string buf;
1804 buf = "{ objc_exception_try_exit(&_stack);";
1805 buf += syncExitBuf;
1806 buf += " return";
1807
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(startLoc, 6, buf);
1809 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001810 }
1811 return;
1812}
1813
Steve Naroffb29b4272008-04-14 22:03:09 +00001814Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001815 // Get the start location and compute the semi location.
1816 SourceLocation startLoc = S->getLocStart();
1817 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Steve Naroff75730982007-11-07 04:08:17 +00001819 assert((*startBuf == '@') && "bogus @try location");
1820
1821 std::string buf;
1822 // declare a new scope with two variables, _stack and _rethrow.
1823 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1824 buf += "int buf[18/*32-bit i386*/];\n";
1825 buf += "char *pointers[4];} _stack;\n";
1826 buf += "id volatile _rethrow = 0;\n";
1827 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001828 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001829
Benjamin Kramerd999b372010-02-14 14:14:16 +00001830 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Steve Naroff75730982007-11-07 04:08:17 +00001832 startLoc = S->getTryBody()->getLocEnd();
1833 startBuf = SM->getCharacterData(startLoc);
1834
1835 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001836
Steve Naroff75730982007-11-07 04:08:17 +00001837 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001838 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001839 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001840 buf = " /* @catch begin */ else {\n";
1841 buf += " id _caught = objc_exception_extract(&_stack);\n";
1842 buf += " objc_exception_try_enter (&_stack);\n";
1843 buf += " if (_setjmp(_stack.buf))\n";
1844 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1845 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Benjamin Kramerd999b372010-02-14 14:14:16 +00001847 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001848 } else { /* no catch list */
1849 buf = "}\nelse {\n";
1850 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1851 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001852 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001853 }
Steve Naroff75730982007-11-07 04:08:17 +00001854 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001855 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1856 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001857 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001858
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001859 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001860 buf = "if ("; // we are generating code for the first catch clause
1861 else
1862 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001863 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001864 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Steve Naroff75730982007-11-07 04:08:17 +00001866 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Steve Naroff75730982007-11-07 04:08:17 +00001868 const char *lParenLoc = strchr(startBuf, '(');
1869
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001870 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001871 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001872 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001873 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1874 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001875 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001876 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001877 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Steve Naroffe12e6922008-02-01 20:02:07 +00001879 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001880 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001881 } else if (catchDecl) {
1882 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001883 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001884 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001885 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001886 } else if (const ObjCObjectPointerType *Ptr =
1887 t->getAs<ObjCObjectPointerType>()) {
1888 // Should be a pointer to a class.
1889 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1890 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001891 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001892 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001893 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001894 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001895 }
1896 }
1897 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001898 lastCatchBody = Catch->getCatchBody();
1899 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001900 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1901 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1902 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1903 assert((*rParenBuf == ')') && "bogus @catch paren location");
1904 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Mike Stump1eb44332009-09-09 15:08:12 +00001906 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001907 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001908 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001909 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001910 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001911 }
Steve Naroff75730982007-11-07 04:08:17 +00001912 }
1913 // Complete the catch list...
1914 if (lastCatchBody) {
1915 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001916 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1917 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Steve Naroff378f47a2008-09-11 15:29:03 +00001919 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001920 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001921 buf = "} /* last catch end */\n";
1922 buf += "else {\n";
1923 buf += " _rethrow = _caught;\n";
1924 buf += " objc_exception_try_exit(&_stack);\n";
1925 buf += "} } /* @catch end */\n";
1926 if (!S->getFinallyStmt())
1927 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001928 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Steve Naroff75730982007-11-07 04:08:17 +00001930 // Set lastCurlyLoc
1931 lastCurlyLoc = lastCatchBody->getLocEnd();
1932 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001933 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001934 startLoc = finalStmt->getLocStart();
1935 startBuf = SM->getCharacterData(startLoc);
1936 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001939
Steve Naroff75730982007-11-07 04:08:17 +00001940 Stmt *body = finalStmt->getFinallyBody();
1941 SourceLocation startLoc = body->getLocStart();
1942 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001943 assert(*SM->getCharacterData(startLoc) == '{' &&
1944 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001945 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001946 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001948 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001949 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001950 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001951 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Steve Naroff75730982007-11-07 04:08:17 +00001953 // Set lastCurlyLoc
1954 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001955
Steve Naroff8c565152008-12-05 17:03:39 +00001956 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001957 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001958 } else { /* no finally clause - make sure we synthesize an implicit one */
1959 buf = "{ /* implicit finally clause */\n";
1960 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1961 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1962 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001963 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001964
1965 // Now check for any return/continue/go statements within the @try.
1966 // The implicit finally clause won't called if the @try contains any
1967 // jump statements.
1968 bool hasReturns = false;
1969 HasReturnStmts(S->getTryBody(), hasReturns);
1970 if (hasReturns)
1971 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001972 }
1973 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001974 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001975 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001976 return 0;
1977}
1978
Mike Stump1eb44332009-09-09 15:08:12 +00001979// This can't be done with ReplaceStmt(S, ThrowExpr), since
1980// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001981// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001983 // Get the start location and compute the semi location.
1984 SourceLocation startLoc = S->getLocStart();
1985 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff2bd03922007-11-07 15:32:26 +00001987 assert((*startBuf == '@') && "bogus @throw location");
1988
1989 std::string buf;
1990 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001991 if (S->getThrowExpr())
1992 buf = "objc_exception_throw(";
1993 else // add an implicit argument
1994 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001996 // handle "@ throw" correctly.
1997 const char *wBuf = strchr(startBuf, 'w');
1998 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001999 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Steve Naroff2bd03922007-11-07 15:32:26 +00002001 const char *semiBuf = strchr(startBuf, ';');
2002 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002003 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002004 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002005 return 0;
2006}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002007
Steve Naroffb29b4272008-04-14 22:03:09 +00002008Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002009 // Create a new string expression.
2010 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002011 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002012 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002013 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002014 StringLiteral::Ascii, false,
2015 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002016 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Chris Lattner07506182007-11-30 22:53:43 +00002018 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002019 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002020 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002021}
2022
Steve Naroffb29b4272008-04-14 22:03:09 +00002023Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002024 if (!SelGetUidFunctionDecl)
2025 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002026 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2027 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002028 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002029 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002030 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002031 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002032 StringLiteral::Ascii, false,
2033 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002034 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2035 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002036 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002037 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002038 return SelExp;
2039}
2040
Steve Naroffb29b4272008-04-14 22:03:09 +00002041CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002042 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2043 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002044 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002045 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Steve Naroffebf2b562007-10-23 23:50:29 +00002047 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002048 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2049 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Steve Naroffebf2b562007-10-23 23:50:29 +00002051 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002052 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002053 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002054 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002055 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
John McCall183700f2009-09-21 23:43:11 +00002057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002059 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002060 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002061 FT->getCallResultType(*Context),
2062 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002063 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002064}
2065
Steve Naroffd5255f52007-11-01 13:24:47 +00002066static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2067 const char *&startRef, const char *&endRef) {
2068 while (startBuf < endBuf) {
2069 if (*startBuf == '<')
2070 startRef = startBuf; // mark the start.
2071 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002072 if (startRef && *startRef == '<') {
2073 endRef = startBuf; // mark the end.
2074 return true;
2075 }
2076 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002077 }
2078 startBuf++;
2079 }
2080 return false;
2081}
2082
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002083static void scanToNextArgument(const char *&argRef) {
2084 int angle = 0;
2085 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2086 if (*argRef == '<')
2087 angle++;
2088 else if (*argRef == '>')
2089 angle--;
2090 argRef++;
2091 }
2092 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2093}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002094
Steve Naroffb29b4272008-04-14 22:03:09 +00002095bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002096 if (T->isObjCQualifiedIdType())
2097 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002098 if (const PointerType *PT = T->getAs<PointerType>()) {
2099 if (PT->getPointeeType()->isObjCQualifiedIdType())
2100 return true;
2101 }
2102 if (T->isObjCObjectPointerType()) {
2103 T = T->getPointeeType();
2104 return T->isObjCQualifiedInterfaceType();
2105 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002106 if (T->isArrayType()) {
2107 QualType ElemTy = Context->getBaseElementType(T);
2108 return needToScanForQualifiers(ElemTy);
2109 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002110 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002111}
2112
Steve Naroff4f95b752008-07-29 18:15:38 +00002113void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2114 QualType Type = E->getType();
2115 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002117
Steve Naroffcda658e2008-11-19 21:15:47 +00002118 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2119 Loc = ECE->getLParenLoc();
2120 EndLoc = ECE->getRParenLoc();
2121 } else {
2122 Loc = E->getLocStart();
2123 EndLoc = E->getLocEnd();
2124 }
2125 // This will defend against trying to rewrite synthesized expressions.
2126 if (Loc.isInvalid() || EndLoc.isInvalid())
2127 return;
2128
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002130 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 const char *startRef = 0, *endRef = 0;
2132 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2133 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002134 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2135 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002136 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002137 InsertText(LessLoc, "/*");
2138 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002139 }
2140 }
2141}
2142
Steve Naroffb29b4272008-04-14 22:03:09 +00002143void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002144 SourceLocation Loc;
2145 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002146 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002147 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2148 Loc = VD->getLocation();
2149 Type = VD->getType();
2150 }
2151 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2152 Loc = FD->getLocation();
2153 // Check for ObjC 'id' and class types that have been adorned with protocol
2154 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002155 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002157 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 if (!proto)
2159 return;
2160 Type = proto->getResultType();
2161 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002162 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2163 Loc = FD->getLocation();
2164 Type = FD->getType();
2165 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002166 else
2167 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002169 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Steve Naroffd5255f52007-11-01 13:24:47 +00002172 const char *endBuf = SM->getCharacterData(Loc);
2173 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002174 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002175 startBuf--; // scan backward (from the decl location) for return type.
2176 const char *startRef = 0, *endRef = 0;
2177 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2178 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002179 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2180 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002181 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002182 InsertText(LessLoc, "/*");
2183 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002184 }
2185 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002186 if (!proto)
2187 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002188 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002189 const char *startBuf = SM->getCharacterData(Loc);
2190 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002191 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2192 if (needToScanForQualifiers(proto->getArgType(i))) {
2193 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffd5255f52007-11-01 13:24:47 +00002195 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002196 // scan forward (from the decl location) for argument types.
2197 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002198 const char *startRef = 0, *endRef = 0;
2199 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2200 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002202 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002203 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002204 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002205 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002206 InsertText(LessLoc, "/*");
2207 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002208 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002209 startBuf = ++endBuf;
2210 }
2211 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002212 // If the function name is derived from a macro expansion, then the
2213 // argument buffer will not follow the name. Need to speak with Chris.
2214 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002215 startBuf++; // scan forward (from the decl location) for argument types.
2216 startBuf++;
2217 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002218 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002219}
2220
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002221void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2222 QualType QT = ND->getType();
2223 const Type* TypePtr = QT->getAs<Type>();
2224 if (!isa<TypeOfExprType>(TypePtr))
2225 return;
2226 while (isa<TypeOfExprType>(TypePtr)) {
2227 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2228 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2229 TypePtr = QT->getAs<Type>();
2230 }
2231 // FIXME. This will not work for multiple declarators; as in:
2232 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002233 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002234 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2235 const char *startBuf = SM->getCharacterData(DeclLoc);
2236 if (ND->getInit()) {
2237 std::string Name(ND->getNameAsString());
2238 TypeAsString += " " + Name + " = ";
2239 Expr *E = ND->getInit();
2240 SourceLocation startLoc;
2241 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2242 startLoc = ECE->getLParenLoc();
2243 else
2244 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002245 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002247 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002248 }
2249 else {
2250 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002251 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002253 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002254 }
2255}
2256
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002258void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002259 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002260 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002261 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002262 QualType getFuncType =
2263 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002264 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002265 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002266 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002267 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002268 SC_Extern,
2269 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002270}
2271
Steve Naroffb29b4272008-04-14 22:03:09 +00002272void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002273 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002274 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002275 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002277 return;
2278 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002279 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002280}
2281
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002282void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002283 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002284 const char *argPtr = TypeString.c_str();
2285 if (!strchr(argPtr, '^')) {
2286 Str += TypeString;
2287 return;
2288 }
2289 while (*argPtr) {
2290 Str += (*argPtr == '^' ? '*' : *argPtr);
2291 argPtr++;
2292 }
2293}
2294
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002295// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002296void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2297 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002299 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002300 const char *argPtr = TypeString.c_str();
2301 int paren = 0;
2302 while (*argPtr) {
2303 switch (*argPtr) {
2304 case '(':
2305 Str += *argPtr;
2306 paren++;
2307 break;
2308 case ')':
2309 Str += *argPtr;
2310 paren--;
2311 break;
2312 case '^':
2313 Str += '*';
2314 if (paren == 1)
2315 Str += VD->getNameAsString();
2316 break;
2317 default:
2318 Str += *argPtr;
2319 break;
2320 }
2321 argPtr++;
2322 }
2323}
2324
2325
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002326void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2327 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2328 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2329 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2330 if (!proto)
2331 return;
2332 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002333 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002334 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002335 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002336 FdStr += "(";
2337 unsigned numArgs = proto->getNumArgs();
2338 for (unsigned i = 0; i < numArgs; i++) {
2339 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002340 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002341 if (i+1 < numArgs)
2342 FdStr += ", ";
2343 }
2344 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002345 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002346 CurFunctionDeclToDeclareForBlock = 0;
2347}
2348
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002350void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351 if (SuperContructorFunctionDecl)
2352 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002353 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002354 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002355 QualType argT = Context->getObjCIdType();
2356 assert(!argT.isNull() && "Can't find 'id' type");
2357 ArgTys.push_back(argT);
2358 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002359 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002361 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002362 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002363 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002364 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002365 SC_Extern,
2366 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002367}
2368
Steve Naroff09b266e2007-10-30 23:14:51 +00002369// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002370void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002372 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002373 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002379 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002382 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002383 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002384 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002385 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002386 SC_Extern,
2387 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002388}
2389
Steve Naroff874e2322007-11-15 10:28:18 +00002390// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002391void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002392 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002393 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002394 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002395 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002396 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002397 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2398 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2399 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002400 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002401 assert(!argT.isNull() && "Can't find 'SEL' type");
2402 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002403 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2404 &ArgTys[0], ArgTys.size(),
2405 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002406 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002407 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002408 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002409 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002410 SC_Extern,
2411 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002412}
2413
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002414// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002415void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002416 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002417 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002418 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002419 assert(!argT.isNull() && "Can't find 'id' type");
2420 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422 assert(!argT.isNull() && "Can't find 'SEL' type");
2423 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002424 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002425 &ArgTys[0], ArgTys.size(),
2426 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002427 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002428 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002429 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002430 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002431 SC_Extern,
2432 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002433}
2434
Mike Stump1eb44332009-09-09 15:08:12 +00002435// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002436// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002437void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002438 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002439 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002440 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002441 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002442 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002443 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2445 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2446 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002447 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002448 assert(!argT.isNull() && "Can't find 'SEL' type");
2449 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002450 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002451 &ArgTys[0], ArgTys.size(),
2452 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002453 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002454 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002455 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002456 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002457 SC_Extern,
2458 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002459}
2460
Steve Naroff1284db82008-05-08 22:02:18 +00002461// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002462void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002463 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002464 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002465 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002466 assert(!argT.isNull() && "Can't find 'id' type");
2467 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002469 assert(!argT.isNull() && "Can't find 'SEL' type");
2470 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002471 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2472 &ArgTys[0], ArgTys.size(),
2473 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002474 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002475 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002476 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002477 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002478 SC_Extern,
2479 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002480}
2481
Steve Naroff09b266e2007-10-30 23:14:51 +00002482// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002483void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002484 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002485 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002486 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002487 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2488 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002489 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002490 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002491 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002492 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002493 SC_Extern,
2494 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002495}
2496
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002497// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2498void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2499 IdentifierInfo *getSuperClassIdent =
2500 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002501 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002502 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002503 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2504 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002505 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002506 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002507 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002508 getSuperClassIdent,
2509 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002510 SC_Extern,
2511 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002512 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002513}
2514
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002515// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002516void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002517 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002518 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002519 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002520 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2521 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002522 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002524 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002525 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002526 SC_Extern,
2527 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002528}
2529
Steve Naroffb29b4272008-04-14 22:03:09 +00002530Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002531 QualType strType = getConstantStringStructType();
2532
2533 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002534
2535 std::string tmpName = InFileName;
2536 unsigned i;
2537 for (i=0; i < tmpName.length(); i++) {
2538 char c = tmpName.at(i);
2539 // replace any non alphanumeric characters with '_'.
2540 if (!isalpha(c) && (c < '0' || c > '9'))
2541 tmpName[i] = '_';
2542 }
2543 S += tmpName;
2544 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002545 S += utostr(NumObjCStringLiterals++);
2546
Steve Naroffba92b2e2008-03-27 22:29:16 +00002547 Preamble += "static __NSConstantStringImpl " + S;
2548 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2549 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002550 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002551 std::string prettyBufS;
2552 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002553 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2554 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002555 Preamble += prettyBuf.str();
2556 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002557 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002558
2559 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002560 SourceLocation(), &Context->Idents.get(S),
2561 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002562 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002563 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002564 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002565 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002566 VK_RValue, OK_Ordinary,
2567 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002568 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002569 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002570 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002571 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002572 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002573 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002574}
2575
Steve Naroff874e2322007-11-15 10:28:18 +00002576// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002577QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002578 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002579 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002580 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002581 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002582 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Steve Naroff874e2322007-11-15 10:28:18 +00002584 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002586 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002587 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002588
Steve Naroff874e2322007-11-15 10:28:18 +00002589 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002590 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002592 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002593 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002594 FieldTypes[i], 0,
2595 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002596 /*Mutable=*/false,
2597 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Douglas Gregor838db382010-02-11 01:19:42 +00002600 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002601 }
2602 return Context->getTagDeclType(SuperStructDecl);
2603}
2604
Steve Naroffb29b4272008-04-14 22:03:09 +00002605QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002606 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002607 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002608 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002609 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002611
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002613 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002614 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002615 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002618 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002619 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002620
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002621 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002622 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002623 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2624 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002625 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002626 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002627 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002628 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002629 /*Mutable=*/true,
2630 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 }
2632
Douglas Gregor838db382010-02-11 01:19:42 +00002633 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002634 }
2635 return Context->getTagDeclType(ConstantStringDecl);
2636}
2637
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002638Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2639 SourceLocation StartLoc,
2640 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002641 if (!SelGetUidFunctionDecl)
2642 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002643 if (!MsgSendFunctionDecl)
2644 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002645 if (!MsgSendSuperFunctionDecl)
2646 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002647 if (!MsgSendStretFunctionDecl)
2648 SynthMsgSendStretFunctionDecl();
2649 if (!MsgSendSuperStretFunctionDecl)
2650 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002651 if (!MsgSendFpretFunctionDecl)
2652 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002653 if (!GetClassFunctionDecl)
2654 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002655 if (!GetSuperClassFunctionDecl)
2656 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002657 if (!GetMetaClassFunctionDecl)
2658 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Steve Naroff874e2322007-11-15 10:28:18 +00002660 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002661 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2662 // May need to use objc_msgSend_stret() as well.
2663 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002664 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2665 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002666 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002667 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002668 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002669 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002670 }
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Steve Naroff934f2762007-10-24 22:48:43 +00002672 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002674 switch (Exp->getReceiverKind()) {
2675 case ObjCMessageExpr::SuperClass: {
2676 MsgSendFlavor = MsgSendSuperFunctionDecl;
2677 if (MsgSendStretFlavor)
2678 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2679 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Douglas Gregor04badcf2010-04-21 00:45:42 +00002681 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002682
Chris Lattner5f9e2722011-07-23 10:55:15 +00002683 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002684
Douglas Gregor04badcf2010-04-21 00:45:42 +00002685 // set the receiver to self, the first argument to all methods.
2686 InitExprs.push_back(
2687 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002688 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002689 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002690 false,
John McCallf89e55a2010-11-18 06:31:45 +00002691 Context->getObjCIdType(),
2692 VK_RValue,
2693 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002694 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002695
Douglas Gregor04badcf2010-04-21 00:45:42 +00002696 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002697 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002698 QualType argType = Context->getPointerType(Context->CharTy);
2699 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002700 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002701 StringLiteral::Ascii, false,
2702 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002703 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2704 &ClsExprs[0],
2705 ClsExprs.size(),
2706 StartLoc,
2707 EndLoc);
2708 // (Class)objc_getClass("CurrentClass")
2709 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2710 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002711 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002712 ClsExprs.clear();
2713 ClsExprs.push_back(ArgExpr);
2714 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2715 &ClsExprs[0], ClsExprs.size(),
2716 StartLoc, EndLoc);
2717
2718 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2719 // To turn off a warning, type-cast to 'id'
2720 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2721 NoTypeInfoCStyleCastExpr(Context,
2722 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002723 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002724 // struct objc_super
2725 QualType superType = getSuperStructType();
2726 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002727
Francois Pichet62ec1f22011-09-17 17:15:52 +00002728 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002729 SynthSuperContructorFunctionDecl();
2730 // Simulate a contructor call...
2731 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002732 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002733 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002734 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2735 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002736 superType, VK_LValue,
2737 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002738 // The code for super is a little tricky to prevent collision with
2739 // the structure definition in the header. The rewriter has it's own
2740 // internal definition (__rw_objc_super) that is uses. This is why
2741 // we need the cast below. For example:
2742 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2743 //
John McCall2de56d12010-08-25 11:45:40 +00002744 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002745 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002746 VK_RValue, OK_Ordinary,
2747 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002748 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2749 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002750 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002751 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002752 // (struct objc_super) { <exprs from above> }
2753 InitListExpr *ILE =
2754 new (Context) InitListExpr(*Context, SourceLocation(),
2755 &InitExprs[0], InitExprs.size(),
2756 SourceLocation());
2757 TypeSourceInfo *superTInfo
2758 = Context->getTrivialTypeSourceInfo(superType);
2759 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002760 superType, VK_LValue,
2761 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002763 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002764 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002765 VK_RValue, OK_Ordinary,
2766 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002767 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768 MsgExprs.push_back(SuperRep);
2769 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002770 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002771
2772 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002773 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002774 QualType argType = Context->getPointerType(Context->CharTy);
2775 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002776 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002777 IdentifierInfo *clsName = Class->getIdentifier();
2778 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002779 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002780 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002781 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002782 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2783 &ClsExprs[0],
2784 ClsExprs.size(),
2785 StartLoc, EndLoc);
2786 MsgExprs.push_back(Cls);
2787 break;
2788 }
2789
2790 case ObjCMessageExpr::SuperInstance:{
2791 MsgSendFlavor = MsgSendSuperFunctionDecl;
2792 if (MsgSendStretFlavor)
2793 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2794 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2795 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002796 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797
2798 InitExprs.push_back(
2799 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002800 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002801 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002802 false,
John McCallf89e55a2010-11-18 06:31:45 +00002803 Context->getObjCIdType(),
2804 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002805 ); // set the 'receiver'.
2806
2807 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002808 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002809 QualType argType = Context->getPointerType(Context->CharTy);
2810 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002811 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002812 StringLiteral::Ascii, false, argType,
2813 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2815 &ClsExprs[0],
2816 ClsExprs.size(),
2817 StartLoc, EndLoc);
2818 // (Class)objc_getClass("CurrentClass")
2819 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2820 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002821 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 ClsExprs.clear();
2823 ClsExprs.push_back(ArgExpr);
2824 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2825 &ClsExprs[0], ClsExprs.size(),
2826 StartLoc, EndLoc);
2827
2828 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2829 // To turn off a warning, type-cast to 'id'
2830 InitExprs.push_back(
2831 // set 'super class', using class_getSuperclass().
2832 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002833 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 // struct objc_super
2835 QualType superType = getSuperStructType();
2836 Expr *SuperRep;
2837
Francois Pichet62ec1f22011-09-17 17:15:52 +00002838 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002839 SynthSuperContructorFunctionDecl();
2840 // Simulate a contructor call...
2841 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002842 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002843 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2845 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002846 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 // The code for super is a little tricky to prevent collision with
2848 // the structure definition in the header. The rewriter has it's own
2849 // internal definition (__rw_objc_super) that is uses. This is why
2850 // we need the cast below. For example:
2851 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2852 //
John McCall2de56d12010-08-25 11:45:40 +00002853 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002855 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 SourceLocation());
2857 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2858 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002859 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002860 } else {
2861 // (struct objc_super) { <exprs from above> }
2862 InitListExpr *ILE =
2863 new (Context) InitListExpr(*Context, SourceLocation(),
2864 &InitExprs[0], InitExprs.size(),
2865 SourceLocation());
2866 TypeSourceInfo *superTInfo
2867 = Context->getTrivialTypeSourceInfo(superType);
2868 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002869 superType, VK_RValue, ILE,
2870 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002871 }
2872 MsgExprs.push_back(SuperRep);
2873 break;
2874 }
2875
2876 case ObjCMessageExpr::Instance: {
2877 // Remove all type-casts because it may contain objc-style types; e.g.
2878 // Foo<Proto> *.
2879 Expr *recExpr = Exp->getInstanceReceiver();
2880 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2881 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002882 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2883 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2884 ? CK_BlockPointerToObjCPointerCast
2885 : CK_CPointerToObjCPointerCast;
2886
Douglas Gregor04badcf2010-04-21 00:45:42 +00002887 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002888 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002889 MsgExprs.push_back(recExpr);
2890 break;
2891 }
2892 }
2893
Steve Naroffbeaf2992007-11-03 11:27:19 +00002894 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002895 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002896 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002897 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002898 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002899 StringLiteral::Ascii, false,
2900 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002901 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002902 &SelExprs[0], SelExprs.size(),
2903 StartLoc,
2904 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002905 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Steve Naroff934f2762007-10-24 22:48:43 +00002907 // Now push any user supplied arguments.
2908 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002909 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002910 // Make all implicit casts explicit...ICE comes in handy:-)
2911 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2912 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002913 QualType type = ICE->getType();
2914 if (needToScanForQualifiers(type))
2915 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002916 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002917 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002918 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002919 CastKind CK;
2920 if (SubExpr->getType()->isIntegralType(*Context) &&
2921 type->isBooleanType()) {
2922 CK = CK_IntegralToBoolean;
2923 } else if (type->isObjCObjectPointerType()) {
2924 if (SubExpr->getType()->isBlockPointerType()) {
2925 CK = CK_BlockPointerToObjCPointerCast;
2926 } else if (SubExpr->getType()->isPointerType()) {
2927 CK = CK_CPointerToObjCPointerCast;
2928 } else {
2929 CK = CK_BitCast;
2930 }
2931 } else {
2932 CK = CK_BitCast;
2933 }
2934
2935 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002936 }
2937 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002938 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002939 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002940 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002941 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002942 CastKind CK;
2943 if (userExpr->getType()->isIntegralType(*Context)) {
2944 CK = CK_IntegralToPointer;
2945 } else if (userExpr->getType()->isBlockPointerType()) {
2946 CK = CK_BlockPointerToObjCPointerCast;
2947 } else if (userExpr->getType()->isPointerType()) {
2948 CK = CK_CPointerToObjCPointerCast;
2949 } else {
2950 CK = CK_BitCast;
2951 }
John McCall9d125032010-01-15 18:39:57 +00002952 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002953 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002954 }
Mike Stump1eb44332009-09-09 15:08:12 +00002955 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002956 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002957 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2958 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002959 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002960 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002961 }
Steve Naroffab972d32007-11-04 22:37:50 +00002962 // Generate the funky cast.
2963 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002964 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002965 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002966
Steve Naroffab972d32007-11-04 22:37:50 +00002967 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002968 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2969 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2970 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002971 ArgTypes.push_back(Context->getObjCIdType());
2972 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002973 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002974 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002975 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2976 E = OMD->param_end(); PI != E; ++PI) {
2977 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002978 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002979 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002980 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002981 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002982 ArgTypes.push_back(t);
2983 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002984 returnType = Exp->getType();
2985 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002986 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002987 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002989 }
2990 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002991 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Steve Naroffab972d32007-11-04 22:37:50 +00002993 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002994 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002995 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002996
Mike Stump1eb44332009-09-09 15:08:12 +00002997 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002998 // If we don't do this cast, we get the following bizarre warning/note:
2999 // xx.m:13: warning: function called through a non-compatible type
3000 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003001 cast = NoTypeInfoCStyleCastExpr(Context,
3002 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003003 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003004
Steve Naroffab972d32007-11-04 22:37:50 +00003005 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003006 QualType castType =
3007 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3008 // If we don't have a method decl, force a variadic cast.
3009 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003010 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003011 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003012 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003013
3014 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003015 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003016
John McCall183700f2009-09-21 23:43:11 +00003017 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003018 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003019 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003020 FT->getResultType(), VK_RValue,
3021 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003022 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003023 if (MsgSendStretFlavor) {
3024 // We have the method which returns a struct/union. Must also generate
3025 // call to objc_msgSend_stret and hang both varieties on a conditional
3026 // expression which dictate which one to envoke depending on size of
3027 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003029 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003030 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3031 false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003032 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003033 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003034 cast = NoTypeInfoCStyleCastExpr(Context,
3035 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003036 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003037 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003038 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3039 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003041 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003042 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003044 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003045 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003046
John McCall183700f2009-09-21 23:43:11 +00003047 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003048 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003049 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003050 FT->getResultType(), VK_RValue,
3051 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003052
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003053 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003054 UnaryExprOrTypeTraitExpr *sizeofExpr =
3055 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3056 Context->getTrivialTypeSourceInfo(returnType),
3057 Context->getSizeType(), SourceLocation(),
3058 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003059 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3060 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3061 // For X86 it is more complicated and some kind of target specific routine
3062 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003063 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003064 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003065 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3066 llvm::APInt(IntSize, 8),
3067 Context->IntTy,
3068 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003069 BinaryOperator *lessThanExpr =
3070 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3071 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003072 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003073 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003074 new (Context) ConditionalOperator(lessThanExpr,
3075 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003076 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003077 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003078 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3079 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003080 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003081 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003082 return ReplacingStmt;
3083}
3084
Steve Naroffb29b4272008-04-14 22:03:09 +00003085Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003086 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3087 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Steve Naroff934f2762007-10-24 22:48:43 +00003089 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003090 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003091
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003092 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003093 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003094}
3095
Steve Naroff621edce2009-04-29 16:37:50 +00003096// typedef struct objc_object Protocol;
3097QualType RewriteObjC::getProtocolType() {
3098 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003099 TypeSourceInfo *TInfo
3100 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003101 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003102 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003103 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003104 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003105 }
3106 return Context->getTypeDeclType(ProtocolTypeDecl);
3107}
3108
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003109/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003110/// a synthesized/forward data reference (to the protocol's metadata).
3111/// The forward references (and metadata) are generated in
3112/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003113Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003114 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3115 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003116 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003117 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003118 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003119 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3120 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003121 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003122 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003123 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003124 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003125 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003126 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003127 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003128 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003129 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003130 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003132}
3133
Mike Stump1eb44332009-09-09 15:08:12 +00003134bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003135 const char *endBuf) {
3136 while (startBuf < endBuf) {
3137 if (*startBuf == '#') {
3138 // Skip whitespace.
3139 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3140 ;
3141 if (!strncmp(startBuf, "if", strlen("if")) ||
3142 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3143 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3144 !strncmp(startBuf, "define", strlen("define")) ||
3145 !strncmp(startBuf, "undef", strlen("undef")) ||
3146 !strncmp(startBuf, "else", strlen("else")) ||
3147 !strncmp(startBuf, "elif", strlen("elif")) ||
3148 !strncmp(startBuf, "endif", strlen("endif")) ||
3149 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3150 !strncmp(startBuf, "include", strlen("include")) ||
3151 !strncmp(startBuf, "import", strlen("import")) ||
3152 !strncmp(startBuf, "include_next", strlen("include_next")))
3153 return true;
3154 }
3155 startBuf++;
3156 }
3157 return false;
3158}
3159
Fariborz Jahanian58457172011-12-05 18:43:13 +00003160/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003161/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003162void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003163 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003164 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003165 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003166 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003167 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003168 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003169 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003170 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003171 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003172 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003173 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003174
Steve Narofffea763e82007-11-14 19:25:57 +00003175 const char *startBuf = SM->getCharacterData(LocStart);
3176 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003177
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003178 // If no ivars and no root or if its root, directly or indirectly,
3179 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003180 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003181 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003182 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003183 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003184 return;
3185 }
Mike Stump1eb44332009-09-09 15:08:12 +00003186
3187 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003188 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003189 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003190 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003191 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003192 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003193
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003194 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003195 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003196 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003197 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003198 // If the buffer contains preprocessor directives, we do more fine-grained
3199 // rewrites. This is intended to fix code that looks like (which occurs in
3200 // NSURL.h, for example):
3201 //
3202 // #ifdef XYZ
3203 // @interface Foo : NSObject
3204 // #else
3205 // @interface FooBar : NSObject
3206 // #endif
3207 // {
3208 // int i;
3209 // }
3210 // @end
3211 //
3212 // This clause is segregated to avoid breaking the common case.
3213 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003214 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003215 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003216 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003217 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003218
Chris Lattnercafeb352009-02-20 18:18:36 +00003219 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003220 // advance to the end of the referenced protocols.
3221 while (endHeader < cursor && *endHeader != '>') endHeader++;
3222 endHeader++;
3223 }
3224 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003225 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003226 } else {
3227 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003228 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003229 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003230 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003231 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003232 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003233 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003235 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003236
Steve Narofffea763e82007-11-14 19:25:57 +00003237 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003238 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003239 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003240 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003241 }
3242 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Steve Narofffea763e82007-11-14 19:25:57 +00003244 // Now comment out any visibility specifiers.
3245 while (cursor < endBuf) {
3246 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003247 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003248 // Skip whitespace.
3249 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3250 /*scan*/;
3251
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003252 // FIXME: presence of @public, etc. inside comment results in
3253 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003254 if (!strncmp(cursor, "public", strlen("public")) ||
3255 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003256 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003257 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003258 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003259 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003260 // FIXME: If there are cases where '<' is used in ivar declaration part
3261 // of user code, then scan the ivar list and use needToScanForQualifiers
3262 // for type checking.
3263 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003264 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003265 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003266 cursor = strchr(cursor, '>');
3267 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003268 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003269 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003270 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003271 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003272 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003273 }
Steve Narofffea763e82007-11-14 19:25:57 +00003274 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003275 }
Steve Narofffea763e82007-11-14 19:25:57 +00003276 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003277 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003278 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003279 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003280 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003282 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003283 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003284 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003285 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003286 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003287 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003288 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003289 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003290}
3291
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003292//===----------------------------------------------------------------------===//
3293// Meta Data Emission
3294//===----------------------------------------------------------------------===//
3295
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003296
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003297/// RewriteImplementations - This routine rewrites all method implementations
3298/// and emits meta-data.
3299
Steve Narofface66252008-11-13 20:07:04 +00003300void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003301 int ClsDefCount = ClassImplementation.size();
3302 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003303
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003304 // Rewrite implemented methods
3305 for (int i = 0; i < ClsDefCount; i++)
3306 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003307
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003308 for (int i = 0; i < CatDefCount; i++)
3309 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003310}
Mike Stump1eb44332009-09-09 15:08:12 +00003311
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003312void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3313 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003314 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003315 assert(BlockByRefDeclNo.count(VD) &&
3316 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003317 if (def)
3318 ResultStr += "struct ";
3319 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003320 "_" + utostr(BlockByRefDeclNo[VD]) ;
3321}
3322
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003323static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3324 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3325 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3326 return false;
3327}
3328
Steve Naroff54055232008-10-27 17:20:55 +00003329std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003330 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003331 std::string Tag) {
3332 const FunctionType *AFT = CE->getFunctionType();
3333 QualType RT = AFT->getResultType();
3334 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003335 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003336 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003337
Steve Naroff54055232008-10-27 17:20:55 +00003338 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Douglas Gregor72564e72009-02-26 23:50:07 +00003340 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003341 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003342 // block (to reference imported block decl refs).
3343 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003344 } else if (BD->param_empty()) {
3345 S += "(" + StructRef + " *__cself)";
3346 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003347 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003348 assert(FT && "SynthesizeBlockFunc: No function proto");
3349 S += '(';
3350 // first add the implicit argument.
3351 S += StructRef + " *__cself, ";
3352 std::string ParamStr;
3353 for (BlockDecl::param_iterator AI = BD->param_begin(),
3354 E = BD->param_end(); AI != E; ++AI) {
3355 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003356 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003357 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003358 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003359 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003360 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003361 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003362 S += ParamStr;
3363 }
3364 if (FT->isVariadic()) {
3365 if (!BD->param_empty()) S += ", ";
3366 S += "...";
3367 }
3368 S += ')';
3369 }
3370 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003371
Steve Naroff54055232008-10-27 17:20:55 +00003372 // Create local declarations to avoid rewriting all closure decl ref exprs.
3373 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003374 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003375 E = BlockByRefDecls.end(); I != E; ++I) {
3376 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003377 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003378 std::string TypeString;
3379 RewriteByRefString(TypeString, Name, (*I));
3380 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003381 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003382 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003383 }
Steve Naroff54055232008-10-27 17:20:55 +00003384 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003385 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003386 E = BlockByCopyDecls.end(); I != E; ++I) {
3387 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003388 // Handle nested closure invocation. For example:
3389 //
3390 // void (^myImportedClosure)(void);
3391 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003392 //
Steve Naroff54055232008-10-27 17:20:55 +00003393 // void (^anotherClosure)(void);
3394 // anotherClosure = ^(void) {
3395 // myImportedClosure(); // import and invoke the closure
3396 // };
3397 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003398 if (isTopLevelBlockPointerType((*I)->getType())) {
3399 RewriteBlockPointerTypeVariable(S, (*I));
3400 S += " = (";
3401 RewriteBlockPointerType(S, (*I)->getType());
3402 S += ")";
3403 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3404 }
3405 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003406 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003407 QualType QT = (*I)->getType();
3408 if (HasLocalVariableExternalStorage(*I))
3409 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003410 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003411 S += Name + " = __cself->" +
3412 (*I)->getNameAsString() + "; // bound by copy\n";
3413 }
Steve Naroff54055232008-10-27 17:20:55 +00003414 }
3415 std::string RewrittenStr = RewrittenBlockExprs[CE];
3416 const char *cstr = RewrittenStr.c_str();
3417 while (*cstr++ != '{') ;
3418 S += cstr;
3419 S += "\n";
3420 return S;
3421}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003422
Steve Naroff54055232008-10-27 17:20:55 +00003423std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003424 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003425 std::string Tag) {
3426 std::string StructRef = "struct " + Tag;
3427 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Steve Naroff54055232008-10-27 17:20:55 +00003429 S += funcName;
3430 S += "_block_copy_" + utostr(i);
3431 S += "(" + StructRef;
3432 S += "*dst, " + StructRef;
3433 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003434 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003435 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003436 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003437 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003438 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003439 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003440 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003441 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003442 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003443 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003444 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003445 else
3446 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003447 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003448 S += "}\n";
3449
Steve Naroff54055232008-10-27 17:20:55 +00003450 S += "\nstatic void __";
3451 S += funcName;
3452 S += "_block_dispose_" + utostr(i);
3453 S += "(" + StructRef;
3454 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003455 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003456 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003457 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003458 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003459 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003460 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003461 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003462 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003463 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003464 else
3465 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003468 return S;
3469}
3470
Steve Naroff01aec112009-12-06 21:14:13 +00003471std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3472 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003473 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003474 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Steve Naroff54055232008-10-27 17:20:55 +00003476 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003477 S += " struct " + Desc;
3478 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Steve Naroff01aec112009-12-06 21:14:13 +00003480 Constructor += "(void *fp, "; // Invoke function pointer.
3481 Constructor += "struct " + Desc; // Descriptor pointer.
3482 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003483
Steve Naroff54055232008-10-27 17:20:55 +00003484 if (BlockDeclRefs.size()) {
3485 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003486 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003487 E = BlockByCopyDecls.end(); I != E; ++I) {
3488 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003489 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003490 std::string ArgName = "_" + FieldName;
3491 // Handle nested closure invocation. For example:
3492 //
3493 // void (^myImportedBlock)(void);
3494 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003495 //
Steve Naroff54055232008-10-27 17:20:55 +00003496 // void (^anotherBlock)(void);
3497 // anotherBlock = ^(void) {
3498 // myImportedBlock(); // import and invoke the closure
3499 // };
3500 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003501 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003502 S += "struct __block_impl *";
3503 Constructor += ", void *" + ArgName;
3504 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003505 QualType QT = (*I)->getType();
3506 if (HasLocalVariableExternalStorage(*I))
3507 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003508 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3509 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003510 Constructor += ", " + ArgName;
3511 }
3512 S += FieldName + ";\n";
3513 }
3514 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003515 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003516 E = BlockByRefDecls.end(); I != E; ++I) {
3517 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003518 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003519 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003520 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003521 std::string TypeString;
3522 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003523 TypeString += " *";
3524 FieldName = TypeString + FieldName;
3525 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003526 Constructor += ", " + ArgName;
3527 }
3528 S += FieldName + "; // by ref\n";
3529 }
3530 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003531 Constructor += ", int flags=0)";
3532 // Initialize all "by copy" arguments.
3533 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003534 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003535 E = BlockByCopyDecls.end(); I != E; ++I) {
3536 std::string Name = (*I)->getNameAsString();
3537 if (firsTime) {
3538 Constructor += " : ";
3539 firsTime = false;
3540 }
3541 else
3542 Constructor += ", ";
3543 if (isTopLevelBlockPointerType((*I)->getType()))
3544 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3545 else
3546 Constructor += Name + "(_" + Name + ")";
3547 }
3548 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003549 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003550 E = BlockByRefDecls.end(); I != E; ++I) {
3551 std::string Name = (*I)->getNameAsString();
3552 if (firsTime) {
3553 Constructor += " : ";
3554 firsTime = false;
3555 }
3556 else
3557 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003558 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003559 }
3560
3561 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003562 if (GlobalVarDecl)
3563 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3564 else
3565 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003566 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Steve Naroff01aec112009-12-06 21:14:13 +00003568 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003569 } else {
3570 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003571 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003572 if (GlobalVarDecl)
3573 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3574 else
3575 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003576 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3577 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003578 }
3579 Constructor += " ";
3580 Constructor += "}\n";
3581 S += Constructor;
3582 S += "};\n";
3583 return S;
3584}
3585
Steve Naroff01aec112009-12-06 21:14:13 +00003586std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3587 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003588 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003589 unsigned hasCopy) {
3590 std::string S = "\nstatic struct " + DescTag;
3591
3592 S += " {\n unsigned long reserved;\n";
3593 S += " unsigned long Block_size;\n";
3594 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003595 S += " void (*copy)(struct ";
3596 S += ImplTag; S += "*, struct ";
3597 S += ImplTag; S += "*);\n";
3598
3599 S += " void (*dispose)(struct ";
3600 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003601 }
3602 S += "} ";
3603
3604 S += DescTag + "_DATA = { 0, sizeof(struct ";
3605 S += ImplTag + ")";
3606 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003607 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3608 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003609 }
3610 S += "};\n";
3611 return S;
3612}
3613
Steve Naroff54055232008-10-27 17:20:55 +00003614void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003615 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003616 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003617 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003618 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003619 bool RewriteSC = (GlobalVarDecl &&
3620 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003621 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003622 GlobalVarDecl->getType().getCVRQualifiers());
3623 if (RewriteSC) {
3624 std::string SC(" void __");
3625 SC += GlobalVarDecl->getNameAsString();
3626 SC += "() {}";
3627 InsertText(FunLocStart, SC);
3628 }
3629
Steve Naroff54055232008-10-27 17:20:55 +00003630 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003631 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3632 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003633 // Need to copy-in the inner copied-in variables not actually used in this
3634 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003635 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003636 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003637 ValueDecl *VD = Exp->getDecl();
3638 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003639 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003640 BlockByCopyDeclsPtrSet.insert(VD);
3641 BlockByCopyDecls.push_back(VD);
3642 }
John McCallf4b88a42012-03-10 09:33:50 +00003643 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003644 BlockByRefDeclsPtrSet.insert(VD);
3645 BlockByRefDecls.push_back(VD);
3646 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003647 // imported objects in the inner blocks not used in the outer
3648 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003649 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003650 VD->getType()->isObjCObjectPointerType() ||
3651 VD->getType()->isBlockPointerType())
3652 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003653 }
Steve Naroff54055232008-10-27 17:20:55 +00003654
Daniel Dunbar4087f272010-08-17 22:39:59 +00003655 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3656 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Steve Naroff01aec112009-12-06 21:14:13 +00003658 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003659
Benjamin Kramerd999b372010-02-14 14:14:16 +00003660 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003661
Steve Naroff01aec112009-12-06 21:14:13 +00003662 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Benjamin Kramerd999b372010-02-14 14:14:16 +00003664 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003665
3666 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003667 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003668 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003669 }
Steve Naroff01aec112009-12-06 21:14:13 +00003670 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3671 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003672 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003673
Steve Naroff54055232008-10-27 17:20:55 +00003674 BlockDeclRefs.clear();
3675 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003676 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003677 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003678 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003679 ImportedBlockDecls.clear();
3680 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003681 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003682 // Must insert any 'const/volatile/static here. Since it has been
3683 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003684 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003685 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003686 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003687 if (GlobalVarDecl->getType().isConstQualified())
3688 SC += "const ";
3689 if (GlobalVarDecl->getType().isVolatileQualified())
3690 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003691 if (GlobalVarDecl->getType().isRestrictQualified())
3692 SC += "restrict ";
3693 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003694 }
3695
Steve Naroff54055232008-10-27 17:20:55 +00003696 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003697 InnerDeclRefsCount.clear();
3698 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003699 RewrittenBlockExprs.clear();
3700}
3701
3702void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3703 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003704 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Steve Naroff54055232008-10-27 17:20:55 +00003706 SynthesizeBlockLiterals(FunLocStart, FuncName);
3707}
3708
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003709static void BuildUniqueMethodName(std::string &Name,
3710 ObjCMethodDecl *MD) {
3711 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003712 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003713 Name += "__" + MD->getSelector().getAsString();
3714 // Convert colons to underscores.
3715 std::string::size_type loc = 0;
3716 while ((loc = Name.find(":", loc)) != std::string::npos)
3717 Name.replace(loc, 1, "_");
3718}
3719
Steve Naroff54055232008-10-27 17:20:55 +00003720void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003721 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3722 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003723 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003724 std::string FuncName;
3725 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003726 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003727}
3728
3729void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003730 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003731 if (*CI) {
3732 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3733 GetBlockDeclRefExprs(CBE->getBody());
3734 else
3735 GetBlockDeclRefExprs(*CI);
3736 }
3737 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003738 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3739 if (DRE->refersToEnclosingLocal()) {
3740 // FIXME: Handle enums.
3741 if (!isa<FunctionDecl>(DRE->getDecl()))
3742 BlockDeclRefs.push_back(DRE);
3743 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3744 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003745 }
John McCallf4b88a42012-03-10 09:33:50 +00003746 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003747
Steve Naroff54055232008-10-27 17:20:55 +00003748 return;
3749}
3750
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003751void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003752 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003753 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003754 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003755 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003756 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3757 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003758 GetInnerBlockDeclRefExprs(CBE->getBody(),
3759 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003760 InnerContexts);
3761 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003762 else
3763 GetInnerBlockDeclRefExprs(*CI,
3764 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003765 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003766
3767 }
3768 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003769 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3770 if (DRE->refersToEnclosingLocal()) {
3771 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3772 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3773 InnerBlockDeclRefs.push_back(DRE);
3774 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3775 if (Var->isFunctionOrMethodVarDecl())
3776 ImportedLocalExternalDecls.insert(Var);
3777 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003778 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003779
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003780 return;
3781}
3782
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003783/// convertFunctionTypeOfBlocks - This routine converts a function type
3784/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003785/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003786/// all block pointers to function pointers.
3787QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3788 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3789 // FTP will be null for closures that don't take arguments.
3790 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003791 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003792 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003793 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003794
3795 if (FTP) {
3796 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3797 E = FTP->arg_type_end(); I && (I != E); ++I) {
3798 QualType t = *I;
3799 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003800 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003801 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003802 ArgTypes.push_back(t);
3803 }
3804 }
3805 QualType FuncType;
3806 // FIXME. Does this work if block takes no argument but has a return type
3807 // which is of block type?
3808 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003809 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003810 else FuncType = QualType(FT, 0);
3811 return FuncType;
3812}
3813
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003814Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003815 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003816 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003818 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003819 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003820 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003821 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003822 }
3823 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3824 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3825 }
3826 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3827 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3828 else if (const ConditionalOperator *CEXPR =
3829 dyn_cast<ConditionalOperator>(BlockExp)) {
3830 Expr *LHSExp = CEXPR->getLHS();
3831 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3832 Expr *RHSExp = CEXPR->getRHS();
3833 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3834 Expr *CONDExp = CEXPR->getCond();
3835 ConditionalOperator *CondExpr =
3836 new (Context) ConditionalOperator(CONDExp,
3837 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003838 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003839 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003840 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003841 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3842 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003843 } else if (const PseudoObjectExpr *POE
3844 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3845 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003846 } else {
3847 assert(1 && "RewriteBlockClass: Bad type");
3848 }
3849 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003850 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003851 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003852 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003853 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003854
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003855 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003856 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003857 &Context->Idents.get("__block_impl"));
3858 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003859
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003860 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003861 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003863 // Push the block argument type.
3864 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003865 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003866 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003867 E = FTP->arg_type_end(); I && (I != E); ++I) {
3868 QualType t = *I;
3869 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003870 if (!convertBlockPointerToFunctionPointer(t))
3871 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003872 ArgTypes.push_back(t);
3873 }
Steve Naroff54055232008-10-27 17:20:55 +00003874 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003876 QualType PtrToFuncCastType
3877 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003878
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003879 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003880
John McCall9d125032010-01-15 18:39:57 +00003881 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003882 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003883 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003884 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003885 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3886 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003887 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003888
Douglas Gregor44b43212008-12-11 16:49:14 +00003889 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003890 SourceLocation(),
3891 &Context->Idents.get("FuncPtr"),
3892 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003893 /*BitWidth=*/0, /*Mutable=*/true,
3894 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003895 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003896 FD->getType(), VK_LValue,
3897 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003899
John McCall9d125032010-01-15 18:39:57 +00003900 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003901 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003902 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Chris Lattner5f9e2722011-07-23 10:55:15 +00003904 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003905 // Add the implicit argument.
3906 BlkExprs.push_back(BlkCast);
3907 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003908 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003909 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003910 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003911 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003912 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3913 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003914 Exp->getType(), VK_RValue,
3915 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003916 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003917}
3918
Steve Naroff621edce2009-04-29 16:37:50 +00003919// We need to return the rewritten expression to handle cases where the
3920// BlockDeclRefExpr is embedded in another expression being rewritten.
3921// For example:
3922//
3923// int main() {
3924// __block Foo *f;
3925// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003926//
Steve Naroff621edce2009-04-29 16:37:50 +00003927// void (^myblock)() = ^() {
3928// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3929// i = 77;
3930// };
3931//}
John McCallf4b88a42012-03-10 09:33:50 +00003932Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003933 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003934 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003935 ValueDecl *VD = DeclRefExp->getDecl();
3936 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003937
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003938 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003939 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003940 &Context->Idents.get("__forwarding"),
3941 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003942 /*BitWidth=*/0, /*Mutable=*/true,
3943 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003944 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3945 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003946 FD->getType(), VK_LValue,
3947 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003948
Chris Lattner5f9e2722011-07-23 10:55:15 +00003949 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003950 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003951 &Context->Idents.get(Name),
3952 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003953 /*BitWidth=*/0, /*Mutable=*/true,
3954 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003955 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003956 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003957
3958
3959
Steve Naroffdf8570d2009-02-02 17:19:26 +00003960 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003961 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3962 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003963 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003964 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003965 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003966}
3967
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003968// Rewrites the imported local variable V with external storage
3969// (static, extern, etc.) as *V
3970//
3971Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3972 ValueDecl *VD = DRE->getDecl();
3973 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3974 if (!ImportedLocalExternalDecls.count(Var))
3975 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003976 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3977 VK_LValue, OK_Ordinary,
3978 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003979 // Need parens to enforce precedence.
3980 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3981 Exp);
3982 ReplaceStmt(DRE, PE);
3983 return PE;
3984}
3985
Steve Naroffb2f9e512008-11-03 23:29:32 +00003986void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3987 SourceLocation LocStart = CE->getLParenLoc();
3988 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003989
3990 // Need to avoid trying to rewrite synthesized casts.
3991 if (LocStart.isInvalid())
3992 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003993 // Need to avoid trying to rewrite casts contained in macros.
3994 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3995 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Steve Naroff54055232008-10-27 17:20:55 +00003997 const char *startBuf = SM->getCharacterData(LocStart);
3998 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003999 QualType QT = CE->getType();
4000 const Type* TypePtr = QT->getAs<Type>();
4001 if (isa<TypeOfExprType>(TypePtr)) {
4002 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4003 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4004 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004005 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004006 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004007 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004008 return;
4009 }
Steve Naroff54055232008-10-27 17:20:55 +00004010 // advance the location to startArgList.
4011 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Steve Naroff54055232008-10-27 17:20:55 +00004013 while (*argPtr++ && (argPtr < endBuf)) {
4014 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004015 case '^':
4016 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004017 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004018 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004019 break;
Steve Naroff54055232008-10-27 17:20:55 +00004020 }
4021 }
4022 return;
4023}
4024
4025void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4026 SourceLocation DeclLoc = FD->getLocation();
4027 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Steve Naroff54055232008-10-27 17:20:55 +00004029 // We have 1 or more arguments that have closure pointers.
4030 const char *startBuf = SM->getCharacterData(DeclLoc);
4031 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Steve Naroff54055232008-10-27 17:20:55 +00004033 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Steve Naroff54055232008-10-27 17:20:55 +00004035 parenCount++;
4036 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004037 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004038 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Steve Naroff54055232008-10-27 17:20:55 +00004040 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Steve Naroff54055232008-10-27 17:20:55 +00004042 while (*argPtr++ && parenCount) {
4043 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004044 case '^':
4045 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004046 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004047 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004048 break;
4049 case '(':
4050 parenCount++;
4051 break;
4052 case ')':
4053 parenCount--;
4054 break;
Steve Naroff54055232008-10-27 17:20:55 +00004055 }
4056 }
4057 return;
4058}
4059
4060bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004061 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004062 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004063 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004064 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004065 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004066 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004067 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004068 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004069 }
4070 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004071 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004072 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004073 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004074 return true;
4075 }
4076 return false;
4077}
4078
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004079bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4080 const FunctionProtoType *FTP;
4081 const PointerType *PT = QT->getAs<PointerType>();
4082 if (PT) {
4083 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4084 } else {
4085 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4086 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4087 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4088 }
4089 if (FTP) {
4090 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004091 E = FTP->arg_type_end(); I != E; ++I) {
4092 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004093 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004094 if ((*I)->isObjCObjectPointerType() &&
4095 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4096 return true;
4097 }
4098
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004099 }
4100 return false;
4101}
4102
Ted Kremenek8189cde2009-02-07 01:47:29 +00004103void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4104 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004105 const char *argPtr = strchr(Name, '(');
4106 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Steve Naroff54055232008-10-27 17:20:55 +00004108 LParen = argPtr; // output the start.
4109 argPtr++; // skip past the left paren.
4110 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroff54055232008-10-27 17:20:55 +00004112 while (*argPtr && parenCount) {
4113 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004114 case '(': parenCount++; break;
4115 case ')': parenCount--; break;
4116 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004117 }
4118 if (parenCount) argPtr++;
4119 }
4120 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4121 RParen = argPtr; // output the end
4122}
4123
4124void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4125 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4126 RewriteBlockPointerFunctionArgs(FD);
4127 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004128 }
Steve Naroff54055232008-10-27 17:20:55 +00004129 // Handle Variables and Typedefs.
4130 SourceLocation DeclLoc = ND->getLocation();
4131 QualType DeclT;
4132 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4133 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004134 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004135 DeclT = TDD->getUnderlyingType();
4136 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4137 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004138 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004139 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Steve Naroff54055232008-10-27 17:20:55 +00004141 const char *startBuf = SM->getCharacterData(DeclLoc);
4142 const char *endBuf = startBuf;
4143 // scan backward (from the decl location) for the end of the previous decl.
4144 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4145 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004146 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004147 std::string buf;
4148 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004149 // *startBuf != '^' if we are dealing with a pointer to function that
4150 // may take block argument types (which will be handled below).
4151 if (*startBuf == '^') {
4152 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004153 buf = '*';
4154 startBuf++;
4155 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004156 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004157 while (*startBuf != ')') {
4158 buf += *startBuf;
4159 startBuf++;
4160 OrigLength++;
4161 }
4162 buf += ')';
4163 OrigLength++;
4164
4165 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4166 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004167 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004168 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004169 DeclLoc = ND->getLocation();
4170 startBuf = SM->getCharacterData(DeclLoc);
4171 const char *argListBegin, *argListEnd;
4172 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4173 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004174 if (*argListBegin == '^')
4175 buf += '*';
4176 else if (*argListBegin == '<') {
4177 buf += "/*";
4178 buf += *argListBegin++;
4179 OrigLength++;;
4180 while (*argListBegin != '>') {
4181 buf += *argListBegin++;
4182 OrigLength++;
4183 }
4184 buf += *argListBegin;
4185 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004186 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004187 else
4188 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004189 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004190 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004191 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004192 buf += ')';
4193 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004194 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004195 ReplaceText(Start, OrigLength, buf);
4196
Steve Naroff54055232008-10-27 17:20:55 +00004197 return;
4198}
4199
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004200
4201/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4202/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4203/// struct Block_byref_id_object *src) {
4204/// _Block_object_assign (&_dest->object, _src->object,
4205/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4206/// [|BLOCK_FIELD_IS_WEAK]) // object
4207/// _Block_object_assign(&_dest->object, _src->object,
4208/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4209/// [|BLOCK_FIELD_IS_WEAK]) // block
4210/// }
4211/// And:
4212/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4213/// _Block_object_dispose(_src->object,
4214/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4215/// [|BLOCK_FIELD_IS_WEAK]) // object
4216/// _Block_object_dispose(_src->object,
4217/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4218/// [|BLOCK_FIELD_IS_WEAK]) // block
4219/// }
4220
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004221std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4222 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004223 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004224 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004225 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004226 CopyDestroyCache.insert(flag);
4227 S = "static void __Block_byref_id_object_copy_";
4228 S += utostr(flag);
4229 S += "(void *dst, void *src) {\n";
4230
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004231 // offset into the object pointer is computed as:
4232 // void * + void* + int + int + void* + void *
4233 unsigned IntSize =
4234 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4235 unsigned VoidPtrSize =
4236 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4237
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004238 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004239 S += " _Block_object_assign((char*)dst + ";
4240 S += utostr(offset);
4241 S += ", *(void * *) ((char*)src + ";
4242 S += utostr(offset);
4243 S += "), ";
4244 S += utostr(flag);
4245 S += ");\n}\n";
4246
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004247 S += "static void __Block_byref_id_object_dispose_";
4248 S += utostr(flag);
4249 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004250 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4251 S += utostr(offset);
4252 S += "), ";
4253 S += utostr(flag);
4254 S += ");\n}\n";
4255 return S;
4256}
4257
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004258/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4259/// the declaration into:
4260/// struct __Block_byref_ND {
4261/// void *__isa; // NULL for everything except __weak pointers
4262/// struct __Block_byref_ND *__forwarding;
4263/// int32_t __flags;
4264/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004265/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4266/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004267/// typex ND;
4268/// };
4269///
4270/// It then replaces declaration of ND variable with:
4271/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4272/// __size=sizeof(struct __Block_byref_ND),
4273/// ND=initializer-if-any};
4274///
4275///
4276void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004277 // Insert declaration for the function in which block literal is
4278 // used.
4279 if (CurFunctionDeclToDeclareForBlock)
4280 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004281 int flag = 0;
4282 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004283 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004284 if (DeclLoc.isInvalid())
4285 // If type location is missing, it is because of missing type (a warning).
4286 // Use variable's location which is good for this case.
4287 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004288 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004289 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004290 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004291 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004292 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004293 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004294 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004295 ByrefType += " {\n";
4296 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004297 RewriteByRefString(ByrefType, Name, ND);
4298 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004299 ByrefType += " int __flags;\n";
4300 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004301 // Add void *__Block_byref_id_object_copy;
4302 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004303 QualType Ty = ND->getType();
4304 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4305 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004306 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4307 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004308 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004309
4310 QualType T = Ty;
4311 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004312 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004313
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004314 ByrefType += " " + Name + ";\n";
4315 ByrefType += "};\n";
4316 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004317 SourceLocation FunLocStart;
4318 if (CurFunctionDef)
4319 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4320 else {
4321 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4322 FunLocStart = CurMethodDef->getLocStart();
4323 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004324 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004325 if (Ty.isObjCGCWeak()) {
4326 flag |= BLOCK_FIELD_IS_WEAK;
4327 isa = 1;
4328 }
4329
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004330 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004331 flag = BLOCK_BYREF_CALLER;
4332 QualType Ty = ND->getType();
4333 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4334 if (Ty->isBlockPointerType())
4335 flag |= BLOCK_FIELD_IS_BLOCK;
4336 else
4337 flag |= BLOCK_FIELD_IS_OBJECT;
4338 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004339 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004340 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004341 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004342
4343 // struct __Block_byref_ND ND =
4344 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4345 // initializer-if-any};
4346 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004347 unsigned flags = 0;
4348 if (HasCopyAndDispose)
4349 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004350 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004351 ByrefType.clear();
4352 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004353 std::string ForwardingCastType("(");
4354 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004355 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004356 ByrefType += " " + Name + " = {(void*)";
4357 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004358 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004359 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004360 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004361 ByrefType += "sizeof(";
4362 RewriteByRefString(ByrefType, Name, ND);
4363 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004364 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004365 ByrefType += ", __Block_byref_id_object_copy_";
4366 ByrefType += utostr(flag);
4367 ByrefType += ", __Block_byref_id_object_dispose_";
4368 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004369 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004370 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004371 unsigned nameSize = Name.size();
4372 // for block or function pointer declaration. Name is aleady
4373 // part of the declaration.
4374 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4375 nameSize = 1;
4376 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004377 }
4378 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004379 SourceLocation startLoc;
4380 Expr *E = ND->getInit();
4381 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4382 startLoc = ECE->getLParenLoc();
4383 else
4384 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004385 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004386 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004387 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004388 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004389 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004390 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004391 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004392 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004393 ByrefType += "sizeof(";
4394 RewriteByRefString(ByrefType, Name, ND);
4395 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004396 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004397 ByrefType += "__Block_byref_id_object_copy_";
4398 ByrefType += utostr(flag);
4399 ByrefType += ", __Block_byref_id_object_dispose_";
4400 ByrefType += utostr(flag);
4401 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004402 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004403 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004404
4405 // Complete the newly synthesized compound expression by inserting a right
4406 // curly brace before the end of the declaration.
4407 // FIXME: This approach avoids rewriting the initializer expression. It
4408 // also assumes there is only one declarator. For example, the following
4409 // isn't currently supported by this routine (in general):
4410 //
4411 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4412 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004413 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4414 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004415 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4416 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004417 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004418
Benjamin Kramerd999b372010-02-14 14:14:16 +00004419 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004420 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004421 return;
4422}
4423
Mike Stump1eb44332009-09-09 15:08:12 +00004424void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004425 // Add initializers for any closure decl refs.
4426 GetBlockDeclRefExprs(Exp->getBody());
4427 if (BlockDeclRefs.size()) {
4428 // Unique all "by copy" declarations.
4429 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004430 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004431 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4432 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4433 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4434 }
4435 }
Steve Naroff54055232008-10-27 17:20:55 +00004436 // Unique all "by ref" declarations.
4437 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004438 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004439 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4440 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4441 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4442 }
Steve Naroff54055232008-10-27 17:20:55 +00004443 }
4444 // Find any imported blocks...they will need special attention.
4445 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004446 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004447 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004448 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004449 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004450 }
4451}
4452
Chris Lattner5f9e2722011-07-23 10:55:15 +00004453FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004454 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004455 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004456 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4457 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004458 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004459}
4460
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004461Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004462 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004463 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004464 Blocks.push_back(Exp);
4465
4466 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004467
4468 // Add inner imported variables now used in current block.
4469 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004470 if (!InnerBlockDeclRefs.empty()) {
4471 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004472 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004473 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004474 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004475 // We need to save the copied-in variables in nested
4476 // blocks because it is needed at the end for some of the API generations.
4477 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004478 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4479 BlockDeclRefs.push_back(Exp);
4480 BlockByCopyDeclsPtrSet.insert(VD);
4481 BlockByCopyDecls.push_back(VD);
4482 }
John McCallf4b88a42012-03-10 09:33:50 +00004483 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004484 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4485 BlockDeclRefs.push_back(Exp);
4486 BlockByRefDeclsPtrSet.insert(VD);
4487 BlockByRefDecls.push_back(VD);
4488 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004489 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004490 // Find any imported blocks...they will need special attention.
4491 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004492 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004493 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4494 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4495 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004496 }
4497 InnerDeclRefsCount.push_back(countOfInnerDecls);
4498
Steve Narofffa15fd92008-10-28 20:29:00 +00004499 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004500
Steve Narofffa15fd92008-10-28 20:29:00 +00004501 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004502 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004503 else if (CurMethodDef)
4504 BuildUniqueMethodName(FuncName, CurMethodDef);
4505 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004506 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004507
Steve Narofffa15fd92008-10-28 20:29:00 +00004508 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Steve Narofffa15fd92008-10-28 20:29:00 +00004510 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4511 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004512
Steve Narofffa15fd92008-10-28 20:29:00 +00004513 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004514 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4515 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004516
4517 FunctionDecl *FD;
4518 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004521 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004522 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004523 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004524
Chris Lattner5f9e2722011-07-23 10:55:15 +00004525 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004526
Steve Narofffdc03722008-10-29 21:23:59 +00004527 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004528 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004529 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4530 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004531 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004532 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004533 InitExprs.push_back(castExpr);
4534
Steve Naroff01aec112009-12-06 21:14:13 +00004535 // Initialize the block descriptor.
4536 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004537
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004538 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4539 SourceLocation(), SourceLocation(),
4540 &Context->Idents.get(DescData.c_str()),
4541 Context->VoidPtrTy, 0,
4542 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004543 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004544 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004545 Context->VoidPtrTy,
4546 VK_LValue,
4547 SourceLocation()),
4548 UO_AddrOf,
4549 Context->getPointerType(Context->VoidPtrTy),
4550 VK_RValue, OK_Ordinary,
4551 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004552 InitExprs.push_back(DescRefExpr);
4553
Steve Narofffa15fd92008-10-28 20:29:00 +00004554 // Add initializers for any closure decl refs.
4555 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004556 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004557 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004558 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004559 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004560 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004561 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004562 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004563 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004564 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004565 if (HasLocalVariableExternalStorage(*I)) {
4566 QualType QT = (*I)->getType();
4567 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004568 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4569 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004570 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004571 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004572 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004573 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004574 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004575 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004576 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004577 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004578 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004579 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004580 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004581 if (HasLocalVariableExternalStorage(*I)) {
4582 QualType QT = (*I)->getType();
4583 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004584 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4585 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004586 }
4587
Steve Narofffa15fd92008-10-28 20:29:00 +00004588 }
Mike Stump1eb44332009-09-09 15:08:12 +00004589 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004590 }
4591 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004592 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004593 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004594 ValueDecl *ND = (*I);
4595 std::string Name(ND->getNameAsString());
4596 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004597 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004598 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4599 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004600 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004601 SourceLocation(), SourceLocation(),
4602 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004603 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4604 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4605
Daniel Dunbar4087f272010-08-17 22:39:59 +00004606 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004607 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004608 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004609 bool isNestedCapturedVar = false;
4610 if (block)
4611 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4612 ce = block->capture_end(); ci != ce; ++ci) {
4613 const VarDecl *variable = ci->getVariable();
4614 if (variable == ND && ci->isNested()) {
4615 assert (ci->isByRef() &&
4616 "SynthBlockInitExpr - captured block variable is not byref");
4617 isNestedCapturedVar = true;
4618 break;
4619 }
4620 }
4621 // captured nested byref variable has its address passed. Do not take
4622 // its address again.
4623 if (!isNestedCapturedVar)
4624 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004625 Context->getPointerType(Exp->getType()),
4626 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004627 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004628 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004629 }
4630 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004631 if (ImportedBlockDecls.size()) {
4632 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4633 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004634 unsigned IntSize =
4635 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004636 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4637 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004638 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004639 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004640 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004641 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004642 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004643 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004644 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004645 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004646 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004647 BlockDeclRefs.clear();
4648 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004649 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004650 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004651 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004652 ImportedBlockDecls.clear();
4653 return NewRep;
4654}
4655
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004656bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4657 if (const ObjCForCollectionStmt * CS =
4658 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4659 return CS->getElement() == DS;
4660 return false;
4661}
4662
Steve Narofffa15fd92008-10-28 20:29:00 +00004663//===----------------------------------------------------------------------===//
4664// Function Body / Expression rewriting
4665//===----------------------------------------------------------------------===//
4666
4667Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004668 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004669 isa<DoStmt>(S) || isa<ForStmt>(S))
4670 Stmts.push_back(S);
4671 else if (isa<ObjCForCollectionStmt>(S)) {
4672 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004673 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004674 }
Mike Stump1eb44332009-09-09 15:08:12 +00004675
John McCall4b9c2d22011-11-06 09:01:30 +00004676 // Pseudo-object operations and ivar references need special
4677 // treatment because we're going to recursively rewrite them.
4678 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4679 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4680 return RewritePropertyOrImplicitSetter(PseudoOp);
4681 } else {
4682 return RewritePropertyOrImplicitGetter(PseudoOp);
4683 }
4684 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4685 return RewriteObjCIvarRefExpr(IvarRefExpr);
4686 }
4687
Steve Narofffa15fd92008-10-28 20:29:00 +00004688 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004689
Steve Narofffa15fd92008-10-28 20:29:00 +00004690 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004691 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004692 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004693 Stmt *childStmt = (*CI);
4694 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004695 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004696 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004697 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004698 }
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Steve Narofffa15fd92008-10-28 20:29:00 +00004700 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004701 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004702 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4703 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004704 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004705 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004706 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004707 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004708 Stmt *SaveCurrentBody = CurrentBody;
4709 CurrentBody = BE->getBody();
4710 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004711 // block literal on rhs of a property-dot-sytax assignment
4712 // must be replaced by its synthesize ast so getRewrittenText
4713 // works as expected. In this case, what actually ends up on RHS
4714 // is the blockTranscribed which is the helper function for the
4715 // block literal; as in: self.c = ^() {[ace ARR];};
4716 bool saveDisableReplaceStmt = DisableReplaceStmt;
4717 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004718 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004719 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004720 CurrentBody = SaveCurrentBody;
4721 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004722 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004723 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004724 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004725 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004726
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004727 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4728
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004730 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004731 return blockTranscribed;
4732 }
4733 // Handle specific things.
4734 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4735 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004736
Steve Narofffa15fd92008-10-28 20:29:00 +00004737 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4738 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Steve Narofffa15fd92008-10-28 20:29:00 +00004740 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4741 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004742
Steve Narofffa15fd92008-10-28 20:29:00 +00004743 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004744#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 // Before we rewrite it, put the original message expression in a comment.
4746 SourceLocation startLoc = MessExpr->getLocStart();
4747 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004748
Steve Narofffa15fd92008-10-28 20:29:00 +00004749 const char *startBuf = SM->getCharacterData(startLoc);
4750 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Steve Narofffa15fd92008-10-28 20:29:00 +00004752 std::string messString;
4753 messString += "// ";
4754 messString.append(startBuf, endBuf-startBuf+1);
4755 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004756
4757 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004758 // InsertText(clang::SourceLocation, char const*, unsigned int).
4759 // InsertText(startLoc, messString.c_str(), messString.size());
4760 // Tried this, but it didn't work either...
4761 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004762#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004763 return RewriteMessageExpr(MessExpr);
4764 }
Mike Stump1eb44332009-09-09 15:08:12 +00004765
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4767 return RewriteObjCTryStmt(StmtTry);
4768
4769 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4770 return RewriteObjCSynchronizedStmt(StmtTry);
4771
4772 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4773 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004774
Steve Narofffa15fd92008-10-28 20:29:00 +00004775 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4776 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004777
4778 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004779 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004780 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004781 OrigStmtRange.getEnd());
4782 if (BreakStmt *StmtBreakStmt =
4783 dyn_cast<BreakStmt>(S))
4784 return RewriteBreakStmt(StmtBreakStmt);
4785 if (ContinueStmt *StmtContinueStmt =
4786 dyn_cast<ContinueStmt>(S))
4787 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004788
4789 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004790 // and cast exprs.
4791 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4792 // FIXME: What we're doing here is modifying the type-specifier that
4793 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004794 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004795 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4796 // the context of an ObjCForCollectionStmt. For example:
4797 // NSArray *someArray;
4798 // for (id <FooProtocol> index in someArray) ;
4799 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4800 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004801 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004802 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Steve Narofffa15fd92008-10-28 20:29:00 +00004804 // Blocks rewrite rules.
4805 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4806 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004807 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004808 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004809 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004810 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004811 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004812 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004813 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004814 if (VD->hasAttr<BlocksAttr>()) {
4815 static unsigned uniqueByrefDeclCount = 0;
4816 assert(!BlockByRefDeclNo.count(ND) &&
4817 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4818 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004819 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004820 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004821 else
4822 RewriteTypeOfDecl(VD);
4823 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004824 }
Richard Smith162e1c12011-04-15 14:24:37 +00004825 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004826 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004827 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004828 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004829 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4830 }
4831 }
4832 }
Mike Stump1eb44332009-09-09 15:08:12 +00004833
Steve Narofffa15fd92008-10-28 20:29:00 +00004834 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4835 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004836
4837 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4839 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004840 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4841 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 && "Statement stack mismatch");
4843 Stmts.pop_back();
4844 }
4845 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004846 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4847 ValueDecl *VD = DRE->getDecl();
4848 if (VD->hasAttr<BlocksAttr>())
4849 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004850 if (HasLocalVariableExternalStorage(VD))
4851 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004852 }
4853
Steve Narofffa15fd92008-10-28 20:29:00 +00004854 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004855 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004856 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004857 ReplaceStmt(S, BlockCall);
4858 return BlockCall;
4859 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004860 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004861 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004862 RewriteCastExpr(CE);
4863 }
4864#if 0
4865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004866 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4867 ICE->getSubExpr(),
4868 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004869 // Get the new text.
4870 std::string SStr;
4871 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004872 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004873 const std::string &Str = Buf.str();
4874
4875 printf("CAST = %s\n", &Str[0]);
4876 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4877 delete S;
4878 return Replacement;
4879 }
4880#endif
4881 // Return this stmt unmodified.
4882 return S;
4883}
4884
Steve Naroff3d7e7862009-12-05 15:55:59 +00004885void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4886 for (RecordDecl::field_iterator i = RD->field_begin(),
4887 e = RD->field_end(); i != e; ++i) {
4888 FieldDecl *FD = *i;
4889 if (isTopLevelBlockPointerType(FD->getType()))
4890 RewriteBlockPointerDecl(FD);
4891 if (FD->getType()->isObjCQualifiedIdType() ||
4892 FD->getType()->isObjCQualifiedInterfaceType())
4893 RewriteObjCQualifiedInterfaceTypes(FD);
4894 }
4895}
4896
Steve Narofffa15fd92008-10-28 20:29:00 +00004897/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4898/// main file of the input.
4899void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004900 switch (D->getKind()) {
4901 case Decl::Function: {
4902 FunctionDecl *FD = cast<FunctionDecl>(D);
4903 if (FD->isOverloadedOperator())
4904 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004905
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004906 // Since function prototypes don't have ParmDecl's, we check the function
4907 // prototype. This enables us to rewrite function declarations and
4908 // definitions using the same code.
4909 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004910
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004911 if (!FD->isThisDeclarationADefinition())
4912 break;
4913
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004914 // FIXME: If this should support Obj-C++, support CXXTryStmt
4915 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4916 CurFunctionDef = FD;
4917 CurFunctionDeclToDeclareForBlock = FD;
4918 CurrentBody = Body;
4919 Body =
4920 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4921 FD->setBody(Body);
4922 CurrentBody = 0;
4923 if (PropParentMap) {
4924 delete PropParentMap;
4925 PropParentMap = 0;
4926 }
4927 // This synthesizes and inserts the block "impl" struct, invoke function,
4928 // and any copy/dispose helper functions.
4929 InsertBlockLiteralsWithinFunction(FD);
4930 CurFunctionDef = 0;
4931 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004932 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004933 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004934 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004935 case Decl::ObjCMethod: {
4936 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4937 if (CompoundStmt *Body = MD->getCompoundBody()) {
4938 CurMethodDef = MD;
4939 CurrentBody = Body;
4940 Body =
4941 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4942 MD->setBody(Body);
4943 CurrentBody = 0;
4944 if (PropParentMap) {
4945 delete PropParentMap;
4946 PropParentMap = 0;
4947 }
4948 InsertBlockLiteralsWithinMethod(MD);
4949 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004950 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004951 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004952 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004953 case Decl::ObjCImplementation: {
4954 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4955 ClassImplementation.push_back(CI);
4956 break;
4957 }
4958 case Decl::ObjCCategoryImpl: {
4959 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4960 CategoryImplementation.push_back(CI);
4961 break;
4962 }
4963 case Decl::Var: {
4964 VarDecl *VD = cast<VarDecl>(D);
4965 RewriteObjCQualifiedInterfaceTypes(VD);
4966 if (isTopLevelBlockPointerType(VD->getType()))
4967 RewriteBlockPointerDecl(VD);
4968 else if (VD->getType()->isFunctionPointerType()) {
4969 CheckFunctionPointerDecl(VD->getType(), VD);
4970 if (VD->getInit()) {
4971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4972 RewriteCastExpr(CE);
4973 }
4974 }
4975 } else if (VD->getType()->isRecordType()) {
4976 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4977 if (RD->isCompleteDefinition())
4978 RewriteRecordBody(RD);
4979 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004980 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004981 GlobalVarDecl = VD;
4982 CurrentBody = VD->getInit();
4983 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4984 CurrentBody = 0;
4985 if (PropParentMap) {
4986 delete PropParentMap;
4987 PropParentMap = 0;
4988 }
4989 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4990 GlobalVarDecl = 0;
4991
4992 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004993 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004994 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004995 }
4996 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004997 break;
4998 }
4999 case Decl::TypeAlias:
5000 case Decl::Typedef: {
5001 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5002 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5003 RewriteBlockPointerDecl(TD);
5004 else if (TD->getUnderlyingType()->isFunctionPointerType())
5005 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5006 }
5007 break;
5008 }
5009 case Decl::CXXRecord:
5010 case Decl::Record: {
5011 RecordDecl *RD = cast<RecordDecl>(D);
5012 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005013 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005014 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005015 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005016 default:
5017 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005018 }
5019 // Nothing yet.
5020}
5021
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005022void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005023 if (Diags.hasErrorOccurred())
5024 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005025
Steve Narofffa15fd92008-10-28 20:29:00 +00005026 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005027
Steve Naroff621edce2009-04-29 16:37:50 +00005028 // Here's a great place to add any extra declarations that may be needed.
5029 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005030 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005031 E = ProtocolExprDecls.end(); I != E; ++I)
5032 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5033
Benjamin Kramerd999b372010-02-14 14:14:16 +00005034 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005035 if (ClassImplementation.size() || CategoryImplementation.size())
5036 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005037
Steve Narofffa15fd92008-10-28 20:29:00 +00005038 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5039 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005040 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005041 Rewrite.getRewriteBufferFor(MainFileID)) {
5042 //printf("Changed:\n");
5043 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5044 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005045 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005046 }
Steve Narofface66252008-11-13 20:07:04 +00005047
Steve Naroff621edce2009-04-29 16:37:50 +00005048 if (ClassImplementation.size() || CategoryImplementation.size() ||
5049 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005050 // Rewrite Objective-c meta data*
5051 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005052 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005053 // Emit metadata.
5054 *OutFile << ResultStr;
5055 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005056 OutFile->flush();
5057}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005058
5059void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5060 InitializeCommon(context);
5061
5062 // declaring objc_selector outside the parameter list removes a silly
5063 // scope related warning...
5064 if (IsHeader)
5065 Preamble = "#pragma once\n";
5066 Preamble += "struct objc_selector; struct objc_class;\n";
5067 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5068 Preamble += "struct objc_object *superClass; ";
5069 if (LangOpts.MicrosoftExt) {
5070 // Add a constructor for creating temporary objects.
5071 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5072 ": ";
5073 Preamble += "object(o), superClass(s) {} ";
5074 }
5075 Preamble += "};\n";
5076 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5077 Preamble += "typedef struct objc_object Protocol;\n";
5078 Preamble += "#define _REWRITER_typedef_Protocol\n";
5079 Preamble += "#endif\n";
5080 if (LangOpts.MicrosoftExt) {
5081 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5082 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5083 } else
5084 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5086 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5088 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5090 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5092 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5094 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5096 Preamble += "(const char *);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5098 Preamble += "(struct objc_class *);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5100 Preamble += "(const char *);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5106 Preamble += "(struct objc_class *, struct objc_object *);\n";
5107 // @synchronized hooks.
5108 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5109 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5110 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5111 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5112 Preamble += "struct __objcFastEnumerationState {\n\t";
5113 Preamble += "unsigned long state;\n\t";
5114 Preamble += "void **itemsPtr;\n\t";
5115 Preamble += "unsigned long *mutationsPtr;\n\t";
5116 Preamble += "unsigned long extra[5];\n};\n";
5117 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5118 Preamble += "#define __FASTENUMERATIONSTATE\n";
5119 Preamble += "#endif\n";
5120 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5121 Preamble += "struct __NSConstantStringImpl {\n";
5122 Preamble += " int *isa;\n";
5123 Preamble += " int flags;\n";
5124 Preamble += " char *str;\n";
5125 Preamble += " long length;\n";
5126 Preamble += "};\n";
5127 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5129 Preamble += "#else\n";
5130 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5131 Preamble += "#endif\n";
5132 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5133 Preamble += "#endif\n";
5134 // Blocks preamble.
5135 Preamble += "#ifndef BLOCK_IMPL\n";
5136 Preamble += "#define BLOCK_IMPL\n";
5137 Preamble += "struct __block_impl {\n";
5138 Preamble += " void *isa;\n";
5139 Preamble += " int Flags;\n";
5140 Preamble += " int Reserved;\n";
5141 Preamble += " void *FuncPtr;\n";
5142 Preamble += "};\n";
5143 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5144 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5145 Preamble += "extern \"C\" __declspec(dllexport) "
5146 "void _Block_object_assign(void *, const void *, const int);\n";
5147 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5148 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5149 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5150 Preamble += "#else\n";
5151 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5152 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5153 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5154 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5155 Preamble += "#endif\n";
5156 Preamble += "#endif\n";
5157 if (LangOpts.MicrosoftExt) {
5158 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5159 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5160 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5161 Preamble += "#define __attribute__(X)\n";
5162 Preamble += "#endif\n";
5163 Preamble += "#define __weak\n";
5164 }
5165 else {
5166 Preamble += "#define __block\n";
5167 Preamble += "#define __weak\n";
5168 }
5169 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5170 // as this avoids warning in any 64bit/32bit compilation model.
5171 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5172}
5173
5174/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5175/// ivar offset.
5176void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5177 std::string &Result) {
5178 if (ivar->isBitField()) {
5179 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5180 // place all bitfields at offset 0.
5181 Result += "0";
5182 } else {
5183 Result += "__OFFSETOFIVAR__(struct ";
5184 Result += ivar->getContainingInterface()->getNameAsString();
5185 if (LangOpts.MicrosoftExt)
5186 Result += "_IMPL";
5187 Result += ", ";
5188 Result += ivar->getNameAsString();
5189 Result += ")";
5190 }
5191}
5192
5193/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5194void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5195 ObjCProtocolDecl *PDecl, StringRef prefix,
5196 StringRef ClassName, std::string &Result) {
5197 static bool objc_protocol_methods = false;
5198
5199 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005200 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005201 /* struct protocol_methods {
5202 SEL _cmd;
5203 char *method_types;
5204 }
5205 */
5206 Result += "\nstruct _protocol_methods {\n";
5207 Result += "\tstruct objc_selector *_cmd;\n";
5208 Result += "\tchar *method_types;\n";
5209 Result += "};\n";
5210
5211 objc_protocol_methods = true;
5212 }
5213 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005214 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005215 return;
5216
Douglas Gregor61cc2962012-01-02 02:00:30 +00005217 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5218 PDecl = Def;
5219
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005220 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5221 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5222 PDecl->instmeth_end());
5223 /* struct _objc_protocol_method_list {
5224 int protocol_method_count;
5225 struct protocol_methods protocols[];
5226 }
5227 */
5228 Result += "\nstatic struct {\n";
5229 Result += "\tint protocol_method_count;\n";
5230 Result += "\tstruct _protocol_methods protocol_methods[";
5231 Result += utostr(NumMethods);
5232 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5233 Result += PDecl->getNameAsString();
5234 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5235 "{\n\t" + utostr(NumMethods) + "\n";
5236
5237 // Output instance methods declared in this protocol.
5238 for (ObjCProtocolDecl::instmeth_iterator
5239 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5240 I != E; ++I) {
5241 if (I == PDecl->instmeth_begin())
5242 Result += "\t ,{{(struct objc_selector *)\"";
5243 else
5244 Result += "\t ,{(struct objc_selector *)\"";
5245 Result += (*I)->getSelector().getAsString();
5246 std::string MethodTypeString;
5247 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5248 Result += "\", \"";
5249 Result += MethodTypeString;
5250 Result += "\"}\n";
5251 }
5252 Result += "\t }\n};\n";
5253 }
5254
5255 // Output class methods declared in this protocol.
5256 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5257 PDecl->classmeth_end());
5258 if (NumMethods > 0) {
5259 /* struct _objc_protocol_method_list {
5260 int protocol_method_count;
5261 struct protocol_methods protocols[];
5262 }
5263 */
5264 Result += "\nstatic struct {\n";
5265 Result += "\tint protocol_method_count;\n";
5266 Result += "\tstruct _protocol_methods protocol_methods[";
5267 Result += utostr(NumMethods);
5268 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5269 Result += PDecl->getNameAsString();
5270 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5271 "{\n\t";
5272 Result += utostr(NumMethods);
5273 Result += "\n";
5274
5275 // Output instance methods declared in this protocol.
5276 for (ObjCProtocolDecl::classmeth_iterator
5277 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5278 I != E; ++I) {
5279 if (I == PDecl->classmeth_begin())
5280 Result += "\t ,{{(struct objc_selector *)\"";
5281 else
5282 Result += "\t ,{(struct objc_selector *)\"";
5283 Result += (*I)->getSelector().getAsString();
5284 std::string MethodTypeString;
5285 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5286 Result += "\", \"";
5287 Result += MethodTypeString;
5288 Result += "\"}\n";
5289 }
5290 Result += "\t }\n};\n";
5291 }
5292
5293 // Output:
5294 /* struct _objc_protocol {
5295 // Objective-C 1.0 extensions
5296 struct _objc_protocol_extension *isa;
5297 char *protocol_name;
5298 struct _objc_protocol **protocol_list;
5299 struct _objc_protocol_method_list *instance_methods;
5300 struct _objc_protocol_method_list *class_methods;
5301 };
5302 */
5303 static bool objc_protocol = false;
5304 if (!objc_protocol) {
5305 Result += "\nstruct _objc_protocol {\n";
5306 Result += "\tstruct _objc_protocol_extension *isa;\n";
5307 Result += "\tchar *protocol_name;\n";
5308 Result += "\tstruct _objc_protocol **protocol_list;\n";
5309 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5310 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5311 Result += "};\n";
5312
5313 objc_protocol = true;
5314 }
5315
5316 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5317 Result += PDecl->getNameAsString();
5318 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5319 "{\n\t0, \"";
5320 Result += PDecl->getNameAsString();
5321 Result += "\", 0, ";
5322 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5323 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5324 Result += PDecl->getNameAsString();
5325 Result += ", ";
5326 }
5327 else
5328 Result += "0, ";
5329 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5330 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5331 Result += PDecl->getNameAsString();
5332 Result += "\n";
5333 }
5334 else
5335 Result += "0\n";
5336 Result += "};\n";
5337
5338 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005339 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005340 llvm_unreachable("protocol already synthesized");
5341
5342}
5343
5344void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5345 const ObjCList<ObjCProtocolDecl> &Protocols,
5346 StringRef prefix, StringRef ClassName,
5347 std::string &Result) {
5348 if (Protocols.empty()) return;
5349
5350 for (unsigned i = 0; i != Protocols.size(); i++)
5351 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5352
5353 // Output the top lovel protocol meta-data for the class.
5354 /* struct _objc_protocol_list {
5355 struct _objc_protocol_list *next;
5356 int protocol_count;
5357 struct _objc_protocol *class_protocols[];
5358 }
5359 */
5360 Result += "\nstatic struct {\n";
5361 Result += "\tstruct _objc_protocol_list *next;\n";
5362 Result += "\tint protocol_count;\n";
5363 Result += "\tstruct _objc_protocol *class_protocols[";
5364 Result += utostr(Protocols.size());
5365 Result += "];\n} _OBJC_";
5366 Result += prefix;
5367 Result += "_PROTOCOLS_";
5368 Result += ClassName;
5369 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5370 "{\n\t0, ";
5371 Result += utostr(Protocols.size());
5372 Result += "\n";
5373
5374 Result += "\t,{&_OBJC_PROTOCOL_";
5375 Result += Protocols[0]->getNameAsString();
5376 Result += " \n";
5377
5378 for (unsigned i = 1; i != Protocols.size(); i++) {
5379 Result += "\t ,&_OBJC_PROTOCOL_";
5380 Result += Protocols[i]->getNameAsString();
5381 Result += "\n";
5382 }
5383 Result += "\t }\n};\n";
5384}
5385
5386void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5387 std::string &Result) {
5388 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5389
5390 // Explicitly declared @interface's are already synthesized.
5391 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005392 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005393 // produce correct synthesis as yet.
5394 RewriteObjCInternalStruct(CDecl, Result);
5395 }
5396
5397 // Build _objc_ivar_list metadata for classes ivars if needed
5398 unsigned NumIvars = !IDecl->ivar_empty()
5399 ? IDecl->ivar_size()
5400 : (CDecl ? CDecl->ivar_size() : 0);
5401 if (NumIvars > 0) {
5402 static bool objc_ivar = false;
5403 if (!objc_ivar) {
5404 /* struct _objc_ivar {
5405 char *ivar_name;
5406 char *ivar_type;
5407 int ivar_offset;
5408 };
5409 */
5410 Result += "\nstruct _objc_ivar {\n";
5411 Result += "\tchar *ivar_name;\n";
5412 Result += "\tchar *ivar_type;\n";
5413 Result += "\tint ivar_offset;\n";
5414 Result += "};\n";
5415
5416 objc_ivar = true;
5417 }
5418
5419 /* struct {
5420 int ivar_count;
5421 struct _objc_ivar ivar_list[nIvars];
5422 };
5423 */
5424 Result += "\nstatic struct {\n";
5425 Result += "\tint ivar_count;\n";
5426 Result += "\tstruct _objc_ivar ivar_list[";
5427 Result += utostr(NumIvars);
5428 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5429 Result += IDecl->getNameAsString();
5430 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5431 "{\n\t";
5432 Result += utostr(NumIvars);
5433 Result += "\n";
5434
5435 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5436 SmallVector<ObjCIvarDecl *, 8> IVars;
5437 if (!IDecl->ivar_empty()) {
5438 for (ObjCInterfaceDecl::ivar_iterator
5439 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5440 IV != IVEnd; ++IV)
5441 IVars.push_back(*IV);
5442 IVI = IDecl->ivar_begin();
5443 IVE = IDecl->ivar_end();
5444 } else {
5445 IVI = CDecl->ivar_begin();
5446 IVE = CDecl->ivar_end();
5447 }
5448 Result += "\t,{{\"";
5449 Result += (*IVI)->getNameAsString();
5450 Result += "\", \"";
5451 std::string TmpString, StrEncoding;
5452 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5453 QuoteDoublequotes(TmpString, StrEncoding);
5454 Result += StrEncoding;
5455 Result += "\", ";
5456 RewriteIvarOffsetComputation(*IVI, Result);
5457 Result += "}\n";
5458 for (++IVI; IVI != IVE; ++IVI) {
5459 Result += "\t ,{\"";
5460 Result += (*IVI)->getNameAsString();
5461 Result += "\", \"";
5462 std::string TmpString, StrEncoding;
5463 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5464 QuoteDoublequotes(TmpString, StrEncoding);
5465 Result += StrEncoding;
5466 Result += "\", ";
5467 RewriteIvarOffsetComputation((*IVI), Result);
5468 Result += "}\n";
5469 }
5470
5471 Result += "\t }\n};\n";
5472 }
5473
5474 // Build _objc_method_list for class's instance methods if needed
5475 SmallVector<ObjCMethodDecl *, 32>
5476 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5477
5478 // If any of our property implementations have associated getters or
5479 // setters, produce metadata for them as well.
5480 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5481 PropEnd = IDecl->propimpl_end();
5482 Prop != PropEnd; ++Prop) {
5483 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5484 continue;
5485 if (!(*Prop)->getPropertyIvarDecl())
5486 continue;
5487 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5488 if (!PD)
5489 continue;
5490 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5491 if (!Getter->isDefined())
5492 InstanceMethods.push_back(Getter);
5493 if (PD->isReadOnly())
5494 continue;
5495 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5496 if (!Setter->isDefined())
5497 InstanceMethods.push_back(Setter);
5498 }
5499 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5500 true, "", IDecl->getName(), Result);
5501
5502 // Build _objc_method_list for class's class methods if needed
5503 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5504 false, "", IDecl->getName(), Result);
5505
5506 // Protocols referenced in class declaration?
5507 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5508 "CLASS", CDecl->getName(), Result);
5509
5510 // Declaration of class/meta-class metadata
5511 /* struct _objc_class {
5512 struct _objc_class *isa; // or const char *root_class_name when metadata
5513 const char *super_class_name;
5514 char *name;
5515 long version;
5516 long info;
5517 long instance_size;
5518 struct _objc_ivar_list *ivars;
5519 struct _objc_method_list *methods;
5520 struct objc_cache *cache;
5521 struct objc_protocol_list *protocols;
5522 const char *ivar_layout;
5523 struct _objc_class_ext *ext;
5524 };
5525 */
5526 static bool objc_class = false;
5527 if (!objc_class) {
5528 Result += "\nstruct _objc_class {\n";
5529 Result += "\tstruct _objc_class *isa;\n";
5530 Result += "\tconst char *super_class_name;\n";
5531 Result += "\tchar *name;\n";
5532 Result += "\tlong version;\n";
5533 Result += "\tlong info;\n";
5534 Result += "\tlong instance_size;\n";
5535 Result += "\tstruct _objc_ivar_list *ivars;\n";
5536 Result += "\tstruct _objc_method_list *methods;\n";
5537 Result += "\tstruct objc_cache *cache;\n";
5538 Result += "\tstruct _objc_protocol_list *protocols;\n";
5539 Result += "\tconst char *ivar_layout;\n";
5540 Result += "\tstruct _objc_class_ext *ext;\n";
5541 Result += "};\n";
5542 objc_class = true;
5543 }
5544
5545 // Meta-class metadata generation.
5546 ObjCInterfaceDecl *RootClass = 0;
5547 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5548 while (SuperClass) {
5549 RootClass = SuperClass;
5550 SuperClass = SuperClass->getSuperClass();
5551 }
5552 SuperClass = CDecl->getSuperClass();
5553
5554 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5555 Result += CDecl->getNameAsString();
5556 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5557 "{\n\t(struct _objc_class *)\"";
5558 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5559 Result += "\"";
5560
5561 if (SuperClass) {
5562 Result += ", \"";
5563 Result += SuperClass->getNameAsString();
5564 Result += "\", \"";
5565 Result += CDecl->getNameAsString();
5566 Result += "\"";
5567 }
5568 else {
5569 Result += ", 0, \"";
5570 Result += CDecl->getNameAsString();
5571 Result += "\"";
5572 }
5573 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5574 // 'info' field is initialized to CLS_META(2) for metaclass
5575 Result += ", 0,2, sizeof(struct _objc_class), 0";
5576 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5577 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5578 Result += IDecl->getNameAsString();
5579 Result += "\n";
5580 }
5581 else
5582 Result += ", 0\n";
5583 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5584 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5585 Result += CDecl->getNameAsString();
5586 Result += ",0,0\n";
5587 }
5588 else
5589 Result += "\t,0,0,0,0\n";
5590 Result += "};\n";
5591
5592 // class metadata generation.
5593 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5594 Result += CDecl->getNameAsString();
5595 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5596 "{\n\t&_OBJC_METACLASS_";
5597 Result += CDecl->getNameAsString();
5598 if (SuperClass) {
5599 Result += ", \"";
5600 Result += SuperClass->getNameAsString();
5601 Result += "\", \"";
5602 Result += CDecl->getNameAsString();
5603 Result += "\"";
5604 }
5605 else {
5606 Result += ", 0, \"";
5607 Result += CDecl->getNameAsString();
5608 Result += "\"";
5609 }
5610 // 'info' field is initialized to CLS_CLASS(1) for class
5611 Result += ", 0,1";
5612 if (!ObjCSynthesizedStructs.count(CDecl))
5613 Result += ",0";
5614 else {
5615 // class has size. Must synthesize its size.
5616 Result += ",sizeof(struct ";
5617 Result += CDecl->getNameAsString();
5618 if (LangOpts.MicrosoftExt)
5619 Result += "_IMPL";
5620 Result += ")";
5621 }
5622 if (NumIvars > 0) {
5623 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5624 Result += CDecl->getNameAsString();
5625 Result += "\n\t";
5626 }
5627 else
5628 Result += ",0";
5629 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5630 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5631 Result += CDecl->getNameAsString();
5632 Result += ", 0\n\t";
5633 }
5634 else
5635 Result += ",0,0";
5636 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5637 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5638 Result += CDecl->getNameAsString();
5639 Result += ", 0,0\n";
5640 }
5641 else
5642 Result += ",0,0,0\n";
5643 Result += "};\n";
5644}
5645
5646void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5647 int ClsDefCount = ClassImplementation.size();
5648 int CatDefCount = CategoryImplementation.size();
5649
5650 // For each implemented class, write out all its meta data.
5651 for (int i = 0; i < ClsDefCount; i++)
5652 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5653
5654 // For each implemented category, write out all its meta data.
5655 for (int i = 0; i < CatDefCount; i++)
5656 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5657
5658 // Write objc_symtab metadata
5659 /*
5660 struct _objc_symtab
5661 {
5662 long sel_ref_cnt;
5663 SEL *refs;
5664 short cls_def_cnt;
5665 short cat_def_cnt;
5666 void *defs[cls_def_cnt + cat_def_cnt];
5667 };
5668 */
5669
5670 Result += "\nstruct _objc_symtab {\n";
5671 Result += "\tlong sel_ref_cnt;\n";
5672 Result += "\tSEL *refs;\n";
5673 Result += "\tshort cls_def_cnt;\n";
5674 Result += "\tshort cat_def_cnt;\n";
5675 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5676 Result += "};\n\n";
5677
5678 Result += "static struct _objc_symtab "
5679 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5680 Result += "\t0, 0, " + utostr(ClsDefCount)
5681 + ", " + utostr(CatDefCount) + "\n";
5682 for (int i = 0; i < ClsDefCount; i++) {
5683 Result += "\t,&_OBJC_CLASS_";
5684 Result += ClassImplementation[i]->getNameAsString();
5685 Result += "\n";
5686 }
5687
5688 for (int i = 0; i < CatDefCount; i++) {
5689 Result += "\t,&_OBJC_CATEGORY_";
5690 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5691 Result += "_";
5692 Result += CategoryImplementation[i]->getNameAsString();
5693 Result += "\n";
5694 }
5695
5696 Result += "};\n\n";
5697
5698 // Write objc_module metadata
5699
5700 /*
5701 struct _objc_module {
5702 long version;
5703 long size;
5704 const char *name;
5705 struct _objc_symtab *symtab;
5706 }
5707 */
5708
5709 Result += "\nstruct _objc_module {\n";
5710 Result += "\tlong version;\n";
5711 Result += "\tlong size;\n";
5712 Result += "\tconst char *name;\n";
5713 Result += "\tstruct _objc_symtab *symtab;\n";
5714 Result += "};\n\n";
5715 Result += "static struct _objc_module "
5716 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5717 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5718 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5719 Result += "};\n\n";
5720
5721 if (LangOpts.MicrosoftExt) {
5722 if (ProtocolExprDecls.size()) {
5723 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5724 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5725 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5726 E = ProtocolExprDecls.end(); I != E; ++I) {
5727 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5728 Result += (*I)->getNameAsString();
5729 Result += " = &_OBJC_PROTOCOL_";
5730 Result += (*I)->getNameAsString();
5731 Result += ";\n";
5732 }
5733 Result += "#pragma data_seg(pop)\n\n";
5734 }
5735 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5736 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5737 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5738 Result += "&_OBJC_MODULES;\n";
5739 Result += "#pragma data_seg(pop)\n\n";
5740 }
5741}
5742
5743/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5744/// implementation.
5745void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5746 std::string &Result) {
5747 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5748 // Find category declaration for this implementation.
5749 ObjCCategoryDecl *CDecl;
5750 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5751 CDecl = CDecl->getNextClassCategory())
5752 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5753 break;
5754
5755 std::string FullCategoryName = ClassDecl->getNameAsString();
5756 FullCategoryName += '_';
5757 FullCategoryName += IDecl->getNameAsString();
5758
5759 // Build _objc_method_list for class's instance methods if needed
5760 SmallVector<ObjCMethodDecl *, 32>
5761 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5762
5763 // If any of our property implementations have associated getters or
5764 // setters, produce metadata for them as well.
5765 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5766 PropEnd = IDecl->propimpl_end();
5767 Prop != PropEnd; ++Prop) {
5768 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5769 continue;
5770 if (!(*Prop)->getPropertyIvarDecl())
5771 continue;
5772 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5773 if (!PD)
5774 continue;
5775 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5776 InstanceMethods.push_back(Getter);
5777 if (PD->isReadOnly())
5778 continue;
5779 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5780 InstanceMethods.push_back(Setter);
5781 }
5782 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5783 true, "CATEGORY_", FullCategoryName.c_str(),
5784 Result);
5785
5786 // Build _objc_method_list for class's class methods if needed
5787 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5788 false, "CATEGORY_", FullCategoryName.c_str(),
5789 Result);
5790
5791 // Protocols referenced in class declaration?
5792 // Null CDecl is case of a category implementation with no category interface
5793 if (CDecl)
5794 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5795 FullCategoryName, Result);
5796 /* struct _objc_category {
5797 char *category_name;
5798 char *class_name;
5799 struct _objc_method_list *instance_methods;
5800 struct _objc_method_list *class_methods;
5801 struct _objc_protocol_list *protocols;
5802 // Objective-C 1.0 extensions
5803 uint32_t size; // sizeof (struct _objc_category)
5804 struct _objc_property_list *instance_properties; // category's own
5805 // @property decl.
5806 };
5807 */
5808
5809 static bool objc_category = false;
5810 if (!objc_category) {
5811 Result += "\nstruct _objc_category {\n";
5812 Result += "\tchar *category_name;\n";
5813 Result += "\tchar *class_name;\n";
5814 Result += "\tstruct _objc_method_list *instance_methods;\n";
5815 Result += "\tstruct _objc_method_list *class_methods;\n";
5816 Result += "\tstruct _objc_protocol_list *protocols;\n";
5817 Result += "\tunsigned int size;\n";
5818 Result += "\tstruct _objc_property_list *instance_properties;\n";
5819 Result += "};\n";
5820 objc_category = true;
5821 }
5822 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5823 Result += FullCategoryName;
5824 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5825 Result += IDecl->getNameAsString();
5826 Result += "\"\n\t, \"";
5827 Result += ClassDecl->getNameAsString();
5828 Result += "\"\n";
5829
5830 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5831 Result += "\t, (struct _objc_method_list *)"
5832 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5833 Result += FullCategoryName;
5834 Result += "\n";
5835 }
5836 else
5837 Result += "\t, 0\n";
5838 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5839 Result += "\t, (struct _objc_method_list *)"
5840 "&_OBJC_CATEGORY_CLASS_METHODS_";
5841 Result += FullCategoryName;
5842 Result += "\n";
5843 }
5844 else
5845 Result += "\t, 0\n";
5846
5847 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5848 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5849 Result += FullCategoryName;
5850 Result += "\n";
5851 }
5852 else
5853 Result += "\t, 0\n";
5854 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5855}
5856
5857// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5858/// class methods.
5859template<typename MethodIterator>
5860void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5861 MethodIterator MethodEnd,
5862 bool IsInstanceMethod,
5863 StringRef prefix,
5864 StringRef ClassName,
5865 std::string &Result) {
5866 if (MethodBegin == MethodEnd) return;
5867
5868 if (!objc_impl_method) {
5869 /* struct _objc_method {
5870 SEL _cmd;
5871 char *method_types;
5872 void *_imp;
5873 }
5874 */
5875 Result += "\nstruct _objc_method {\n";
5876 Result += "\tSEL _cmd;\n";
5877 Result += "\tchar *method_types;\n";
5878 Result += "\tvoid *_imp;\n";
5879 Result += "};\n";
5880
5881 objc_impl_method = true;
5882 }
5883
5884 // Build _objc_method_list for class's methods if needed
5885
5886 /* struct {
5887 struct _objc_method_list *next_method;
5888 int method_count;
5889 struct _objc_method method_list[];
5890 }
5891 */
5892 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5893 Result += "\nstatic struct {\n";
5894 Result += "\tstruct _objc_method_list *next_method;\n";
5895 Result += "\tint method_count;\n";
5896 Result += "\tstruct _objc_method method_list[";
5897 Result += utostr(NumMethods);
5898 Result += "];\n} _OBJC_";
5899 Result += prefix;
5900 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5901 Result += "_METHODS_";
5902 Result += ClassName;
5903 Result += " __attribute__ ((used, section (\"__OBJC, __";
5904 Result += IsInstanceMethod ? "inst" : "cls";
5905 Result += "_meth\")))= ";
5906 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5907
5908 Result += "\t,{{(SEL)\"";
5909 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5910 std::string MethodTypeString;
5911 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5912 Result += "\", \"";
5913 Result += MethodTypeString;
5914 Result += "\", (void *)";
5915 Result += MethodInternalNames[*MethodBegin];
5916 Result += "}\n";
5917 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5918 Result += "\t ,{(SEL)\"";
5919 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5920 std::string MethodTypeString;
5921 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5922 Result += "\", \"";
5923 Result += MethodTypeString;
5924 Result += "\", (void *)";
5925 Result += MethodInternalNames[*MethodBegin];
5926 Result += "}\n";
5927 }
5928 Result += "\t }\n};\n";
5929}
5930
5931Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5932 SourceRange OldRange = IV->getSourceRange();
5933 Expr *BaseExpr = IV->getBase();
5934
5935 // Rewrite the base, but without actually doing replaces.
5936 {
5937 DisableReplaceStmtScope S(*this);
5938 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5939 IV->setBase(BaseExpr);
5940 }
5941
5942 ObjCIvarDecl *D = IV->getDecl();
5943
5944 Expr *Replacement = IV;
5945 if (CurMethodDef) {
5946 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5947 const ObjCInterfaceType *iFaceDecl =
5948 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5949 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5950 // lookup which class implements the instance variable.
5951 ObjCInterfaceDecl *clsDeclared = 0;
5952 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5953 clsDeclared);
5954 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5955
5956 // Synthesize an explicit cast to gain access to the ivar.
5957 std::string RecName = clsDeclared->getIdentifier()->getName();
5958 RecName += "_IMPL";
5959 IdentifierInfo *II = &Context->Idents.get(RecName);
5960 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5961 SourceLocation(), SourceLocation(),
5962 II);
5963 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5964 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5965 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5966 CK_BitCast,
5967 IV->getBase());
5968 // Don't forget the parens to enforce the proper binding.
5969 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5970 OldRange.getEnd(),
5971 castExpr);
5972 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005973 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005974 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5975 IV->getLocation(),
5976 D->getType(),
5977 VK_LValue, OK_Ordinary);
5978 Replacement = ME;
5979 } else {
5980 IV->setBase(PE);
5981 }
5982 }
5983 } else { // we are outside a method.
5984 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5985
5986 // Explicit ivar refs need to have a cast inserted.
5987 // FIXME: consider sharing some of this code with the code above.
5988 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5989 const ObjCInterfaceType *iFaceDecl =
5990 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5991 // lookup which class implements the instance variable.
5992 ObjCInterfaceDecl *clsDeclared = 0;
5993 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5994 clsDeclared);
5995 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5996
5997 // Synthesize an explicit cast to gain access to the ivar.
5998 std::string RecName = clsDeclared->getIdentifier()->getName();
5999 RecName += "_IMPL";
6000 IdentifierInfo *II = &Context->Idents.get(RecName);
6001 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6002 SourceLocation(), SourceLocation(),
6003 II);
6004 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6005 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6006 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6007 CK_BitCast,
6008 IV->getBase());
6009 // Don't forget the parens to enforce the proper binding.
6010 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6011 IV->getBase()->getLocEnd(), castExpr);
6012 // Cannot delete IV->getBase(), since PE points to it.
6013 // Replace the old base with the cast. This is important when doing
6014 // embedded rewrites. For example, [newInv->_container addObject:0].
6015 IV->setBase(PE);
6016 }
6017 }
6018
6019 ReplaceStmtWithRange(IV, Replacement, OldRange);
6020 return Replacement;
6021}
6022