blob: 396c7aeec202c44e8d18e0f94c1c981c69d41f81 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
Chris Lattner01c57482007-10-17 22:35:30 +000063 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000064 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000065 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000066 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000067 const char *MainFileStart, *MainFileEnd;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000122 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
John McCallf4b88a42012-03-10 09:33:50 +0000124 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Douglas Gregor375bb142011-12-27 22:43:10 +0000168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Douglas Gregor375bb142011-12-27 22:43:10 +0000174
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
Chris Lattner682bf922009-03-29 16:50:03 +0000182 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000183 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000184 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000185 }
186 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000187 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000188 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000189 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000190 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000191
192 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000194 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000198
Steve Naroff4c3580e2008-12-04 23:50:32 +0000199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000201
Steve Naroffb619d952008-12-09 12:56:34 +0000202 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000203 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000204
Steve Naroff4c3580e2008-12-04 23:50:32 +0000205 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000206 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000214 }
Steve Naroffb619d952008-12-09 12:56:34 +0000215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000217 if (DisableReplaceStmt)
218 return;
219
Nick Lewycky7e749242010-10-31 21:07:24 +0000220 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
Chris Lattner5f9e2722011-07-23 10:55:15 +0000244 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000245 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000255 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000256 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000258 SilenceRewriteMacroWarning)
259 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000260
Chris Lattneraadaf782008-01-31 19:51:04 +0000261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnerf04da132007-10-24 17:06:59 +0000264 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000265 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000266 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000267 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
Douglas Gregor375bb142011-12-27 22:43:10 +0000269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000270 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000271 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000276 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000282 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000288 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000289 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000294 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000296
Chris Lattnerf04da132007-10-24 17:06:59 +0000297 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000316
Steve Naroff54055232008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000319
Mike Stump1eb44332009-09-09 15:08:12 +0000320 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000321 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000322 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000323 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000329
330 virtual void Initialize(ASTContext &context) = 0;
331
332 // Metadata Rewriting.
333 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
334 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
335 StringRef prefix,
336 StringRef ClassName,
337 std::string &Result) = 0;
338 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
339 std::string &Result) = 0;
340 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
341 StringRef prefix,
342 StringRef ClassName,
343 std::string &Result) = 0;
344 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
345 std::string &Result) = 0;
346
347 // Rewriting ivar access
348 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
349 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
350 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000351
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000352 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian58457172011-12-05 18:43:13 +0000353 // rewriting routines on the new ASTs.
354 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
355 Expr **args, unsigned nargs,
356 SourceLocation StartLoc=SourceLocation(),
357 SourceLocation EndLoc=SourceLocation());
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
David Blaikie4e4d0842012-03-11 07:00:24 +0000633 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
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)
David Blaikie262bc182012-04-30 02:36:29 +0000970 RewriteProperty(&*I);
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000971
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)
David Blaikie262bc182012-04-30 02:36:29 +00001004 RewriteProperty(&*I);
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001005
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 (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001140 (void)convertBlockPointerToFunctionPointer(QT);
1141 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001142 ResultStr += Name;
1143 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001144 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001145 if (OMD->isVariadic())
1146 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001147 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Steve Naroff76e429d2008-07-16 14:40:40 +00001149 if (FPRetType) {
1150 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Steve Naroff76e429d2008-07-16 14:40:40 +00001152 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001153 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001154 ResultStr += "(";
1155 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1156 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001157 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001158 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001159 ResultStr += ParamStr;
1160 }
1161 if (FT->isVariadic()) {
1162 if (FT->getNumArgs()) ResultStr += ", ";
1163 ResultStr += "...";
1164 }
1165 ResultStr += ")";
1166 } else {
1167 ResultStr += "()";
1168 }
1169 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001171void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001172 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1173 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001175 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001177 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001178 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1179 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001180 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001182 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001183 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001184 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001185 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001186
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001187 const char *startBuf = SM->getCharacterData(LocStart);
1188 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001189 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190 }
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001192 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001193 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1194 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001195 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001197 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001198 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001199 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001200 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001201
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001202 const char *startBuf = SM->getCharacterData(LocStart);
1203 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001204 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001206 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001207 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001208 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001209 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001210 RewritePropertyImplDecl(&*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001211 }
1212
Benjamin Kramerd999b372010-02-14 14:14:16 +00001213 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214}
1215
Steve Naroffb29b4272008-04-14 22:03:09 +00001216void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001217 std::string ResultStr;
Douglas Gregor7723fec2011-12-15 20:29:51 +00001218 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001219 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001220 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001221 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001222 ResultStr += "\n";
1223 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001224 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001225 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001226 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001227 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001228 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001229 // Mark this typedef as having been generated.
Douglas Gregor7723fec2011-12-15 20:29:51 +00001230 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001231 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001232 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
1234 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001235 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001236 RewriteProperty(&*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001237 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001238 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001239 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001240 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001241 for (ObjCInterfaceDecl::classmeth_iterator
1242 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001243 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001244 RewriteMethodDeclaration(*I);
1245
Steve Naroff2feac5e2007-10-30 03:43:13 +00001246 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001247 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1248 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001249}
1250
John McCall4b9c2d22011-11-06 09:01:30 +00001251Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1252 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001253
John McCall4b9c2d22011-11-06 09:01:30 +00001254 // We just magically know some things about the structure of this
1255 // expression.
1256 ObjCMessageExpr *OldMsg =
1257 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1258 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001259
John McCall4b9c2d22011-11-06 09:01:30 +00001260 // Because the rewriter doesn't allow us to rewrite rewritten code,
1261 // we need to suppress rewriting the sub-statements.
1262 Expr *Base, *RHS;
1263 {
1264 DisableReplaceStmtScope S(*this);
1265
1266 // Rebuild the base expression if we have one.
1267 Base = 0;
1268 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1269 Base = OldMsg->getInstanceReceiver();
1270 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1271 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1272 }
1273
1274 // Rebuild the RHS.
1275 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1276 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1277 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1278 }
1279
1280 // TODO: avoid this copy.
1281 SmallVector<SourceLocation, 1> SelLocs;
1282 OldMsg->getSelectorLocs(SelLocs);
1283
Chad Rosier0774ba72012-01-06 20:05:14 +00001284 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001285 switch (OldMsg->getReceiverKind()) {
1286 case ObjCMessageExpr::Class:
1287 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1288 OldMsg->getValueKind(),
1289 OldMsg->getLeftLoc(),
1290 OldMsg->getClassReceiverTypeInfo(),
1291 OldMsg->getSelector(),
1292 SelLocs,
1293 OldMsg->getMethodDecl(),
1294 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001295 OldMsg->getRightLoc(),
1296 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001297 break;
1298
1299 case ObjCMessageExpr::Instance:
1300 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1301 OldMsg->getValueKind(),
1302 OldMsg->getLeftLoc(),
1303 Base,
1304 OldMsg->getSelector(),
1305 SelLocs,
1306 OldMsg->getMethodDecl(),
1307 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001308 OldMsg->getRightLoc(),
1309 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001310 break;
1311
1312 case ObjCMessageExpr::SuperClass:
1313 case ObjCMessageExpr::SuperInstance:
1314 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1315 OldMsg->getValueKind(),
1316 OldMsg->getLeftLoc(),
1317 OldMsg->getSuperLoc(),
1318 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1319 OldMsg->getSuperType(),
1320 OldMsg->getSelector(),
1321 SelLocs,
1322 OldMsg->getMethodDecl(),
1323 RHS,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001324 OldMsg->getRightLoc(),
1325 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001326 break;
1327 }
1328
1329 Stmt *Replacement = SynthMessageExpr(NewMsg);
1330 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1331 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001332}
1333
John McCall4b9c2d22011-11-06 09:01:30 +00001334Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1335 SourceRange OldRange = PseudoOp->getSourceRange();
1336
1337 // We just magically know some things about the structure of this
1338 // expression.
1339 ObjCMessageExpr *OldMsg =
1340 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1341
1342 // Because the rewriter doesn't allow us to rewrite rewritten code,
1343 // we need to suppress rewriting the sub-statements.
1344 Expr *Base = 0;
1345 {
1346 DisableReplaceStmtScope S(*this);
1347
1348 // Rebuild the base expression if we have one.
1349 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1350 Base = OldMsg->getInstanceReceiver();
1351 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1352 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001353 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001354 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001355
John McCall4b9c2d22011-11-06 09:01:30 +00001356 // Intentionally empty.
1357 SmallVector<SourceLocation, 1> SelLocs;
1358 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001359
Chad Rosier0774ba72012-01-06 20:05:14 +00001360 ObjCMessageExpr *NewMsg = 0;
John McCall4b9c2d22011-11-06 09:01:30 +00001361 switch (OldMsg->getReceiverKind()) {
1362 case ObjCMessageExpr::Class:
1363 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1364 OldMsg->getValueKind(),
1365 OldMsg->getLeftLoc(),
1366 OldMsg->getClassReceiverTypeInfo(),
1367 OldMsg->getSelector(),
1368 SelLocs,
1369 OldMsg->getMethodDecl(),
1370 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001371 OldMsg->getRightLoc(),
1372 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001373 break;
1374
1375 case ObjCMessageExpr::Instance:
1376 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1377 OldMsg->getValueKind(),
1378 OldMsg->getLeftLoc(),
1379 Base,
1380 OldMsg->getSelector(),
1381 SelLocs,
1382 OldMsg->getMethodDecl(),
1383 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001384 OldMsg->getRightLoc(),
1385 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001386 break;
1387
1388 case ObjCMessageExpr::SuperClass:
1389 case ObjCMessageExpr::SuperInstance:
1390 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1391 OldMsg->getValueKind(),
1392 OldMsg->getLeftLoc(),
1393 OldMsg->getSuperLoc(),
1394 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1395 OldMsg->getSuperType(),
1396 OldMsg->getSelector(),
1397 SelLocs,
1398 OldMsg->getMethodDecl(),
1399 Args,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001400 OldMsg->getRightLoc(),
1401 OldMsg->isImplicit());
John McCall4b9c2d22011-11-06 09:01:30 +00001402 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001403 }
John McCall4b9c2d22011-11-06 09:01:30 +00001404
1405 Stmt *Replacement = SynthMessageExpr(NewMsg);
1406 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1407 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001408}
1409
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001410/// SynthCountByEnumWithState - To print:
1411/// ((unsigned int (*)
1412/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001413/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001414/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001415/// "countByEnumeratingWithState:objects:count:"),
1416/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001417/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001418///
Steve Naroffb29b4272008-04-14 22:03:09 +00001419void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1421 "id *, unsigned int))(void *)objc_msgSend)";
1422 buf += "\n\t\t";
1423 buf += "((id)l_collection,\n\t\t";
1424 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1425 buf += "\n\t\t";
1426 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001427 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001428}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001429
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001430/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1431/// statement to exit to its outer synthesized loop.
1432///
Steve Naroffb29b4272008-04-14 22:03:09 +00001433Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001434 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1435 return S;
1436 // replace break with goto __break_label
1437 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001439 SourceLocation startLoc = S->getLocStart();
1440 buf = "goto __break_label_";
1441 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001442 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001443
1444 return 0;
1445}
1446
1447/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1448/// statement to continue with its inner synthesized loop.
1449///
Steve Naroffb29b4272008-04-14 22:03:09 +00001450Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001451 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1452 return S;
1453 // replace continue with goto __continue_label
1454 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 SourceLocation startLoc = S->getLocStart();
1457 buf = "goto __continue_label_";
1458 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001459 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001461 return 0;
1462}
1463
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001464/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001465/// It rewrites:
1466/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001468/// Into:
1469/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001470/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001472/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001473/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001474/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001475/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001476/// if (limit) {
1477/// unsigned long startMutations = *enumState.mutationsPtr;
1478/// do {
1479/// unsigned long counter = 0;
1480/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001481/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001482/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001483/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001484/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001485/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001486/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001487/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001488/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001489/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001490/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001491/// }
1492/// else
1493/// elem = nil;
1494/// }
1495///
Steve Naroffb29b4272008-04-14 22:03:09 +00001496Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001497 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001498 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001499 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001500 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001501 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001502 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001504 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001506 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001507 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001508 std::string buf;
1509 buf = "\n{\n\t";
1510 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1511 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001512 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001513 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001514 if (ElementType->isObjCQualifiedIdType() ||
1515 ElementType->isObjCQualifiedInterfaceType())
1516 // Simply use 'id' for all qualified types.
1517 elementTypeAsString = "id";
1518 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001519 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001520 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001522 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 buf += elementName;
1524 buf += ";\n\t";
1525 }
Chris Lattner06767512008-04-08 05:52:18 +00001526 else {
1527 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001528 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001529 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1530 if (VD->getType()->isObjCQualifiedIdType() ||
1531 VD->getType()->isObjCQualifiedInterfaceType())
1532 // Simply use 'id' for all qualified types.
1533 elementTypeAsString = "id";
1534 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001535 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001536 }
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001538 // struct __objcFastEnumerationState enumState = { 0 };
1539 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001540 // id __rw_items[16];
1541 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542 // id l_collection = (id)
1543 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001544 // Find start location of 'collection' the hard way!
1545 const char *startCollectionBuf = startBuf;
1546 startCollectionBuf += 3; // skip 'for'
1547 startCollectionBuf = strchr(startCollectionBuf, '(');
1548 startCollectionBuf++; // skip '('
1549 // find 'in' and skip it.
1550 while (*startCollectionBuf != ' ' ||
1551 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1552 (*(startCollectionBuf+3) != ' ' &&
1553 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1554 startCollectionBuf++;
1555 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
1557 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001558 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001559 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001560 SourceLocation rightParenLoc = S->getRParenLoc();
1561 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001562 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001566 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001568 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 // ((unsigned int (*)
1570 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001571 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001573 // "countByEnumeratingWithState:objects:count:"),
1574 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001575 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001576 buf += "unsigned long limit =\n\t\t";
1577 SynthCountByEnumWithState(buf);
1578 buf += ";\n\t";
1579 /// if (limit) {
1580 /// unsigned long startMutations = *enumState.mutationsPtr;
1581 /// do {
1582 /// unsigned long counter = 0;
1583 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001584 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001585 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001586 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001587 buf += "if (limit) {\n\t";
1588 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1589 buf += "do {\n\t\t";
1590 buf += "unsigned long counter = 0;\n\t\t";
1591 buf += "do {\n\t\t\t";
1592 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1593 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1594 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001595 buf += " = (";
1596 buf += elementTypeAsString;
1597 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001598 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001599 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001602 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001603 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001604 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001605 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607 /// }
1608 /// else
1609 /// elem = nil;
1610 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001611 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001612 buf = ";\n\t";
1613 buf += "__continue_label_";
1614 buf += utostr(ObjCBcLabelNo.back());
1615 buf += ": ;";
1616 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001617 buf += "} while (counter < limit);\n\t";
1618 buf += "} while (limit = ";
1619 SynthCountByEnumWithState(buf);
1620 buf += ");\n\t";
1621 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001622 buf += " = ((";
1623 buf += elementTypeAsString;
1624 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001625 buf += "__break_label_";
1626 buf += utostr(ObjCBcLabelNo.back());
1627 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628 buf += "}\n\t";
1629 buf += "else\n\t\t";
1630 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001631 buf += " = ((";
1632 buf += elementTypeAsString;
1633 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001636 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001637 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001638 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001639 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001640 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001641 } else {
1642 /* Need to treat single statements specially. For example:
1643 *
1644 * for (A *a in b) if (stuff()) break;
1645 * for (A *a in b) xxxyy;
1646 *
1647 * The following code simply scans ahead to the semi to find the actual end.
1648 */
1649 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1650 const char *semiBuf = strchr(stmtBuf, ';');
1651 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001652 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001653 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001654 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 Stmts.pop_back();
1656 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001658}
1659
Mike Stump1eb44332009-09-09 15:08:12 +00001660/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001661/// This routine rewrites @synchronized(expr) stmt;
1662/// into:
1663/// objc_sync_enter(expr);
1664/// @try stmt @finally { objc_sync_exit(expr); }
1665///
Steve Naroffb29b4272008-04-14 22:03:09 +00001666Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001667 // Get the start location and compute the semi location.
1668 SourceLocation startLoc = S->getLocStart();
1669 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001671 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001672
1673 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001674 buf = "objc_sync_enter((id)";
1675 const char *lparenBuf = startBuf;
1676 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001677 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001678 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1679 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001680 // been rewritten! (which implies the SourceLocation's are invalid).
1681 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001682 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001683 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001684 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001685 buf = ");\n";
1686 // declare a new scope with two variables, _stack and _rethrow.
1687 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1688 buf += "int buf[18/*32-bit i386*/];\n";
1689 buf += "char *pointers[4];} _stack;\n";
1690 buf += "id volatile _rethrow = 0;\n";
1691 buf += "objc_exception_try_enter(&_stack);\n";
1692 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001693 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001694 startLoc = S->getSynchBody()->getLocEnd();
1695 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Steve Naroffc7089f12008-08-19 13:04:19 +00001697 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001698 SourceLocation lastCurlyLoc = startLoc;
1699 buf = "}\nelse {\n";
1700 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001701 buf += "}\n";
1702 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001703 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001704
1705 std::string syncBuf;
1706 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001707
1708 Expr *syncExpr = S->getSynchExpr();
1709 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1710 ? CK_BitCast :
1711 syncExpr->getType()->isBlockPointerType()
1712 ? CK_BlockPointerToObjCPointerCast
1713 : CK_CPointerToObjCPointerCast;
1714 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1715 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001716 std::string syncExprBufS;
1717 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001718 syncExpr->printPretty(syncExprBuf, *Context, 0,
1719 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001720 syncBuf += syncExprBuf.str();
1721 syncBuf += ");";
1722
1723 buf += syncBuf;
1724 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001725 buf += "}\n";
1726 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Benjamin Kramerd999b372010-02-14 14:14:16 +00001728 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001729
1730 bool hasReturns = false;
1731 HasReturnStmts(S->getSynchBody(), hasReturns);
1732 if (hasReturns)
1733 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1734
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001735 return 0;
1736}
1737
Steve Naroffb85e77a2009-12-05 21:43:12 +00001738void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1739{
Steve Naroff8c565152008-12-05 17:03:39 +00001740 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001741 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001742 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001743 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001744
Steve Naroffb85e77a2009-12-05 21:43:12 +00001745 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001746 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001747 TryFinallyContainsReturnDiag);
1748 }
1749 return;
1750}
1751
Steve Naroffb85e77a2009-12-05 21:43:12 +00001752void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1753{
1754 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001755 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001756 if (*CI)
1757 HasReturnStmts(*CI, hasReturns);
1758
1759 if (isa<ReturnStmt>(S))
1760 hasReturns = true;
1761 return;
1762}
1763
1764void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1765 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001766 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001767 if (*CI) {
1768 RewriteTryReturnStmts(*CI);
1769 }
1770 if (isa<ReturnStmt>(S)) {
1771 SourceLocation startLoc = S->getLocStart();
1772 const char *startBuf = SM->getCharacterData(startLoc);
1773
1774 const char *semiBuf = strchr(startBuf, ';');
1775 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001776 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001777
1778 std::string buf;
1779 buf = "{ objc_exception_try_exit(&_stack); return";
1780
Benjamin Kramerd999b372010-02-14 14:14:16 +00001781 ReplaceText(startLoc, 6, buf);
1782 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001783 }
1784 return;
1785}
1786
1787void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1788 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001789 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001790 if (*CI) {
1791 RewriteSyncReturnStmts(*CI, syncExitBuf);
1792 }
1793 if (isa<ReturnStmt>(S)) {
1794 SourceLocation startLoc = S->getLocStart();
1795 const char *startBuf = SM->getCharacterData(startLoc);
1796
1797 const char *semiBuf = strchr(startBuf, ';');
1798 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001799 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001800
1801 std::string buf;
1802 buf = "{ objc_exception_try_exit(&_stack);";
1803 buf += syncExitBuf;
1804 buf += " return";
1805
Benjamin Kramerd999b372010-02-14 14:14:16 +00001806 ReplaceText(startLoc, 6, buf);
1807 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001808 }
1809 return;
1810}
1811
Steve Naroffb29b4272008-04-14 22:03:09 +00001812Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001813 // Get the start location and compute the semi location.
1814 SourceLocation startLoc = S->getLocStart();
1815 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001816
Steve Naroff75730982007-11-07 04:08:17 +00001817 assert((*startBuf == '@') && "bogus @try location");
1818
1819 std::string buf;
1820 // declare a new scope with two variables, _stack and _rethrow.
1821 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1822 buf += "int buf[18/*32-bit i386*/];\n";
1823 buf += "char *pointers[4];} _stack;\n";
1824 buf += "id volatile _rethrow = 0;\n";
1825 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001826 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001827
Benjamin Kramerd999b372010-02-14 14:14:16 +00001828 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001829
Steve Naroff75730982007-11-07 04:08:17 +00001830 startLoc = S->getTryBody()->getLocEnd();
1831 startBuf = SM->getCharacterData(startLoc);
1832
1833 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff75730982007-11-07 04:08:17 +00001835 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001836 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001837 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001838 buf = " /* @catch begin */ else {\n";
1839 buf += " id _caught = objc_exception_extract(&_stack);\n";
1840 buf += " objc_exception_try_enter (&_stack);\n";
1841 buf += " if (_setjmp(_stack.buf))\n";
1842 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1843 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Benjamin Kramerd999b372010-02-14 14:14:16 +00001845 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001846 } else { /* no catch list */
1847 buf = "}\nelse {\n";
1848 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1849 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001851 }
Steve Naroff75730982007-11-07 04:08:17 +00001852 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001853 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1854 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001855 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001856
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001857 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001858 buf = "if ("; // we are generating code for the first catch clause
1859 else
1860 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001861 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001862 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Steve Naroff75730982007-11-07 04:08:17 +00001864 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001865
Steve Naroff75730982007-11-07 04:08:17 +00001866 const char *lParenLoc = strchr(startBuf, '(');
1867
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001868 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001869 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001870 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001871 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1872 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001873 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001874 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001875 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Steve Naroffe12e6922008-02-01 20:02:07 +00001877 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001878 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001879 } else if (catchDecl) {
1880 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001881 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001882 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001883 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001884 } else if (const ObjCObjectPointerType *Ptr =
1885 t->getAs<ObjCObjectPointerType>()) {
1886 // Should be a pointer to a class.
1887 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1888 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001889 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001890 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001891 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001892 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001893 }
1894 }
1895 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001896 lastCatchBody = Catch->getCatchBody();
1897 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001898 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1899 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1900 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1901 assert((*rParenBuf == ')') && "bogus @catch paren location");
1902 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Mike Stump1eb44332009-09-09 15:08:12 +00001904 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001905 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001906 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001907 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001908 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001909 }
Steve Naroff75730982007-11-07 04:08:17 +00001910 }
1911 // Complete the catch list...
1912 if (lastCatchBody) {
1913 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001914 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1915 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Steve Naroff378f47a2008-09-11 15:29:03 +00001917 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001918 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001919 buf = "} /* last catch end */\n";
1920 buf += "else {\n";
1921 buf += " _rethrow = _caught;\n";
1922 buf += " objc_exception_try_exit(&_stack);\n";
1923 buf += "} } /* @catch end */\n";
1924 if (!S->getFinallyStmt())
1925 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001926 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Steve Naroff75730982007-11-07 04:08:17 +00001928 // Set lastCurlyLoc
1929 lastCurlyLoc = lastCatchBody->getLocEnd();
1930 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001931 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001932 startLoc = finalStmt->getLocStart();
1933 startBuf = SM->getCharacterData(startLoc);
1934 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Benjamin Kramerd999b372010-02-14 14:14:16 +00001936 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Steve Naroff75730982007-11-07 04:08:17 +00001938 Stmt *body = finalStmt->getFinallyBody();
1939 SourceLocation startLoc = body->getLocStart();
1940 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001941 assert(*SM->getCharacterData(startLoc) == '{' &&
1942 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001943 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001944 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001945
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001946 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001947 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001948 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001949 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Steve Naroff75730982007-11-07 04:08:17 +00001951 // Set lastCurlyLoc
1952 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Steve Naroff8c565152008-12-05 17:03:39 +00001954 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001955 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001956 } else { /* no finally clause - make sure we synthesize an implicit one */
1957 buf = "{ /* implicit finally clause */\n";
1958 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1959 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1960 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001961 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001962
1963 // Now check for any return/continue/go statements within the @try.
1964 // The implicit finally clause won't called if the @try contains any
1965 // jump statements.
1966 bool hasReturns = false;
1967 HasReturnStmts(S->getTryBody(), hasReturns);
1968 if (hasReturns)
1969 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001970 }
1971 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001972 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001973 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001974 return 0;
1975}
1976
Mike Stump1eb44332009-09-09 15:08:12 +00001977// This can't be done with ReplaceStmt(S, ThrowExpr), since
1978// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001979// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001980Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001981 // Get the start location and compute the semi location.
1982 SourceLocation startLoc = S->getLocStart();
1983 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Steve Naroff2bd03922007-11-07 15:32:26 +00001985 assert((*startBuf == '@') && "bogus @throw location");
1986
1987 std::string buf;
1988 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001989 if (S->getThrowExpr())
1990 buf = "objc_exception_throw(";
1991 else // add an implicit argument
1992 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001994 // handle "@ throw" correctly.
1995 const char *wBuf = strchr(startBuf, 'w');
1996 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroff2bd03922007-11-07 15:32:26 +00001999 const char *semiBuf = strchr(startBuf, ';');
2000 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002001 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002003 return 0;
2004}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002005
Steve Naroffb29b4272008-04-14 22:03:09 +00002006Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002007 // Create a new string expression.
2008 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002009 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002010 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002011 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002012 StringLiteral::Ascii, false,
2013 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002014 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Chris Lattner07506182007-11-30 22:53:43 +00002016 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002017 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002018 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002019}
2020
Steve Naroffb29b4272008-04-14 22:03:09 +00002021Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002022 if (!SelGetUidFunctionDecl)
2023 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002024 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2025 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002026 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002027 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002028 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002029 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002030 StringLiteral::Ascii, false,
2031 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002032 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2033 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002034 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002035 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002036 return SelExp;
2037}
2038
Steve Naroffb29b4272008-04-14 22:03:09 +00002039CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002040 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2041 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002042 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002043 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Steve Naroffebf2b562007-10-23 23:50:29 +00002045 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002046 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, msgSendType,
2047 VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroffebf2b562007-10-23 23:50:29 +00002049 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002050 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002051 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002052 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002053 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002054
John McCall183700f2009-09-21 23:43:11 +00002055 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002057 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002058 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002059 FT->getCallResultType(*Context),
2060 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002061 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002062}
2063
Steve Naroffd5255f52007-11-01 13:24:47 +00002064static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2065 const char *&startRef, const char *&endRef) {
2066 while (startBuf < endBuf) {
2067 if (*startBuf == '<')
2068 startRef = startBuf; // mark the start.
2069 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002070 if (startRef && *startRef == '<') {
2071 endRef = startBuf; // mark the end.
2072 return true;
2073 }
2074 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002075 }
2076 startBuf++;
2077 }
2078 return false;
2079}
2080
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002081static void scanToNextArgument(const char *&argRef) {
2082 int angle = 0;
2083 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2084 if (*argRef == '<')
2085 angle++;
2086 else if (*argRef == '>')
2087 angle--;
2088 argRef++;
2089 }
2090 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2091}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002092
Steve Naroffb29b4272008-04-14 22:03:09 +00002093bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002094 if (T->isObjCQualifiedIdType())
2095 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002096 if (const PointerType *PT = T->getAs<PointerType>()) {
2097 if (PT->getPointeeType()->isObjCQualifiedIdType())
2098 return true;
2099 }
2100 if (T->isObjCObjectPointerType()) {
2101 T = T->getPointeeType();
2102 return T->isObjCQualifiedInterfaceType();
2103 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002104 if (T->isArrayType()) {
2105 QualType ElemTy = Context->getBaseElementType(T);
2106 return needToScanForQualifiers(ElemTy);
2107 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002108 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002109}
2110
Steve Naroff4f95b752008-07-29 18:15:38 +00002111void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2112 QualType Type = E->getType();
2113 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002114 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002115
Steve Naroffcda658e2008-11-19 21:15:47 +00002116 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2117 Loc = ECE->getLParenLoc();
2118 EndLoc = ECE->getRParenLoc();
2119 } else {
2120 Loc = E->getLocStart();
2121 EndLoc = E->getLocEnd();
2122 }
2123 // This will defend against trying to rewrite synthesized expressions.
2124 if (Loc.isInvalid() || EndLoc.isInvalid())
2125 return;
2126
Steve Naroff4f95b752008-07-29 18:15:38 +00002127 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002128 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002129 const char *startRef = 0, *endRef = 0;
2130 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2131 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002132 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2133 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002134 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002135 InsertText(LessLoc, "/*");
2136 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002137 }
2138 }
2139}
2140
Steve Naroffb29b4272008-04-14 22:03:09 +00002141void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002142 SourceLocation Loc;
2143 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002144 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002145 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2146 Loc = VD->getLocation();
2147 Type = VD->getType();
2148 }
2149 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2150 Loc = FD->getLocation();
2151 // Check for ObjC 'id' and class types that have been adorned with protocol
2152 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002153 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002154 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002155 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002156 if (!proto)
2157 return;
2158 Type = proto->getResultType();
2159 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002160 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2161 Loc = FD->getLocation();
2162 Type = FD->getType();
2163 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002164 else
2165 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002167 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002168 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Steve Naroffd5255f52007-11-01 13:24:47 +00002170 const char *endBuf = SM->getCharacterData(Loc);
2171 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002172 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002173 startBuf--; // scan backward (from the decl location) for return type.
2174 const char *startRef = 0, *endRef = 0;
2175 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2176 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002177 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2178 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002179 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002180 InsertText(LessLoc, "/*");
2181 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002182 }
2183 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002184 if (!proto)
2185 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002186 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002187 const char *startBuf = SM->getCharacterData(Loc);
2188 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002189 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2190 if (needToScanForQualifiers(proto->getArgType(i))) {
2191 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Steve Naroffd5255f52007-11-01 13:24:47 +00002193 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002194 // scan forward (from the decl location) for argument types.
2195 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002196 const char *startRef = 0, *endRef = 0;
2197 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2198 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002199 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002200 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002202 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002203 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002204 InsertText(LessLoc, "/*");
2205 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002206 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002207 startBuf = ++endBuf;
2208 }
2209 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002210 // If the function name is derived from a macro expansion, then the
2211 // argument buffer will not follow the name. Need to speak with Chris.
2212 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002213 startBuf++; // scan forward (from the decl location) for argument types.
2214 startBuf++;
2215 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002216 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002217}
2218
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002219void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2220 QualType QT = ND->getType();
2221 const Type* TypePtr = QT->getAs<Type>();
2222 if (!isa<TypeOfExprType>(TypePtr))
2223 return;
2224 while (isa<TypeOfExprType>(TypePtr)) {
2225 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2226 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2227 TypePtr = QT->getAs<Type>();
2228 }
2229 // FIXME. This will not work for multiple declarators; as in:
2230 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002231 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002232 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2233 const char *startBuf = SM->getCharacterData(DeclLoc);
2234 if (ND->getInit()) {
2235 std::string Name(ND->getNameAsString());
2236 TypeAsString += " " + Name + " = ";
2237 Expr *E = ND->getInit();
2238 SourceLocation startLoc;
2239 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2240 startLoc = ECE->getLParenLoc();
2241 else
2242 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002243 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002244 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002245 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002246 }
2247 else {
2248 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002249 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002250 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002251 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002252 }
2253}
2254
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002255// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002256void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002257 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002258 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002259 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002260 QualType getFuncType =
2261 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002262 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002263 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002264 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002265 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002266 SC_Extern,
2267 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002268}
2269
Steve Naroffb29b4272008-04-14 22:03:09 +00002270void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002271 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002272 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002273 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002274 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002275 return;
2276 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002277 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002278}
2279
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002280void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002281 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002282 const char *argPtr = TypeString.c_str();
2283 if (!strchr(argPtr, '^')) {
2284 Str += TypeString;
2285 return;
2286 }
2287 while (*argPtr) {
2288 Str += (*argPtr == '^' ? '*' : *argPtr);
2289 argPtr++;
2290 }
2291}
2292
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002293// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002294void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2295 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002296 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002297 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298 const char *argPtr = TypeString.c_str();
2299 int paren = 0;
2300 while (*argPtr) {
2301 switch (*argPtr) {
2302 case '(':
2303 Str += *argPtr;
2304 paren++;
2305 break;
2306 case ')':
2307 Str += *argPtr;
2308 paren--;
2309 break;
2310 case '^':
2311 Str += '*';
2312 if (paren == 1)
2313 Str += VD->getNameAsString();
2314 break;
2315 default:
2316 Str += *argPtr;
2317 break;
2318 }
2319 argPtr++;
2320 }
2321}
2322
2323
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002324void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2325 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2326 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2327 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2328 if (!proto)
2329 return;
2330 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002331 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002332 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002333 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002334 FdStr += "(";
2335 unsigned numArgs = proto->getNumArgs();
2336 for (unsigned i = 0; i < numArgs; i++) {
2337 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002338 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002339 if (i+1 < numArgs)
2340 FdStr += ", ";
2341 }
2342 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002343 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002344 CurFunctionDeclToDeclareForBlock = 0;
2345}
2346
Steve Naroffc0a123c2008-03-11 17:37:02 +00002347// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002348void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002349 if (SuperContructorFunctionDecl)
2350 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002351 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002352 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002353 QualType argT = Context->getObjCIdType();
2354 assert(!argT.isNull() && "Can't find 'id' type");
2355 ArgTys.push_back(argT);
2356 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002359 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002360 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002361 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002362 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002363 SC_Extern,
2364 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002365}
2366
Steve Naroff09b266e2007-10-30 23:14:51 +00002367// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002368void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002369 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002370 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002371 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002372 assert(!argT.isNull() && "Can't find 'id' type");
2373 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002375 assert(!argT.isNull() && "Can't find 'SEL' type");
2376 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002377 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2378 &ArgTys[0], ArgTys.size(),
2379 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002380 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002381 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002382 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002383 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002384 SC_Extern,
2385 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002386}
2387
Steve Naroff874e2322007-11-15 10:28:18 +00002388// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002389void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002390 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002391 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002392 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002393 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002394 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002395 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2396 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2397 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002398 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002399 assert(!argT.isNull() && "Can't find 'SEL' type");
2400 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002401 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2402 &ArgTys[0], ArgTys.size(),
2403 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002404 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002405 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002406 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002407 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002408 SC_Extern,
2409 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002410}
2411
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002412// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002414 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002416 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002417 assert(!argT.isNull() && "Can't find 'id' type");
2418 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002419 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002420 assert(!argT.isNull() && "Can't find 'SEL' type");
2421 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002422 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002423 &ArgTys[0], ArgTys.size(),
2424 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002425 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002426 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002427 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002428 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002429 SC_Extern,
2430 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002431}
2432
Mike Stump1eb44332009-09-09 15:08:12 +00002433// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002434// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002435void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002436 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002437 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002438 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002439 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002440 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002441 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2443 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2444 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002445 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002446 assert(!argT.isNull() && "Can't find 'SEL' type");
2447 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002448 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002449 &ArgTys[0], ArgTys.size(),
2450 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002451 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002452 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002453 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002454 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002455 SC_Extern,
2456 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002457}
2458
Steve Naroff1284db82008-05-08 22:02:18 +00002459// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002460void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002461 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002462 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002463 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002464 assert(!argT.isNull() && "Can't find 'id' type");
2465 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002466 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002467 assert(!argT.isNull() && "Can't find 'SEL' type");
2468 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002469 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2470 &ArgTys[0], ArgTys.size(),
2471 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002472 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002473 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002474 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002475 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002476 SC_Extern,
2477 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002478}
2479
Steve Naroff09b266e2007-10-30 23:14:51 +00002480// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002481void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002482 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002483 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002484 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002485 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2486 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002487 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002488 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002489 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002490 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002491 SC_Extern,
2492 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002493}
2494
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002495// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2496void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2497 IdentifierInfo *getSuperClassIdent =
2498 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002499 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002500 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002501 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2502 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002503 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002504 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002505 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002506 getSuperClassIdent,
2507 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002508 SC_Extern,
2509 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002510 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002511}
2512
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002513// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002514void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002515 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002516 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002517 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002518 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2519 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002520 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002521 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002522 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002523 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002524 SC_Extern,
2525 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002526}
2527
Steve Naroffb29b4272008-04-14 22:03:09 +00002528Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002529 QualType strType = getConstantStringStructType();
2530
2531 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002532
2533 std::string tmpName = InFileName;
2534 unsigned i;
2535 for (i=0; i < tmpName.length(); i++) {
2536 char c = tmpName.at(i);
2537 // replace any non alphanumeric characters with '_'.
2538 if (!isalpha(c) && (c < '0' || c > '9'))
2539 tmpName[i] = '_';
2540 }
2541 S += tmpName;
2542 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002543 S += utostr(NumObjCStringLiterals++);
2544
Steve Naroffba92b2e2008-03-27 22:29:16 +00002545 Preamble += "static __NSConstantStringImpl " + S;
2546 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2547 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002548 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002549 std::string prettyBufS;
2550 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002551 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2552 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002553 Preamble += prettyBuf.str();
2554 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002555 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002556
2557 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 SourceLocation(), &Context->Idents.get(S),
2559 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002560 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002561 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002562 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002563 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002564 VK_RValue, OK_Ordinary,
2565 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002566 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002567 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002568 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002569 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002570 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002571 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002572}
2573
Steve Naroff874e2322007-11-15 10:28:18 +00002574// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002575QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002576 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002577 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002578 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002579 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002580 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Steve Naroff874e2322007-11-15 10:28:18 +00002582 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002583 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002584 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002585 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002586
Steve Naroff874e2322007-11-15 10:28:18 +00002587 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002588 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002589 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002590 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002591 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002592 FieldTypes[i], 0,
2593 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002594 /*Mutable=*/false,
2595 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002596 }
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Douglas Gregor838db382010-02-11 01:19:42 +00002598 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002599 }
2600 return Context->getTagDeclType(SuperStructDecl);
2601}
2602
Steve Naroffb29b4272008-04-14 22:03:09 +00002603QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002604 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002605 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002606 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002607 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002608 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002609
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002610 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002611 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002613 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002614 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002615 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002617 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002618
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002619 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002620 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002621 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2622 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002623 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002624 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002625 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002626 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002627 /*Mutable=*/true,
2628 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002629 }
2630
Douglas Gregor838db382010-02-11 01:19:42 +00002631 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002632 }
2633 return Context->getTagDeclType(ConstantStringDecl);
2634}
2635
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002636Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2637 SourceLocation StartLoc,
2638 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002639 if (!SelGetUidFunctionDecl)
2640 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002641 if (!MsgSendFunctionDecl)
2642 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002643 if (!MsgSendSuperFunctionDecl)
2644 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002645 if (!MsgSendStretFunctionDecl)
2646 SynthMsgSendStretFunctionDecl();
2647 if (!MsgSendSuperStretFunctionDecl)
2648 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002649 if (!MsgSendFpretFunctionDecl)
2650 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002651 if (!GetClassFunctionDecl)
2652 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002653 if (!GetSuperClassFunctionDecl)
2654 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002655 if (!GetMetaClassFunctionDecl)
2656 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Steve Naroff874e2322007-11-15 10:28:18 +00002658 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002659 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2660 // May need to use objc_msgSend_stret() as well.
2661 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002662 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2663 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002664 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002665 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002666 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002667 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002668 }
Mike Stump1eb44332009-09-09 15:08:12 +00002669
Steve Naroff934f2762007-10-24 22:48:43 +00002670 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002671 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002672 switch (Exp->getReceiverKind()) {
2673 case ObjCMessageExpr::SuperClass: {
2674 MsgSendFlavor = MsgSendSuperFunctionDecl;
2675 if (MsgSendStretFlavor)
2676 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2677 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Douglas Gregor04badcf2010-04-21 00:45:42 +00002679 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002680
Chris Lattner5f9e2722011-07-23 10:55:15 +00002681 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002682
Douglas Gregor04badcf2010-04-21 00:45:42 +00002683 // set the receiver to self, the first argument to all methods.
2684 InitExprs.push_back(
2685 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002686 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002687 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002688 false,
John McCallf89e55a2010-11-18 06:31:45 +00002689 Context->getObjCIdType(),
2690 VK_RValue,
2691 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002692 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Douglas Gregor04badcf2010-04-21 00:45:42 +00002694 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002695 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002696 QualType argType = Context->getPointerType(Context->CharTy);
2697 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002698 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002699 StringLiteral::Ascii, false,
2700 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002701 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2702 &ClsExprs[0],
2703 ClsExprs.size(),
2704 StartLoc,
2705 EndLoc);
2706 // (Class)objc_getClass("CurrentClass")
2707 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2708 Context->getObjCClassType(),
Fariborz Jahanian97bbab22011-12-21 19:48:07 +00002709 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002710 ClsExprs.clear();
2711 ClsExprs.push_back(ArgExpr);
2712 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2713 &ClsExprs[0], ClsExprs.size(),
2714 StartLoc, EndLoc);
2715
2716 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2717 // To turn off a warning, type-cast to 'id'
2718 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2719 NoTypeInfoCStyleCastExpr(Context,
2720 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002721 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002722 // struct objc_super
2723 QualType superType = getSuperStructType();
2724 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002725
Francois Pichet62ec1f22011-09-17 17:15:52 +00002726 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002727 SynthSuperContructorFunctionDecl();
2728 // Simulate a contructor call...
2729 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002730 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002731 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2733 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002734 superType, VK_LValue,
2735 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002736 // The code for super is a little tricky to prevent collision with
2737 // the structure definition in the header. The rewriter has it's own
2738 // internal definition (__rw_objc_super) that is uses. This is why
2739 // we need the cast below. For example:
2740 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2741 //
John McCall2de56d12010-08-25 11:45:40 +00002742 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002743 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002744 VK_RValue, OK_Ordinary,
2745 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002746 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2747 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002748 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002749 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002750 // (struct objc_super) { <exprs from above> }
2751 InitListExpr *ILE =
2752 new (Context) InitListExpr(*Context, SourceLocation(),
2753 &InitExprs[0], InitExprs.size(),
2754 SourceLocation());
2755 TypeSourceInfo *superTInfo
2756 = Context->getTrivialTypeSourceInfo(superType);
2757 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002758 superType, VK_LValue,
2759 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002760 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002761 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002762 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002763 VK_RValue, OK_Ordinary,
2764 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002765 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002766 MsgExprs.push_back(SuperRep);
2767 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002768 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002769
2770 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002771 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002772 QualType argType = Context->getPointerType(Context->CharTy);
2773 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002774 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002775 IdentifierInfo *clsName = Class->getIdentifier();
2776 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002777 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002778 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002779 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002780 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2781 &ClsExprs[0],
2782 ClsExprs.size(),
2783 StartLoc, EndLoc);
2784 MsgExprs.push_back(Cls);
2785 break;
2786 }
2787
2788 case ObjCMessageExpr::SuperInstance:{
2789 MsgSendFlavor = MsgSendSuperFunctionDecl;
2790 if (MsgSendStretFlavor)
2791 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2792 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2793 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002794 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002795
2796 InitExprs.push_back(
2797 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002798 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002799 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002800 false,
John McCallf89e55a2010-11-18 06:31:45 +00002801 Context->getObjCIdType(),
2802 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002803 ); // set the 'receiver'.
2804
2805 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002806 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002807 QualType argType = Context->getPointerType(Context->CharTy);
2808 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002809 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002810 StringLiteral::Ascii, false, argType,
2811 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2813 &ClsExprs[0],
2814 ClsExprs.size(),
2815 StartLoc, EndLoc);
2816 // (Class)objc_getClass("CurrentClass")
2817 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2818 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002819 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 ClsExprs.clear();
2821 ClsExprs.push_back(ArgExpr);
2822 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2823 &ClsExprs[0], ClsExprs.size(),
2824 StartLoc, EndLoc);
2825
2826 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2827 // To turn off a warning, type-cast to 'id'
2828 InitExprs.push_back(
2829 // set 'super class', using class_getSuperclass().
2830 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002831 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002832 // struct objc_super
2833 QualType superType = getSuperStructType();
2834 Expr *SuperRep;
2835
Francois Pichet62ec1f22011-09-17 17:15:52 +00002836 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 SynthSuperContructorFunctionDecl();
2838 // Simulate a contructor call...
2839 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002840 false, superType, VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00002841 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002842 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2843 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002844 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 // The code for super is a little tricky to prevent collision with
2846 // the structure definition in the header. The rewriter has it's own
2847 // internal definition (__rw_objc_super) that is uses. This is why
2848 // we need the cast below. For example:
2849 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2850 //
John McCall2de56d12010-08-25 11:45:40 +00002851 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002853 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002854 SourceLocation());
2855 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2856 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002857 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002858 } else {
2859 // (struct objc_super) { <exprs from above> }
2860 InitListExpr *ILE =
2861 new (Context) InitListExpr(*Context, SourceLocation(),
2862 &InitExprs[0], InitExprs.size(),
2863 SourceLocation());
2864 TypeSourceInfo *superTInfo
2865 = Context->getTrivialTypeSourceInfo(superType);
2866 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002867 superType, VK_RValue, ILE,
2868 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002869 }
2870 MsgExprs.push_back(SuperRep);
2871 break;
2872 }
2873
2874 case ObjCMessageExpr::Instance: {
2875 // Remove all type-casts because it may contain objc-style types; e.g.
2876 // Foo<Proto> *.
2877 Expr *recExpr = Exp->getInstanceReceiver();
2878 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2879 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002880 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2881 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2882 ? CK_BlockPointerToObjCPointerCast
2883 : CK_CPointerToObjCPointerCast;
2884
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002886 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002887 MsgExprs.push_back(recExpr);
2888 break;
2889 }
2890 }
2891
Steve Naroffbeaf2992007-11-03 11:27:19 +00002892 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002893 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002894 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002895 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002896 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002897 StringLiteral::Ascii, false,
2898 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002899 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002900 &SelExprs[0], SelExprs.size(),
2901 StartLoc,
2902 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002903 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002904
Steve Naroff934f2762007-10-24 22:48:43 +00002905 // Now push any user supplied arguments.
2906 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002907 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002908 // Make all implicit casts explicit...ICE comes in handy:-)
2909 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2910 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002911 QualType type = ICE->getType();
2912 if (needToScanForQualifiers(type))
2913 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002914 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002915 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002916 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002917 CastKind CK;
2918 if (SubExpr->getType()->isIntegralType(*Context) &&
2919 type->isBooleanType()) {
2920 CK = CK_IntegralToBoolean;
2921 } else if (type->isObjCObjectPointerType()) {
2922 if (SubExpr->getType()->isBlockPointerType()) {
2923 CK = CK_BlockPointerToObjCPointerCast;
2924 } else if (SubExpr->getType()->isPointerType()) {
2925 CK = CK_CPointerToObjCPointerCast;
2926 } else {
2927 CK = CK_BitCast;
2928 }
2929 } else {
2930 CK = CK_BitCast;
2931 }
2932
2933 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002934 }
2935 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002936 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002937 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002938 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002939 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002940 CastKind CK;
2941 if (userExpr->getType()->isIntegralType(*Context)) {
2942 CK = CK_IntegralToPointer;
2943 } else if (userExpr->getType()->isBlockPointerType()) {
2944 CK = CK_BlockPointerToObjCPointerCast;
2945 } else if (userExpr->getType()->isPointerType()) {
2946 CK = CK_CPointerToObjCPointerCast;
2947 } else {
2948 CK = CK_BitCast;
2949 }
John McCall9d125032010-01-15 18:39:57 +00002950 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002951 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002952 }
Mike Stump1eb44332009-09-09 15:08:12 +00002953 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002954 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002955 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2956 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002957 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002958 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002959 }
Steve Naroffab972d32007-11-04 22:37:50 +00002960 // Generate the funky cast.
2961 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002962 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002963 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002964
Steve Naroffab972d32007-11-04 22:37:50 +00002965 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002966 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2967 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2968 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002969 ArgTypes.push_back(Context->getObjCIdType());
2970 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002971 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002972 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002973 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2974 E = OMD->param_end(); PI != E; ++PI) {
2975 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002976 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002977 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002978 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002979 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002980 ArgTypes.push_back(t);
2981 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002982 returnType = Exp->getType();
2983 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002984 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002985 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002986 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002987 }
2988 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002989 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Steve Naroffab972d32007-11-04 22:37:50 +00002991 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002992 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002993 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002994
Mike Stump1eb44332009-09-09 15:08:12 +00002995 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002996 // If we don't do this cast, we get the following bizarre warning/note:
2997 // xx.m:13: warning: function called through a non-compatible type
2998 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002999 cast = NoTypeInfoCStyleCastExpr(Context,
3000 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003001 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Steve Naroffab972d32007-11-04 22:37:50 +00003003 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003004 QualType castType =
3005 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3006 // If we don't have a method decl, force a variadic cast.
3007 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003008 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003009 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003010 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003011
3012 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003013 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003014
John McCall183700f2009-09-21 23:43:11 +00003015 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003016 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003017 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003018 FT->getResultType(), VK_RValue,
3019 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003020 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003021 if (MsgSendStretFlavor) {
3022 // We have the method which returns a struct/union. Must also generate
3023 // call to objc_msgSend_stret and hang both varieties on a conditional
3024 // expression which dictate which one to envoke depending on size of
3025 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003027 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003028 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3029 false, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003030 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003031 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003032 cast = NoTypeInfoCStyleCastExpr(Context,
3033 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003034 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003035 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003036 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3037 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003038 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003039 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003040 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003042 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003043 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003044
John McCall183700f2009-09-21 23:43:11 +00003045 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003046 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003047 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003048 FT->getResultType(), VK_RValue,
3049 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003050
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003051 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003052 UnaryExprOrTypeTraitExpr *sizeofExpr =
3053 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3054 Context->getTrivialTypeSourceInfo(returnType),
3055 Context->getSizeType(), SourceLocation(),
3056 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003057 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3058 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3059 // For X86 it is more complicated and some kind of target specific routine
3060 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003061 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003062 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003063 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3064 llvm::APInt(IntSize, 8),
3065 Context->IntTy,
3066 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003067 BinaryOperator *lessThanExpr =
3068 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3069 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003070 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003071 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003072 new (Context) ConditionalOperator(lessThanExpr,
3073 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003074 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003075 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003076 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3077 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003078 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003079 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003080 return ReplacingStmt;
3081}
3082
Steve Naroffb29b4272008-04-14 22:03:09 +00003083Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003084 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3085 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003086
Steve Naroff934f2762007-10-24 22:48:43 +00003087 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003088 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003090 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003091 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003092}
3093
Steve Naroff621edce2009-04-29 16:37:50 +00003094// typedef struct objc_object Protocol;
3095QualType RewriteObjC::getProtocolType() {
3096 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003097 TypeSourceInfo *TInfo
3098 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003099 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003100 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003101 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003102 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003103 }
3104 return Context->getTypeDeclType(ProtocolTypeDecl);
3105}
3106
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003107/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003108/// a synthesized/forward data reference (to the protocol's metadata).
3109/// The forward references (and metadata) are generated in
3110/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003111Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003112 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3113 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003114 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003115 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003116 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003117 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3118 VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003119 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003120 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003121 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003122 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003123 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003124 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003125 ReplaceStmt(Exp, castExpr);
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00003126 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003127 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003128 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003129
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003130}
3131
Mike Stump1eb44332009-09-09 15:08:12 +00003132bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003133 const char *endBuf) {
3134 while (startBuf < endBuf) {
3135 if (*startBuf == '#') {
3136 // Skip whitespace.
3137 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3138 ;
3139 if (!strncmp(startBuf, "if", strlen("if")) ||
3140 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3141 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3142 !strncmp(startBuf, "define", strlen("define")) ||
3143 !strncmp(startBuf, "undef", strlen("undef")) ||
3144 !strncmp(startBuf, "else", strlen("else")) ||
3145 !strncmp(startBuf, "elif", strlen("elif")) ||
3146 !strncmp(startBuf, "endif", strlen("endif")) ||
3147 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3148 !strncmp(startBuf, "include", strlen("include")) ||
3149 !strncmp(startBuf, "import", strlen("import")) ||
3150 !strncmp(startBuf, "include_next", strlen("include_next")))
3151 return true;
3152 }
3153 startBuf++;
3154 }
3155 return false;
3156}
3157
Fariborz Jahanian58457172011-12-05 18:43:13 +00003158/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003159/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003160void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003161 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003162 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003163 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003164 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003165 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003166 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003167 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003168 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003169 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003170 SourceLocation LocStart = CDecl->getLocStart();
Douglas Gregor05c272f2011-12-15 22:34:59 +00003171 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Steve Narofffea763e82007-11-14 19:25:57 +00003173 const char *startBuf = SM->getCharacterData(LocStart);
3174 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003175
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003176 // If no ivars and no root or if its root, directly or indirectly,
3177 // have no ivars (thus not synthesized) then no need to synthesize this class.
Douglas Gregor7723fec2011-12-15 20:29:51 +00003178 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003179 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003180 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003181 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003182 return;
3183 }
Mike Stump1eb44332009-09-09 15:08:12 +00003184
3185 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003186 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003187 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003188 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003189 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003190 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003191
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003192 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003193 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003194 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003195 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003196 // If the buffer contains preprocessor directives, we do more fine-grained
3197 // rewrites. This is intended to fix code that looks like (which occurs in
3198 // NSURL.h, for example):
3199 //
3200 // #ifdef XYZ
3201 // @interface Foo : NSObject
3202 // #else
3203 // @interface FooBar : NSObject
3204 // #endif
3205 // {
3206 // int i;
3207 // }
3208 // @end
3209 //
3210 // This clause is segregated to avoid breaking the common case.
3211 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003212 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003213 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003214 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003215 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003216
Chris Lattnercafeb352009-02-20 18:18:36 +00003217 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003218 // advance to the end of the referenced protocols.
3219 while (endHeader < cursor && *endHeader != '>') endHeader++;
3220 endHeader++;
3221 }
3222 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003223 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003224 } else {
3225 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003226 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003227 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003228 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003229 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003230 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003231 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003232 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003233 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003234
Steve Narofffea763e82007-11-14 19:25:57 +00003235 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003236 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003237 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003238 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003239 }
3240 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003241
Steve Narofffea763e82007-11-14 19:25:57 +00003242 // Now comment out any visibility specifiers.
3243 while (cursor < endBuf) {
3244 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003245 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003246 // Skip whitespace.
3247 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3248 /*scan*/;
3249
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003250 // FIXME: presence of @public, etc. inside comment results in
3251 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003252 if (!strncmp(cursor, "public", strlen("public")) ||
3253 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003254 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003255 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003256 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003257 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003258 // FIXME: If there are cases where '<' is used in ivar declaration part
3259 // of user code, then scan the ivar list and use needToScanForQualifiers
3260 // for type checking.
3261 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003262 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003263 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003264 cursor = strchr(cursor, '>');
3265 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003266 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003267 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003268 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003269 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003270 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003271 }
Steve Narofffea763e82007-11-14 19:25:57 +00003272 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003273 }
Steve Narofffea763e82007-11-14 19:25:57 +00003274 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003275 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003276 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003277 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003278 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003279 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003280 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003281 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003282 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003283 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003284 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003285 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003286 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003287 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003288}
3289
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003290//===----------------------------------------------------------------------===//
3291// Meta Data Emission
3292//===----------------------------------------------------------------------===//
3293
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003294
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003295/// RewriteImplementations - This routine rewrites all method implementations
3296/// and emits meta-data.
3297
Steve Narofface66252008-11-13 20:07:04 +00003298void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003299 int ClsDefCount = ClassImplementation.size();
3300 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003302 // Rewrite implemented methods
3303 for (int i = 0; i < ClsDefCount; i++)
3304 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003305
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003306 for (int i = 0; i < CatDefCount; i++)
3307 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003308}
Mike Stump1eb44332009-09-09 15:08:12 +00003309
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003310void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3311 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003312 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003313 assert(BlockByRefDeclNo.count(VD) &&
3314 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003315 if (def)
3316 ResultStr += "struct ";
3317 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003318 "_" + utostr(BlockByRefDeclNo[VD]) ;
3319}
3320
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003321static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3322 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3323 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3324 return false;
3325}
3326
Steve Naroff54055232008-10-27 17:20:55 +00003327std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003328 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003329 std::string Tag) {
3330 const FunctionType *AFT = CE->getFunctionType();
3331 QualType RT = AFT->getResultType();
3332 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003333 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003334 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003335
Steve Naroff54055232008-10-27 17:20:55 +00003336 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003337
Douglas Gregor72564e72009-02-26 23:50:07 +00003338 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003339 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003340 // block (to reference imported block decl refs).
3341 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003342 } else if (BD->param_empty()) {
3343 S += "(" + StructRef + " *__cself)";
3344 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003345 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003346 assert(FT && "SynthesizeBlockFunc: No function proto");
3347 S += '(';
3348 // first add the implicit argument.
3349 S += StructRef + " *__cself, ";
3350 std::string ParamStr;
3351 for (BlockDecl::param_iterator AI = BD->param_begin(),
3352 E = BD->param_end(); AI != E; ++AI) {
3353 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003354 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003355 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003356 (void)convertBlockPointerToFunctionPointer(QT);
3357 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003358 S += ParamStr;
3359 }
3360 if (FT->isVariadic()) {
3361 if (!BD->param_empty()) S += ", ";
3362 S += "...";
3363 }
3364 S += ')';
3365 }
3366 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Steve Naroff54055232008-10-27 17:20:55 +00003368 // Create local declarations to avoid rewriting all closure decl ref exprs.
3369 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003370 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003371 E = BlockByRefDecls.end(); I != E; ++I) {
3372 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003373 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003374 std::string TypeString;
3375 RewriteByRefString(TypeString, Name, (*I));
3376 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003377 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003378 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003379 }
Steve Naroff54055232008-10-27 17:20:55 +00003380 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003381 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003382 E = BlockByCopyDecls.end(); I != E; ++I) {
3383 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003384 // Handle nested closure invocation. For example:
3385 //
3386 // void (^myImportedClosure)(void);
3387 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003388 //
Steve Naroff54055232008-10-27 17:20:55 +00003389 // void (^anotherClosure)(void);
3390 // anotherClosure = ^(void) {
3391 // myImportedClosure(); // import and invoke the closure
3392 // };
3393 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003394 if (isTopLevelBlockPointerType((*I)->getType())) {
3395 RewriteBlockPointerTypeVariable(S, (*I));
3396 S += " = (";
3397 RewriteBlockPointerType(S, (*I)->getType());
3398 S += ")";
3399 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3400 }
3401 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003402 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003403 QualType QT = (*I)->getType();
3404 if (HasLocalVariableExternalStorage(*I))
3405 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003406 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003407 S += Name + " = __cself->" +
3408 (*I)->getNameAsString() + "; // bound by copy\n";
3409 }
Steve Naroff54055232008-10-27 17:20:55 +00003410 }
3411 std::string RewrittenStr = RewrittenBlockExprs[CE];
3412 const char *cstr = RewrittenStr.c_str();
3413 while (*cstr++ != '{') ;
3414 S += cstr;
3415 S += "\n";
3416 return S;
3417}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003418
Steve Naroff54055232008-10-27 17:20:55 +00003419std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003420 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003421 std::string Tag) {
3422 std::string StructRef = "struct " + Tag;
3423 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003424
Steve Naroff54055232008-10-27 17:20:55 +00003425 S += funcName;
3426 S += "_block_copy_" + utostr(i);
3427 S += "(" + StructRef;
3428 S += "*dst, " + StructRef;
3429 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003430 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003431 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003432 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003433 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003434 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003435 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003436 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003437 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003438 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003439 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003440 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003441 else
3442 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003443 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003444 S += "}\n";
3445
Steve Naroff54055232008-10-27 17:20:55 +00003446 S += "\nstatic void __";
3447 S += funcName;
3448 S += "_block_dispose_" + utostr(i);
3449 S += "(" + StructRef;
3450 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003451 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003452 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003453 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003454 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003455 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003456 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003457 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003458 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003459 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003460 else
3461 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003462 }
Mike Stump1eb44332009-09-09 15:08:12 +00003463 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003464 return S;
3465}
3466
Steve Naroff01aec112009-12-06 21:14:13 +00003467std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3468 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003469 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003470 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003471
Steve Naroff54055232008-10-27 17:20:55 +00003472 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003473 S += " struct " + Desc;
3474 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003475
Steve Naroff01aec112009-12-06 21:14:13 +00003476 Constructor += "(void *fp, "; // Invoke function pointer.
3477 Constructor += "struct " + Desc; // Descriptor pointer.
3478 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003479
Steve Naroff54055232008-10-27 17:20:55 +00003480 if (BlockDeclRefs.size()) {
3481 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003482 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003483 E = BlockByCopyDecls.end(); I != E; ++I) {
3484 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003485 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003486 std::string ArgName = "_" + FieldName;
3487 // Handle nested closure invocation. For example:
3488 //
3489 // void (^myImportedBlock)(void);
3490 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003491 //
Steve Naroff54055232008-10-27 17:20:55 +00003492 // void (^anotherBlock)(void);
3493 // anotherBlock = ^(void) {
3494 // myImportedBlock(); // import and invoke the closure
3495 // };
3496 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003497 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003498 S += "struct __block_impl *";
3499 Constructor += ", void *" + ArgName;
3500 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003501 QualType QT = (*I)->getType();
3502 if (HasLocalVariableExternalStorage(*I))
3503 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003504 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3505 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003506 Constructor += ", " + ArgName;
3507 }
3508 S += FieldName + ";\n";
3509 }
3510 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003511 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003512 E = BlockByRefDecls.end(); I != E; ++I) {
3513 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003514 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003515 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003516 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003517 std::string TypeString;
3518 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003519 TypeString += " *";
3520 FieldName = TypeString + FieldName;
3521 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003522 Constructor += ", " + ArgName;
3523 }
3524 S += FieldName + "; // by ref\n";
3525 }
3526 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003527 Constructor += ", int flags=0)";
3528 // Initialize all "by copy" arguments.
3529 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003530 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003531 E = BlockByCopyDecls.end(); I != E; ++I) {
3532 std::string Name = (*I)->getNameAsString();
3533 if (firsTime) {
3534 Constructor += " : ";
3535 firsTime = false;
3536 }
3537 else
3538 Constructor += ", ";
3539 if (isTopLevelBlockPointerType((*I)->getType()))
3540 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3541 else
3542 Constructor += Name + "(_" + Name + ")";
3543 }
3544 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003545 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003546 E = BlockByRefDecls.end(); I != E; ++I) {
3547 std::string Name = (*I)->getNameAsString();
3548 if (firsTime) {
3549 Constructor += " : ";
3550 firsTime = false;
3551 }
3552 else
3553 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003554 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003555 }
3556
3557 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003558 if (GlobalVarDecl)
3559 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3560 else
3561 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003562 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Steve Naroff01aec112009-12-06 21:14:13 +00003564 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003565 } else {
3566 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003567 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003568 if (GlobalVarDecl)
3569 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3570 else
3571 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003572 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3573 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003574 }
3575 Constructor += " ";
3576 Constructor += "}\n";
3577 S += Constructor;
3578 S += "};\n";
3579 return S;
3580}
3581
Steve Naroff01aec112009-12-06 21:14:13 +00003582std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3583 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003584 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003585 unsigned hasCopy) {
3586 std::string S = "\nstatic struct " + DescTag;
3587
3588 S += " {\n unsigned long reserved;\n";
3589 S += " unsigned long Block_size;\n";
3590 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003591 S += " void (*copy)(struct ";
3592 S += ImplTag; S += "*, struct ";
3593 S += ImplTag; S += "*);\n";
3594
3595 S += " void (*dispose)(struct ";
3596 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003597 }
3598 S += "} ";
3599
3600 S += DescTag + "_DATA = { 0, sizeof(struct ";
3601 S += ImplTag + ")";
3602 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003603 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3604 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003605 }
3606 S += "};\n";
3607 return S;
3608}
3609
Steve Naroff54055232008-10-27 17:20:55 +00003610void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003611 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003612 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003613 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003614 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003615 bool RewriteSC = (GlobalVarDecl &&
3616 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003617 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003618 GlobalVarDecl->getType().getCVRQualifiers());
3619 if (RewriteSC) {
3620 std::string SC(" void __");
3621 SC += GlobalVarDecl->getNameAsString();
3622 SC += "() {}";
3623 InsertText(FunLocStart, SC);
3624 }
3625
Steve Naroff54055232008-10-27 17:20:55 +00003626 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003627 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3628 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003629 // Need to copy-in the inner copied-in variables not actually used in this
3630 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003631 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003632 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003633 ValueDecl *VD = Exp->getDecl();
3634 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003635 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003636 BlockByCopyDeclsPtrSet.insert(VD);
3637 BlockByCopyDecls.push_back(VD);
3638 }
John McCallf4b88a42012-03-10 09:33:50 +00003639 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003640 BlockByRefDeclsPtrSet.insert(VD);
3641 BlockByRefDecls.push_back(VD);
3642 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003643 // imported objects in the inner blocks not used in the outer
3644 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003645 if (VD->hasAttr<BlocksAttr>() ||
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003646 VD->getType()->isObjCObjectPointerType() ||
3647 VD->getType()->isBlockPointerType())
3648 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003649 }
Steve Naroff54055232008-10-27 17:20:55 +00003650
Daniel Dunbar4087f272010-08-17 22:39:59 +00003651 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3652 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Steve Naroff01aec112009-12-06 21:14:13 +00003654 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003655
Benjamin Kramerd999b372010-02-14 14:14:16 +00003656 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003657
Steve Naroff01aec112009-12-06 21:14:13 +00003658 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Benjamin Kramerd999b372010-02-14 14:14:16 +00003660 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003661
3662 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003663 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003664 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003665 }
Steve Naroff01aec112009-12-06 21:14:13 +00003666 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3667 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003668 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Steve Naroff54055232008-10-27 17:20:55 +00003670 BlockDeclRefs.clear();
3671 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003672 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003673 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003674 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003675 ImportedBlockDecls.clear();
3676 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003677 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003678 // Must insert any 'const/volatile/static here. Since it has been
3679 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003680 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003681 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003682 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003683 if (GlobalVarDecl->getType().isConstQualified())
3684 SC += "const ";
3685 if (GlobalVarDecl->getType().isVolatileQualified())
3686 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003687 if (GlobalVarDecl->getType().isRestrictQualified())
3688 SC += "restrict ";
3689 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003690 }
3691
Steve Naroff54055232008-10-27 17:20:55 +00003692 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003693 InnerDeclRefsCount.clear();
3694 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003695 RewrittenBlockExprs.clear();
3696}
3697
3698void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3699 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003700 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Steve Naroff54055232008-10-27 17:20:55 +00003702 SynthesizeBlockLiterals(FunLocStart, FuncName);
3703}
3704
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003705static void BuildUniqueMethodName(std::string &Name,
3706 ObjCMethodDecl *MD) {
3707 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003708 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003709 Name += "__" + MD->getSelector().getAsString();
3710 // Convert colons to underscores.
3711 std::string::size_type loc = 0;
3712 while ((loc = Name.find(":", loc)) != std::string::npos)
3713 Name.replace(loc, 1, "_");
3714}
3715
Steve Naroff54055232008-10-27 17:20:55 +00003716void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003717 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3718 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003719 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003720 std::string FuncName;
3721 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003722 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003723}
3724
3725void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003726 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003727 if (*CI) {
3728 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3729 GetBlockDeclRefExprs(CBE->getBody());
3730 else
3731 GetBlockDeclRefExprs(*CI);
3732 }
3733 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003734 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3735 if (DRE->refersToEnclosingLocal()) {
3736 // FIXME: Handle enums.
3737 if (!isa<FunctionDecl>(DRE->getDecl()))
3738 BlockDeclRefs.push_back(DRE);
3739 if (HasLocalVariableExternalStorage(DRE->getDecl()))
3740 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003741 }
John McCallf4b88a42012-03-10 09:33:50 +00003742 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003743
Steve Naroff54055232008-10-27 17:20:55 +00003744 return;
3745}
3746
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003747void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003748 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003749 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003750 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003751 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003752 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3753 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003754 GetInnerBlockDeclRefExprs(CBE->getBody(),
3755 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003756 InnerContexts);
3757 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003758 else
3759 GetInnerBlockDeclRefExprs(*CI,
3760 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003761 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003762
3763 }
3764 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3766 if (DRE->refersToEnclosingLocal()) {
3767 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3768 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3769 InnerBlockDeclRefs.push_back(DRE);
3770 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3771 if (Var->isFunctionOrMethodVarDecl())
3772 ImportedLocalExternalDecls.insert(Var);
3773 }
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003774 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003775
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003776 return;
3777}
3778
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003779/// convertFunctionTypeOfBlocks - This routine converts a function type
3780/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003781/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003782/// all block pointers to function pointers.
3783QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3784 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3785 // FTP will be null for closures that don't take arguments.
3786 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003787 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003788 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003789 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003790
3791 if (FTP) {
3792 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3793 E = FTP->arg_type_end(); I && (I != E); ++I) {
3794 QualType t = *I;
3795 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003796 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003797 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003798 ArgTypes.push_back(t);
3799 }
3800 }
3801 QualType FuncType;
3802 // FIXME. Does this work if block takes no argument but has a return type
3803 // which is of block type?
3804 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003805 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003806 else FuncType = QualType(FT, 0);
3807 return FuncType;
3808}
3809
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003810Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003811 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003812 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003813
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003814 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003815 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003816 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003817 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003818 }
3819 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3820 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3821 }
3822 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3823 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3824 else if (const ConditionalOperator *CEXPR =
3825 dyn_cast<ConditionalOperator>(BlockExp)) {
3826 Expr *LHSExp = CEXPR->getLHS();
3827 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3828 Expr *RHSExp = CEXPR->getRHS();
3829 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3830 Expr *CONDExp = CEXPR->getCond();
3831 ConditionalOperator *CondExpr =
3832 new (Context) ConditionalOperator(CONDExp,
3833 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003834 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003835 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003836 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003837 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3838 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003839 } else if (const PseudoObjectExpr *POE
3840 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3841 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003842 } else {
3843 assert(1 && "RewriteBlockClass: Bad type");
3844 }
3845 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003846 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003847 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003848 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003849 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003851 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003852 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003853 &Context->Idents.get("__block_impl"));
3854 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003855
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003856 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003857 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003859 // Push the block argument type.
3860 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003861 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003862 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003863 E = FTP->arg_type_end(); I && (I != E); ++I) {
3864 QualType t = *I;
3865 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003866 if (!convertBlockPointerToFunctionPointer(t))
3867 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003868 ArgTypes.push_back(t);
3869 }
Steve Naroff54055232008-10-27 17:20:55 +00003870 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003871 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003872 QualType PtrToFuncCastType
3873 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003874
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003875 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003876
John McCall9d125032010-01-15 18:39:57 +00003877 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003878 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003879 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003880 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003881 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3882 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003883 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Douglas Gregor44b43212008-12-11 16:49:14 +00003885 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003886 SourceLocation(),
3887 &Context->Idents.get("FuncPtr"),
3888 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003889 /*BitWidth=*/0, /*Mutable=*/true,
3890 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003891 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003892 FD->getType(), VK_LValue,
3893 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003895
John McCall9d125032010-01-15 18:39:57 +00003896 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003897 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003898 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003899
Chris Lattner5f9e2722011-07-23 10:55:15 +00003900 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003901 // Add the implicit argument.
3902 BlkExprs.push_back(BlkCast);
3903 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003904 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003905 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003906 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003907 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003908 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3909 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003910 Exp->getType(), VK_RValue,
3911 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003912 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003913}
3914
Steve Naroff621edce2009-04-29 16:37:50 +00003915// We need to return the rewritten expression to handle cases where the
3916// BlockDeclRefExpr is embedded in another expression being rewritten.
3917// For example:
3918//
3919// int main() {
3920// __block Foo *f;
3921// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003922//
Steve Naroff621edce2009-04-29 16:37:50 +00003923// void (^myblock)() = ^() {
3924// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3925// i = 77;
3926// };
3927//}
John McCallf4b88a42012-03-10 09:33:50 +00003928Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003929 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003930 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003931 ValueDecl *VD = DeclRefExp->getDecl();
3932 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003933
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003934 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003935 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003936 &Context->Idents.get("__forwarding"),
3937 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003938 /*BitWidth=*/0, /*Mutable=*/true,
3939 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003940 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3941 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003942 FD->getType(), VK_LValue,
3943 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003944
Chris Lattner5f9e2722011-07-23 10:55:15 +00003945 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003946 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003947 &Context->Idents.get(Name),
3948 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003949 /*BitWidth=*/0, /*Mutable=*/true,
3950 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003951 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003952 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003953
3954
3955
Steve Naroffdf8570d2009-02-02 17:19:26 +00003956 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003957 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3958 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003959 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003960 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003961 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003962}
3963
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003964// Rewrites the imported local variable V with external storage
3965// (static, extern, etc.) as *V
3966//
3967Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3968 ValueDecl *VD = DRE->getDecl();
3969 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3970 if (!ImportedLocalExternalDecls.count(Var))
3971 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003972 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3973 VK_LValue, OK_Ordinary,
3974 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003975 // Need parens to enforce precedence.
3976 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3977 Exp);
3978 ReplaceStmt(DRE, PE);
3979 return PE;
3980}
3981
Steve Naroffb2f9e512008-11-03 23:29:32 +00003982void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3983 SourceLocation LocStart = CE->getLParenLoc();
3984 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003985
3986 // Need to avoid trying to rewrite synthesized casts.
3987 if (LocStart.isInvalid())
3988 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003989 // Need to avoid trying to rewrite casts contained in macros.
3990 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3991 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Steve Naroff54055232008-10-27 17:20:55 +00003993 const char *startBuf = SM->getCharacterData(LocStart);
3994 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003995 QualType QT = CE->getType();
3996 const Type* TypePtr = QT->getAs<Type>();
3997 if (isa<TypeOfExprType>(TypePtr)) {
3998 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3999 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4000 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004001 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004002 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004003 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004004 return;
4005 }
Steve Naroff54055232008-10-27 17:20:55 +00004006 // advance the location to startArgList.
4007 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Steve Naroff54055232008-10-27 17:20:55 +00004009 while (*argPtr++ && (argPtr < endBuf)) {
4010 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004011 case '^':
4012 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004013 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004014 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004015 break;
Steve Naroff54055232008-10-27 17:20:55 +00004016 }
4017 }
4018 return;
4019}
4020
4021void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4022 SourceLocation DeclLoc = FD->getLocation();
4023 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Steve Naroff54055232008-10-27 17:20:55 +00004025 // We have 1 or more arguments that have closure pointers.
4026 const char *startBuf = SM->getCharacterData(DeclLoc);
4027 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Steve Naroff54055232008-10-27 17:20:55 +00004029 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Steve Naroff54055232008-10-27 17:20:55 +00004031 parenCount++;
4032 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004033 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004034 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004035
Steve Naroff54055232008-10-27 17:20:55 +00004036 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Steve Naroff54055232008-10-27 17:20:55 +00004038 while (*argPtr++ && parenCount) {
4039 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004040 case '^':
4041 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004042 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004043 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004044 break;
4045 case '(':
4046 parenCount++;
4047 break;
4048 case ')':
4049 parenCount--;
4050 break;
Steve Naroff54055232008-10-27 17:20:55 +00004051 }
4052 }
4053 return;
4054}
4055
4056bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004057 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004058 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004059 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004060 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004061 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004062 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004063 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004064 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004065 }
4066 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004067 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004068 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004069 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004070 return true;
4071 }
4072 return false;
4073}
4074
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004075bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4076 const FunctionProtoType *FTP;
4077 const PointerType *PT = QT->getAs<PointerType>();
4078 if (PT) {
4079 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4080 } else {
4081 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4082 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4083 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4084 }
4085 if (FTP) {
4086 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004087 E = FTP->arg_type_end(); I != E; ++I) {
4088 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004089 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004090 if ((*I)->isObjCObjectPointerType() &&
4091 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4092 return true;
4093 }
4094
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004095 }
4096 return false;
4097}
4098
Ted Kremenek8189cde2009-02-07 01:47:29 +00004099void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4100 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004101 const char *argPtr = strchr(Name, '(');
4102 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004103
Steve Naroff54055232008-10-27 17:20:55 +00004104 LParen = argPtr; // output the start.
4105 argPtr++; // skip past the left paren.
4106 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Steve Naroff54055232008-10-27 17:20:55 +00004108 while (*argPtr && parenCount) {
4109 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004110 case '(': parenCount++; break;
4111 case ')': parenCount--; break;
4112 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004113 }
4114 if (parenCount) argPtr++;
4115 }
4116 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4117 RParen = argPtr; // output the end
4118}
4119
4120void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4122 RewriteBlockPointerFunctionArgs(FD);
4123 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004124 }
Steve Naroff54055232008-10-27 17:20:55 +00004125 // Handle Variables and Typedefs.
4126 SourceLocation DeclLoc = ND->getLocation();
4127 QualType DeclT;
4128 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4129 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004130 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004131 DeclT = TDD->getUnderlyingType();
4132 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4133 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004134 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004135 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004136
Steve Naroff54055232008-10-27 17:20:55 +00004137 const char *startBuf = SM->getCharacterData(DeclLoc);
4138 const char *endBuf = startBuf;
4139 // scan backward (from the decl location) for the end of the previous decl.
4140 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4141 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004142 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004143 std::string buf;
4144 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004145 // *startBuf != '^' if we are dealing with a pointer to function that
4146 // may take block argument types (which will be handled below).
4147 if (*startBuf == '^') {
4148 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004149 buf = '*';
4150 startBuf++;
4151 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004152 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004153 while (*startBuf != ')') {
4154 buf += *startBuf;
4155 startBuf++;
4156 OrigLength++;
4157 }
4158 buf += ')';
4159 OrigLength++;
4160
4161 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4162 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004163 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004164 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004165 DeclLoc = ND->getLocation();
4166 startBuf = SM->getCharacterData(DeclLoc);
4167 const char *argListBegin, *argListEnd;
4168 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4169 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004170 if (*argListBegin == '^')
4171 buf += '*';
4172 else if (*argListBegin == '<') {
4173 buf += "/*";
4174 buf += *argListBegin++;
4175 OrigLength++;;
4176 while (*argListBegin != '>') {
4177 buf += *argListBegin++;
4178 OrigLength++;
4179 }
4180 buf += *argListBegin;
4181 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004182 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004183 else
4184 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004185 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004186 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004187 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004188 buf += ')';
4189 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004190 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004191 ReplaceText(Start, OrigLength, buf);
4192
Steve Naroff54055232008-10-27 17:20:55 +00004193 return;
4194}
4195
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004196
4197/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4198/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4199/// struct Block_byref_id_object *src) {
4200/// _Block_object_assign (&_dest->object, _src->object,
4201/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4202/// [|BLOCK_FIELD_IS_WEAK]) // object
4203/// _Block_object_assign(&_dest->object, _src->object,
4204/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4205/// [|BLOCK_FIELD_IS_WEAK]) // block
4206/// }
4207/// And:
4208/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4209/// _Block_object_dispose(_src->object,
4210/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4211/// [|BLOCK_FIELD_IS_WEAK]) // object
4212/// _Block_object_dispose(_src->object,
4213/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4214/// [|BLOCK_FIELD_IS_WEAK]) // block
4215/// }
4216
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004217std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4218 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004219 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004220 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004221 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004222 CopyDestroyCache.insert(flag);
4223 S = "static void __Block_byref_id_object_copy_";
4224 S += utostr(flag);
4225 S += "(void *dst, void *src) {\n";
4226
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004227 // offset into the object pointer is computed as:
4228 // void * + void* + int + int + void* + void *
4229 unsigned IntSize =
4230 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4231 unsigned VoidPtrSize =
4232 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4233
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004234 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004235 S += " _Block_object_assign((char*)dst + ";
4236 S += utostr(offset);
4237 S += ", *(void * *) ((char*)src + ";
4238 S += utostr(offset);
4239 S += "), ";
4240 S += utostr(flag);
4241 S += ");\n}\n";
4242
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004243 S += "static void __Block_byref_id_object_dispose_";
4244 S += utostr(flag);
4245 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004246 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4247 S += utostr(offset);
4248 S += "), ";
4249 S += utostr(flag);
4250 S += ");\n}\n";
4251 return S;
4252}
4253
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004254/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4255/// the declaration into:
4256/// struct __Block_byref_ND {
4257/// void *__isa; // NULL for everything except __weak pointers
4258/// struct __Block_byref_ND *__forwarding;
4259/// int32_t __flags;
4260/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004261/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4262/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004263/// typex ND;
4264/// };
4265///
4266/// It then replaces declaration of ND variable with:
4267/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4268/// __size=sizeof(struct __Block_byref_ND),
4269/// ND=initializer-if-any};
4270///
4271///
4272void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004273 // Insert declaration for the function in which block literal is
4274 // used.
4275 if (CurFunctionDeclToDeclareForBlock)
4276 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004277 int flag = 0;
4278 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004279 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004280 if (DeclLoc.isInvalid())
4281 // If type location is missing, it is because of missing type (a warning).
4282 // Use variable's location which is good for this case.
4283 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004284 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004285 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004286 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004287 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004288 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004289 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004290 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004291 ByrefType += " {\n";
4292 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004293 RewriteByRefString(ByrefType, Name, ND);
4294 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004295 ByrefType += " int __flags;\n";
4296 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004297 // Add void *__Block_byref_id_object_copy;
4298 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004299 QualType Ty = ND->getType();
4300 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4301 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004302 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4303 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004304 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004305
4306 QualType T = Ty;
4307 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004308 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004309
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004310 ByrefType += " " + Name + ";\n";
4311 ByrefType += "};\n";
4312 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004313 SourceLocation FunLocStart;
4314 if (CurFunctionDef)
4315 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4316 else {
4317 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4318 FunLocStart = CurMethodDef->getLocStart();
4319 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004320 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004321 if (Ty.isObjCGCWeak()) {
4322 flag |= BLOCK_FIELD_IS_WEAK;
4323 isa = 1;
4324 }
4325
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004326 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004327 flag = BLOCK_BYREF_CALLER;
4328 QualType Ty = ND->getType();
4329 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4330 if (Ty->isBlockPointerType())
4331 flag |= BLOCK_FIELD_IS_BLOCK;
4332 else
4333 flag |= BLOCK_FIELD_IS_OBJECT;
4334 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004335 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004336 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004337 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004338
4339 // struct __Block_byref_ND ND =
4340 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4341 // initializer-if-any};
4342 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004343 unsigned flags = 0;
4344 if (HasCopyAndDispose)
4345 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004346 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004347 ByrefType.clear();
4348 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004349 std::string ForwardingCastType("(");
4350 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004351 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004352 ByrefType += " " + Name + " = {(void*)";
4353 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004354 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004355 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004356 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004357 ByrefType += "sizeof(";
4358 RewriteByRefString(ByrefType, Name, ND);
4359 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004360 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004361 ByrefType += ", __Block_byref_id_object_copy_";
4362 ByrefType += utostr(flag);
4363 ByrefType += ", __Block_byref_id_object_dispose_";
4364 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004365 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004366 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004367 unsigned nameSize = Name.size();
4368 // for block or function pointer declaration. Name is aleady
4369 // part of the declaration.
4370 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4371 nameSize = 1;
4372 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004373 }
4374 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004375 SourceLocation startLoc;
4376 Expr *E = ND->getInit();
4377 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4378 startLoc = ECE->getLParenLoc();
4379 else
4380 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004381 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004382 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004383 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004384 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004385 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004386 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004387 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004388 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004389 ByrefType += "sizeof(";
4390 RewriteByRefString(ByrefType, Name, ND);
4391 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004392 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004393 ByrefType += "__Block_byref_id_object_copy_";
4394 ByrefType += utostr(flag);
4395 ByrefType += ", __Block_byref_id_object_dispose_";
4396 ByrefType += utostr(flag);
4397 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004398 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004399 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004400
4401 // Complete the newly synthesized compound expression by inserting a right
4402 // curly brace before the end of the declaration.
4403 // FIXME: This approach avoids rewriting the initializer expression. It
4404 // also assumes there is only one declarator. For example, the following
4405 // isn't currently supported by this routine (in general):
4406 //
4407 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4408 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004409 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4410 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004411 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4412 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004413 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004414
Benjamin Kramerd999b372010-02-14 14:14:16 +00004415 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004416 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004417 return;
4418}
4419
Mike Stump1eb44332009-09-09 15:08:12 +00004420void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004421 // Add initializers for any closure decl refs.
4422 GetBlockDeclRefExprs(Exp->getBody());
4423 if (BlockDeclRefs.size()) {
4424 // Unique all "by copy" declarations.
4425 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004426 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004427 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4428 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4429 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4430 }
4431 }
Steve Naroff54055232008-10-27 17:20:55 +00004432 // Unique all "by ref" declarations.
4433 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004434 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004435 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4436 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4437 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4438 }
Steve Naroff54055232008-10-27 17:20:55 +00004439 }
4440 // Find any imported blocks...they will need special attention.
4441 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004442 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004443 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004444 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004445 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004446 }
4447}
4448
Chris Lattner5f9e2722011-07-23 10:55:15 +00004449FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004450 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004451 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004452 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4453 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004454 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004455}
4456
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004457Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004458 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004459 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004460 Blocks.push_back(Exp);
4461
4462 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004463
4464 // Add inner imported variables now used in current block.
4465 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004466 if (!InnerBlockDeclRefs.empty()) {
4467 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004468 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004469 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004470 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004471 // We need to save the copied-in variables in nested
4472 // blocks because it is needed at the end for some of the API generations.
4473 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004474 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4475 BlockDeclRefs.push_back(Exp);
4476 BlockByCopyDeclsPtrSet.insert(VD);
4477 BlockByCopyDecls.push_back(VD);
4478 }
John McCallf4b88a42012-03-10 09:33:50 +00004479 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004480 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4481 BlockDeclRefs.push_back(Exp);
4482 BlockByRefDeclsPtrSet.insert(VD);
4483 BlockByRefDecls.push_back(VD);
4484 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004485 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004486 // Find any imported blocks...they will need special attention.
4487 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004488 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004489 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4490 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4491 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004492 }
4493 InnerDeclRefsCount.push_back(countOfInnerDecls);
4494
Steve Narofffa15fd92008-10-28 20:29:00 +00004495 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004496
Steve Narofffa15fd92008-10-28 20:29:00 +00004497 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004498 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004499 else if (CurMethodDef)
4500 BuildUniqueMethodName(FuncName, CurMethodDef);
4501 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004502 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Steve Narofffa15fd92008-10-28 20:29:00 +00004504 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Steve Narofffa15fd92008-10-28 20:29:00 +00004506 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4507 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004508
Steve Narofffa15fd92008-10-28 20:29:00 +00004509 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004510 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4511 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004512
4513 FunctionDecl *FD;
4514 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004515
Steve Narofffa15fd92008-10-28 20:29:00 +00004516 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004517 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004518 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
John McCallf89e55a2010-11-18 06:31:45 +00004519 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004520
Chris Lattner5f9e2722011-07-23 10:55:15 +00004521 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004522
Steve Narofffdc03722008-10-29 21:23:59 +00004523 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004524 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004525 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4526 VK_LValue, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004527 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004528 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004529 InitExprs.push_back(castExpr);
4530
Steve Naroff01aec112009-12-06 21:14:13 +00004531 // Initialize the block descriptor.
4532 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004534 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4535 SourceLocation(), SourceLocation(),
4536 &Context->Idents.get(DescData.c_str()),
4537 Context->VoidPtrTy, 0,
4538 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004539 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004540 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
John McCallf89e55a2010-11-18 06:31:45 +00004541 Context->VoidPtrTy,
4542 VK_LValue,
4543 SourceLocation()),
4544 UO_AddrOf,
4545 Context->getPointerType(Context->VoidPtrTy),
4546 VK_RValue, OK_Ordinary,
4547 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004548 InitExprs.push_back(DescRefExpr);
4549
Steve Narofffa15fd92008-10-28 20:29:00 +00004550 // Add initializers for any closure decl refs.
4551 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004552 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004553 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004554 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004555 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004556 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004557 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004558 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004559 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004560 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004561 if (HasLocalVariableExternalStorage(*I)) {
4562 QualType QT = (*I)->getType();
4563 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004564 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4565 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004566 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004567 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004568 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004569 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004570 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004571 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004572 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004573 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004574 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004575 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004576 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004577 if (HasLocalVariableExternalStorage(*I)) {
4578 QualType QT = (*I)->getType();
4579 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004580 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4581 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004582 }
4583
Steve Narofffa15fd92008-10-28 20:29:00 +00004584 }
Mike Stump1eb44332009-09-09 15:08:12 +00004585 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004586 }
4587 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004588 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004589 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004590 ValueDecl *ND = (*I);
4591 std::string Name(ND->getNameAsString());
4592 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004593 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004594 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4595 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004596 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004597 SourceLocation(), SourceLocation(),
4598 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004599 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4600 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4601
Daniel Dunbar4087f272010-08-17 22:39:59 +00004602 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004603 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
John McCallf89e55a2010-11-18 06:31:45 +00004604 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004605 bool isNestedCapturedVar = false;
4606 if (block)
4607 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4608 ce = block->capture_end(); ci != ce; ++ci) {
4609 const VarDecl *variable = ci->getVariable();
4610 if (variable == ND && ci->isNested()) {
4611 assert (ci->isByRef() &&
4612 "SynthBlockInitExpr - captured block variable is not byref");
4613 isNestedCapturedVar = true;
4614 break;
4615 }
4616 }
4617 // captured nested byref variable has its address passed. Do not take
4618 // its address again.
4619 if (!isNestedCapturedVar)
4620 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004621 Context->getPointerType(Exp->getType()),
4622 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004623 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004624 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004625 }
4626 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004627 if (ImportedBlockDecls.size()) {
4628 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4629 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004630 unsigned IntSize =
4631 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004632 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4633 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004634 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004635 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004636 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004637 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004638 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004639 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004640 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004641 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004642 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004643 BlockDeclRefs.clear();
4644 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004645 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004646 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004647 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004648 ImportedBlockDecls.clear();
4649 return NewRep;
4650}
4651
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004652bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4653 if (const ObjCForCollectionStmt * CS =
4654 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4655 return CS->getElement() == DS;
4656 return false;
4657}
4658
Steve Narofffa15fd92008-10-28 20:29:00 +00004659//===----------------------------------------------------------------------===//
4660// Function Body / Expression rewriting
4661//===----------------------------------------------------------------------===//
4662
4663Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004664 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004665 isa<DoStmt>(S) || isa<ForStmt>(S))
4666 Stmts.push_back(S);
4667 else if (isa<ObjCForCollectionStmt>(S)) {
4668 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004669 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004670 }
Mike Stump1eb44332009-09-09 15:08:12 +00004671
John McCall4b9c2d22011-11-06 09:01:30 +00004672 // Pseudo-object operations and ivar references need special
4673 // treatment because we're going to recursively rewrite them.
4674 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4675 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4676 return RewritePropertyOrImplicitSetter(PseudoOp);
4677 } else {
4678 return RewritePropertyOrImplicitGetter(PseudoOp);
4679 }
4680 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4681 return RewriteObjCIvarRefExpr(IvarRefExpr);
4682 }
4683
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004685
Steve Narofffa15fd92008-10-28 20:29:00 +00004686 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004687 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004688 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004689 Stmt *childStmt = (*CI);
4690 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004691 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004692 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004693 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004694 }
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Steve Narofffa15fd92008-10-28 20:29:00 +00004696 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004697 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004698 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4699 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004700 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004701 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004702 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004703 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004704 Stmt *SaveCurrentBody = CurrentBody;
4705 CurrentBody = BE->getBody();
4706 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004707 // block literal on rhs of a property-dot-sytax assignment
4708 // must be replaced by its synthesize ast so getRewrittenText
4709 // works as expected. In this case, what actually ends up on RHS
4710 // is the blockTranscribed which is the helper function for the
4711 // block literal; as in: self.c = ^() {[ace ARR];};
4712 bool saveDisableReplaceStmt = DisableReplaceStmt;
4713 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004714 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004715 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004716 CurrentBody = SaveCurrentBody;
4717 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004718 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004719 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004720 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004721 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004723 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4724
Steve Narofffa15fd92008-10-28 20:29:00 +00004725 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004726 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004727 return blockTranscribed;
4728 }
4729 // Handle specific things.
4730 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4731 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004732
Steve Narofffa15fd92008-10-28 20:29:00 +00004733 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4734 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Steve Narofffa15fd92008-10-28 20:29:00 +00004736 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4737 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004738
Steve Narofffa15fd92008-10-28 20:29:00 +00004739 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004740#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004741 // Before we rewrite it, put the original message expression in a comment.
4742 SourceLocation startLoc = MessExpr->getLocStart();
4743 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 const char *startBuf = SM->getCharacterData(startLoc);
4746 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004747
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 std::string messString;
4749 messString += "// ";
4750 messString.append(startBuf, endBuf-startBuf+1);
4751 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004752
4753 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 // InsertText(clang::SourceLocation, char const*, unsigned int).
4755 // InsertText(startLoc, messString.c_str(), messString.size());
4756 // Tried this, but it didn't work either...
4757 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004758#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004759 return RewriteMessageExpr(MessExpr);
4760 }
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Steve Narofffa15fd92008-10-28 20:29:00 +00004762 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4763 return RewriteObjCTryStmt(StmtTry);
4764
4765 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4766 return RewriteObjCSynchronizedStmt(StmtTry);
4767
4768 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4769 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004770
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4772 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004773
4774 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004775 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004776 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004777 OrigStmtRange.getEnd());
4778 if (BreakStmt *StmtBreakStmt =
4779 dyn_cast<BreakStmt>(S))
4780 return RewriteBreakStmt(StmtBreakStmt);
4781 if (ContinueStmt *StmtContinueStmt =
4782 dyn_cast<ContinueStmt>(S))
4783 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004784
4785 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004786 // and cast exprs.
4787 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4788 // FIXME: What we're doing here is modifying the type-specifier that
4789 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004790 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004791 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4792 // the context of an ObjCForCollectionStmt. For example:
4793 // NSArray *someArray;
4794 // for (id <FooProtocol> index in someArray) ;
4795 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4796 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004797 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004798 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 // Blocks rewrite rules.
4801 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4802 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004803 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004804 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004805 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004806 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004807 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004808 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004809 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004810 if (VD->hasAttr<BlocksAttr>()) {
4811 static unsigned uniqueByrefDeclCount = 0;
4812 assert(!BlockByRefDeclNo.count(ND) &&
4813 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4814 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004815 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004816 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004817 else
4818 RewriteTypeOfDecl(VD);
4819 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004820 }
Richard Smith162e1c12011-04-15 14:24:37 +00004821 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004822 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004823 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004824 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004825 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4826 }
4827 }
4828 }
Mike Stump1eb44332009-09-09 15:08:12 +00004829
Steve Narofffa15fd92008-10-28 20:29:00 +00004830 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4831 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004832
4833 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004834 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4835 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004836 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4837 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004838 && "Statement stack mismatch");
4839 Stmts.pop_back();
4840 }
4841 // Handle blocks rewriting.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004842 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4843 ValueDecl *VD = DRE->getDecl();
4844 if (VD->hasAttr<BlocksAttr>())
4845 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004846 if (HasLocalVariableExternalStorage(VD))
4847 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004848 }
4849
Steve Narofffa15fd92008-10-28 20:29:00 +00004850 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004851 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004852 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004853 ReplaceStmt(S, BlockCall);
4854 return BlockCall;
4855 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004856 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004857 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004858 RewriteCastExpr(CE);
4859 }
4860#if 0
4861 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004862 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4863 ICE->getSubExpr(),
4864 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004865 // Get the new text.
4866 std::string SStr;
4867 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004868 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004869 const std::string &Str = Buf.str();
4870
4871 printf("CAST = %s\n", &Str[0]);
4872 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4873 delete S;
4874 return Replacement;
4875 }
4876#endif
4877 // Return this stmt unmodified.
4878 return S;
4879}
4880
Steve Naroff3d7e7862009-12-05 15:55:59 +00004881void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4882 for (RecordDecl::field_iterator i = RD->field_begin(),
4883 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00004884 FieldDecl *FD = &*i;
Steve Naroff3d7e7862009-12-05 15:55:59 +00004885 if (isTopLevelBlockPointerType(FD->getType()))
4886 RewriteBlockPointerDecl(FD);
4887 if (FD->getType()->isObjCQualifiedIdType() ||
4888 FD->getType()->isObjCQualifiedInterfaceType())
4889 RewriteObjCQualifiedInterfaceTypes(FD);
4890 }
4891}
4892
Steve Narofffa15fd92008-10-28 20:29:00 +00004893/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4894/// main file of the input.
4895void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004896 switch (D->getKind()) {
4897 case Decl::Function: {
4898 FunctionDecl *FD = cast<FunctionDecl>(D);
4899 if (FD->isOverloadedOperator())
4900 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004901
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004902 // Since function prototypes don't have ParmDecl's, we check the function
4903 // prototype. This enables us to rewrite function declarations and
4904 // definitions using the same code.
4905 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004906
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004907 if (!FD->isThisDeclarationADefinition())
4908 break;
4909
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004910 // FIXME: If this should support Obj-C++, support CXXTryStmt
4911 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4912 CurFunctionDef = FD;
4913 CurFunctionDeclToDeclareForBlock = FD;
4914 CurrentBody = Body;
4915 Body =
4916 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4917 FD->setBody(Body);
4918 CurrentBody = 0;
4919 if (PropParentMap) {
4920 delete PropParentMap;
4921 PropParentMap = 0;
4922 }
4923 // This synthesizes and inserts the block "impl" struct, invoke function,
4924 // and any copy/dispose helper functions.
4925 InsertBlockLiteralsWithinFunction(FD);
4926 CurFunctionDef = 0;
4927 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004928 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004929 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004930 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004931 case Decl::ObjCMethod: {
4932 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4933 if (CompoundStmt *Body = MD->getCompoundBody()) {
4934 CurMethodDef = MD;
4935 CurrentBody = Body;
4936 Body =
4937 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4938 MD->setBody(Body);
4939 CurrentBody = 0;
4940 if (PropParentMap) {
4941 delete PropParentMap;
4942 PropParentMap = 0;
4943 }
4944 InsertBlockLiteralsWithinMethod(MD);
4945 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004946 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004947 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004949 case Decl::ObjCImplementation: {
4950 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4951 ClassImplementation.push_back(CI);
4952 break;
4953 }
4954 case Decl::ObjCCategoryImpl: {
4955 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4956 CategoryImplementation.push_back(CI);
4957 break;
4958 }
4959 case Decl::Var: {
4960 VarDecl *VD = cast<VarDecl>(D);
4961 RewriteObjCQualifiedInterfaceTypes(VD);
4962 if (isTopLevelBlockPointerType(VD->getType()))
4963 RewriteBlockPointerDecl(VD);
4964 else if (VD->getType()->isFunctionPointerType()) {
4965 CheckFunctionPointerDecl(VD->getType(), VD);
4966 if (VD->getInit()) {
4967 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4968 RewriteCastExpr(CE);
4969 }
4970 }
4971 } else if (VD->getType()->isRecordType()) {
4972 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4973 if (RD->isCompleteDefinition())
4974 RewriteRecordBody(RD);
4975 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004976 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004977 GlobalVarDecl = VD;
4978 CurrentBody = VD->getInit();
4979 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4980 CurrentBody = 0;
4981 if (PropParentMap) {
4982 delete PropParentMap;
4983 PropParentMap = 0;
4984 }
4985 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4986 GlobalVarDecl = 0;
4987
4988 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004989 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004990 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004991 }
4992 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004993 break;
4994 }
4995 case Decl::TypeAlias:
4996 case Decl::Typedef: {
4997 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4998 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4999 RewriteBlockPointerDecl(TD);
5000 else if (TD->getUnderlyingType()->isFunctionPointerType())
5001 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5002 }
5003 break;
5004 }
5005 case Decl::CXXRecord:
5006 case Decl::Record: {
5007 RecordDecl *RD = cast<RecordDecl>(D);
5008 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005009 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005010 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005011 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00005012 default:
5013 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00005014 }
5015 // Nothing yet.
5016}
5017
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005018void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005019 if (Diags.hasErrorOccurred())
5020 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005021
Steve Narofffa15fd92008-10-28 20:29:00 +00005022 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Naroff621edce2009-04-29 16:37:50 +00005024 // Here's a great place to add any extra declarations that may be needed.
5025 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005026 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005027 E = ProtocolExprDecls.end(); I != E; ++I)
5028 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5029
Benjamin Kramerd999b372010-02-14 14:14:16 +00005030 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005031 if (ClassImplementation.size() || CategoryImplementation.size())
5032 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005033
Steve Narofffa15fd92008-10-28 20:29:00 +00005034 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5035 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005036 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005037 Rewrite.getRewriteBufferFor(MainFileID)) {
5038 //printf("Changed:\n");
5039 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5040 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005041 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 }
Steve Narofface66252008-11-13 20:07:04 +00005043
Steve Naroff621edce2009-04-29 16:37:50 +00005044 if (ClassImplementation.size() || CategoryImplementation.size() ||
5045 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005046 // Rewrite Objective-c meta data*
5047 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005048 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005049 // Emit metadata.
5050 *OutFile << ResultStr;
5051 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005052 OutFile->flush();
5053}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005054
5055void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5056 InitializeCommon(context);
5057
5058 // declaring objc_selector outside the parameter list removes a silly
5059 // scope related warning...
5060 if (IsHeader)
5061 Preamble = "#pragma once\n";
5062 Preamble += "struct objc_selector; struct objc_class;\n";
5063 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5064 Preamble += "struct objc_object *superClass; ";
5065 if (LangOpts.MicrosoftExt) {
5066 // Add a constructor for creating temporary objects.
5067 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5068 ": ";
5069 Preamble += "object(o), superClass(s) {} ";
5070 }
5071 Preamble += "};\n";
5072 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5073 Preamble += "typedef struct objc_object Protocol;\n";
5074 Preamble += "#define _REWRITER_typedef_Protocol\n";
5075 Preamble += "#endif\n";
5076 if (LangOpts.MicrosoftExt) {
5077 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5078 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5079 } else
5080 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5081 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5082 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5084 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5086 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5088 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5090 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5091 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5092 Preamble += "(const char *);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5094 Preamble += "(struct objc_class *);\n";
5095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5096 Preamble += "(const char *);\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5099 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5102 Preamble += "(struct objc_class *, struct objc_object *);\n";
5103 // @synchronized hooks.
5104 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5106 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5107 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5108 Preamble += "struct __objcFastEnumerationState {\n\t";
5109 Preamble += "unsigned long state;\n\t";
5110 Preamble += "void **itemsPtr;\n\t";
5111 Preamble += "unsigned long *mutationsPtr;\n\t";
5112 Preamble += "unsigned long extra[5];\n};\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5114 Preamble += "#define __FASTENUMERATIONSTATE\n";
5115 Preamble += "#endif\n";
5116 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5117 Preamble += "struct __NSConstantStringImpl {\n";
5118 Preamble += " int *isa;\n";
5119 Preamble += " int flags;\n";
5120 Preamble += " char *str;\n";
5121 Preamble += " long length;\n";
5122 Preamble += "};\n";
5123 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5124 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5125 Preamble += "#else\n";
5126 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5127 Preamble += "#endif\n";
5128 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5129 Preamble += "#endif\n";
5130 // Blocks preamble.
5131 Preamble += "#ifndef BLOCK_IMPL\n";
5132 Preamble += "#define BLOCK_IMPL\n";
5133 Preamble += "struct __block_impl {\n";
5134 Preamble += " void *isa;\n";
5135 Preamble += " int Flags;\n";
5136 Preamble += " int Reserved;\n";
5137 Preamble += " void *FuncPtr;\n";
5138 Preamble += "};\n";
5139 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5140 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5141 Preamble += "extern \"C\" __declspec(dllexport) "
5142 "void _Block_object_assign(void *, const void *, const int);\n";
5143 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5144 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5145 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5146 Preamble += "#else\n";
5147 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5148 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5150 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5151 Preamble += "#endif\n";
5152 Preamble += "#endif\n";
5153 if (LangOpts.MicrosoftExt) {
5154 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5155 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5156 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5157 Preamble += "#define __attribute__(X)\n";
5158 Preamble += "#endif\n";
5159 Preamble += "#define __weak\n";
5160 }
5161 else {
5162 Preamble += "#define __block\n";
5163 Preamble += "#define __weak\n";
5164 }
5165 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5166 // as this avoids warning in any 64bit/32bit compilation model.
5167 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5168}
5169
5170/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5171/// ivar offset.
5172void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5173 std::string &Result) {
5174 if (ivar->isBitField()) {
5175 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5176 // place all bitfields at offset 0.
5177 Result += "0";
5178 } else {
5179 Result += "__OFFSETOFIVAR__(struct ";
5180 Result += ivar->getContainingInterface()->getNameAsString();
5181 if (LangOpts.MicrosoftExt)
5182 Result += "_IMPL";
5183 Result += ", ";
5184 Result += ivar->getNameAsString();
5185 Result += ")";
5186 }
5187}
5188
5189/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5190void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5191 ObjCProtocolDecl *PDecl, StringRef prefix,
5192 StringRef ClassName, std::string &Result) {
5193 static bool objc_protocol_methods = false;
5194
5195 // Output struct protocol_methods holder of method selector and type.
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00005196 if (!objc_protocol_methods && PDecl->hasDefinition()) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005197 /* struct protocol_methods {
5198 SEL _cmd;
5199 char *method_types;
5200 }
5201 */
5202 Result += "\nstruct _protocol_methods {\n";
5203 Result += "\tstruct objc_selector *_cmd;\n";
5204 Result += "\tchar *method_types;\n";
5205 Result += "};\n";
5206
5207 objc_protocol_methods = true;
5208 }
5209 // Do not synthesize the protocol more than once.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005210 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005211 return;
5212
Douglas Gregor61cc2962012-01-02 02:00:30 +00005213 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5214 PDecl = Def;
5215
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005216 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5217 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5218 PDecl->instmeth_end());
5219 /* struct _objc_protocol_method_list {
5220 int protocol_method_count;
5221 struct protocol_methods protocols[];
5222 }
5223 */
5224 Result += "\nstatic struct {\n";
5225 Result += "\tint protocol_method_count;\n";
5226 Result += "\tstruct _protocol_methods protocol_methods[";
5227 Result += utostr(NumMethods);
5228 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5229 Result += PDecl->getNameAsString();
5230 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5231 "{\n\t" + utostr(NumMethods) + "\n";
5232
5233 // Output instance methods declared in this protocol.
5234 for (ObjCProtocolDecl::instmeth_iterator
5235 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5236 I != E; ++I) {
5237 if (I == PDecl->instmeth_begin())
5238 Result += "\t ,{{(struct objc_selector *)\"";
5239 else
5240 Result += "\t ,{(struct objc_selector *)\"";
5241 Result += (*I)->getSelector().getAsString();
5242 std::string MethodTypeString;
5243 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5244 Result += "\", \"";
5245 Result += MethodTypeString;
5246 Result += "\"}\n";
5247 }
5248 Result += "\t }\n};\n";
5249 }
5250
5251 // Output class methods declared in this protocol.
5252 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5253 PDecl->classmeth_end());
5254 if (NumMethods > 0) {
5255 /* struct _objc_protocol_method_list {
5256 int protocol_method_count;
5257 struct protocol_methods protocols[];
5258 }
5259 */
5260 Result += "\nstatic struct {\n";
5261 Result += "\tint protocol_method_count;\n";
5262 Result += "\tstruct _protocol_methods protocol_methods[";
5263 Result += utostr(NumMethods);
5264 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5265 Result += PDecl->getNameAsString();
5266 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5267 "{\n\t";
5268 Result += utostr(NumMethods);
5269 Result += "\n";
5270
5271 // Output instance methods declared in this protocol.
5272 for (ObjCProtocolDecl::classmeth_iterator
5273 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5274 I != E; ++I) {
5275 if (I == PDecl->classmeth_begin())
5276 Result += "\t ,{{(struct objc_selector *)\"";
5277 else
5278 Result += "\t ,{(struct objc_selector *)\"";
5279 Result += (*I)->getSelector().getAsString();
5280 std::string MethodTypeString;
5281 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5282 Result += "\", \"";
5283 Result += MethodTypeString;
5284 Result += "\"}\n";
5285 }
5286 Result += "\t }\n};\n";
5287 }
5288
5289 // Output:
5290 /* struct _objc_protocol {
5291 // Objective-C 1.0 extensions
5292 struct _objc_protocol_extension *isa;
5293 char *protocol_name;
5294 struct _objc_protocol **protocol_list;
5295 struct _objc_protocol_method_list *instance_methods;
5296 struct _objc_protocol_method_list *class_methods;
5297 };
5298 */
5299 static bool objc_protocol = false;
5300 if (!objc_protocol) {
5301 Result += "\nstruct _objc_protocol {\n";
5302 Result += "\tstruct _objc_protocol_extension *isa;\n";
5303 Result += "\tchar *protocol_name;\n";
5304 Result += "\tstruct _objc_protocol **protocol_list;\n";
5305 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5306 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5307 Result += "};\n";
5308
5309 objc_protocol = true;
5310 }
5311
5312 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5313 Result += PDecl->getNameAsString();
5314 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5315 "{\n\t0, \"";
5316 Result += PDecl->getNameAsString();
5317 Result += "\", 0, ";
5318 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5319 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5320 Result += PDecl->getNameAsString();
5321 Result += ", ";
5322 }
5323 else
5324 Result += "0, ";
5325 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5326 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5327 Result += PDecl->getNameAsString();
5328 Result += "\n";
5329 }
5330 else
5331 Result += "0\n";
5332 Result += "};\n";
5333
5334 // Mark this protocol as having been generated.
Douglas Gregor3fc73ee2012-01-01 18:09:12 +00005335 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005336 llvm_unreachable("protocol already synthesized");
5337
5338}
5339
5340void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5341 const ObjCList<ObjCProtocolDecl> &Protocols,
5342 StringRef prefix, StringRef ClassName,
5343 std::string &Result) {
5344 if (Protocols.empty()) return;
5345
5346 for (unsigned i = 0; i != Protocols.size(); i++)
5347 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5348
5349 // Output the top lovel protocol meta-data for the class.
5350 /* struct _objc_protocol_list {
5351 struct _objc_protocol_list *next;
5352 int protocol_count;
5353 struct _objc_protocol *class_protocols[];
5354 }
5355 */
5356 Result += "\nstatic struct {\n";
5357 Result += "\tstruct _objc_protocol_list *next;\n";
5358 Result += "\tint protocol_count;\n";
5359 Result += "\tstruct _objc_protocol *class_protocols[";
5360 Result += utostr(Protocols.size());
5361 Result += "];\n} _OBJC_";
5362 Result += prefix;
5363 Result += "_PROTOCOLS_";
5364 Result += ClassName;
5365 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5366 "{\n\t0, ";
5367 Result += utostr(Protocols.size());
5368 Result += "\n";
5369
5370 Result += "\t,{&_OBJC_PROTOCOL_";
5371 Result += Protocols[0]->getNameAsString();
5372 Result += " \n";
5373
5374 for (unsigned i = 1; i != Protocols.size(); i++) {
5375 Result += "\t ,&_OBJC_PROTOCOL_";
5376 Result += Protocols[i]->getNameAsString();
5377 Result += "\n";
5378 }
5379 Result += "\t }\n};\n";
5380}
5381
5382void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5383 std::string &Result) {
5384 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5385
5386 // Explicitly declared @interface's are already synthesized.
5387 if (CDecl->isImplicitInterfaceDecl()) {
Douglas Gregor7723fec2011-12-15 20:29:51 +00005388 // FIXME: Implementation of a class with no @interface (legacy) does not
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005389 // produce correct synthesis as yet.
5390 RewriteObjCInternalStruct(CDecl, Result);
5391 }
5392
5393 // Build _objc_ivar_list metadata for classes ivars if needed
5394 unsigned NumIvars = !IDecl->ivar_empty()
5395 ? IDecl->ivar_size()
5396 : (CDecl ? CDecl->ivar_size() : 0);
5397 if (NumIvars > 0) {
5398 static bool objc_ivar = false;
5399 if (!objc_ivar) {
5400 /* struct _objc_ivar {
5401 char *ivar_name;
5402 char *ivar_type;
5403 int ivar_offset;
5404 };
5405 */
5406 Result += "\nstruct _objc_ivar {\n";
5407 Result += "\tchar *ivar_name;\n";
5408 Result += "\tchar *ivar_type;\n";
5409 Result += "\tint ivar_offset;\n";
5410 Result += "};\n";
5411
5412 objc_ivar = true;
5413 }
5414
5415 /* struct {
5416 int ivar_count;
5417 struct _objc_ivar ivar_list[nIvars];
5418 };
5419 */
5420 Result += "\nstatic struct {\n";
5421 Result += "\tint ivar_count;\n";
5422 Result += "\tstruct _objc_ivar ivar_list[";
5423 Result += utostr(NumIvars);
5424 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5425 Result += IDecl->getNameAsString();
5426 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5427 "{\n\t";
5428 Result += utostr(NumIvars);
5429 Result += "\n";
5430
5431 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5432 SmallVector<ObjCIvarDecl *, 8> IVars;
5433 if (!IDecl->ivar_empty()) {
5434 for (ObjCInterfaceDecl::ivar_iterator
5435 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5436 IV != IVEnd; ++IV)
David Blaikie262bc182012-04-30 02:36:29 +00005437 IVars.push_back(&*IV);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005438 IVI = IDecl->ivar_begin();
5439 IVE = IDecl->ivar_end();
5440 } else {
5441 IVI = CDecl->ivar_begin();
5442 IVE = CDecl->ivar_end();
5443 }
5444 Result += "\t,{{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005445 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005446 Result += "\", \"";
5447 std::string TmpString, StrEncoding;
David Blaikie262bc182012-04-30 02:36:29 +00005448 Context->getObjCEncodingForType(IVI->getType(), TmpString, &*IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005449 QuoteDoublequotes(TmpString, StrEncoding);
5450 Result += StrEncoding;
5451 Result += "\", ";
David Blaikie262bc182012-04-30 02:36:29 +00005452 RewriteIvarOffsetComputation(&*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005453 Result += "}\n";
5454 for (++IVI; IVI != IVE; ++IVI) {
5455 Result += "\t ,{\"";
David Blaikie262bc182012-04-30 02:36:29 +00005456 Result += IVI->getNameAsString();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005457 Result += "\", \"";
5458 std::string TmpString, StrEncoding;
David Blaikie262bc182012-04-30 02:36:29 +00005459 Context->getObjCEncodingForType(IVI->getType(), TmpString, &*IVI);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005460 QuoteDoublequotes(TmpString, StrEncoding);
5461 Result += StrEncoding;
5462 Result += "\", ";
David Blaikie262bc182012-04-30 02:36:29 +00005463 RewriteIvarOffsetComputation(&*IVI, Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005464 Result += "}\n";
5465 }
5466
5467 Result += "\t }\n};\n";
5468 }
5469
5470 // Build _objc_method_list for class's instance methods if needed
5471 SmallVector<ObjCMethodDecl *, 32>
5472 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5473
5474 // If any of our property implementations have associated getters or
5475 // setters, produce metadata for them as well.
5476 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5477 PropEnd = IDecl->propimpl_end();
5478 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005479 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005480 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005481 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005482 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005483 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005484 if (!PD)
5485 continue;
5486 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5487 if (!Getter->isDefined())
5488 InstanceMethods.push_back(Getter);
5489 if (PD->isReadOnly())
5490 continue;
5491 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5492 if (!Setter->isDefined())
5493 InstanceMethods.push_back(Setter);
5494 }
5495 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5496 true, "", IDecl->getName(), Result);
5497
5498 // Build _objc_method_list for class's class methods if needed
5499 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5500 false, "", IDecl->getName(), Result);
5501
5502 // Protocols referenced in class declaration?
5503 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5504 "CLASS", CDecl->getName(), Result);
5505
5506 // Declaration of class/meta-class metadata
5507 /* struct _objc_class {
5508 struct _objc_class *isa; // or const char *root_class_name when metadata
5509 const char *super_class_name;
5510 char *name;
5511 long version;
5512 long info;
5513 long instance_size;
5514 struct _objc_ivar_list *ivars;
5515 struct _objc_method_list *methods;
5516 struct objc_cache *cache;
5517 struct objc_protocol_list *protocols;
5518 const char *ivar_layout;
5519 struct _objc_class_ext *ext;
5520 };
5521 */
5522 static bool objc_class = false;
5523 if (!objc_class) {
5524 Result += "\nstruct _objc_class {\n";
5525 Result += "\tstruct _objc_class *isa;\n";
5526 Result += "\tconst char *super_class_name;\n";
5527 Result += "\tchar *name;\n";
5528 Result += "\tlong version;\n";
5529 Result += "\tlong info;\n";
5530 Result += "\tlong instance_size;\n";
5531 Result += "\tstruct _objc_ivar_list *ivars;\n";
5532 Result += "\tstruct _objc_method_list *methods;\n";
5533 Result += "\tstruct objc_cache *cache;\n";
5534 Result += "\tstruct _objc_protocol_list *protocols;\n";
5535 Result += "\tconst char *ivar_layout;\n";
5536 Result += "\tstruct _objc_class_ext *ext;\n";
5537 Result += "};\n";
5538 objc_class = true;
5539 }
5540
5541 // Meta-class metadata generation.
5542 ObjCInterfaceDecl *RootClass = 0;
5543 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5544 while (SuperClass) {
5545 RootClass = SuperClass;
5546 SuperClass = SuperClass->getSuperClass();
5547 }
5548 SuperClass = CDecl->getSuperClass();
5549
5550 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5551 Result += CDecl->getNameAsString();
5552 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5553 "{\n\t(struct _objc_class *)\"";
5554 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5555 Result += "\"";
5556
5557 if (SuperClass) {
5558 Result += ", \"";
5559 Result += SuperClass->getNameAsString();
5560 Result += "\", \"";
5561 Result += CDecl->getNameAsString();
5562 Result += "\"";
5563 }
5564 else {
5565 Result += ", 0, \"";
5566 Result += CDecl->getNameAsString();
5567 Result += "\"";
5568 }
5569 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5570 // 'info' field is initialized to CLS_META(2) for metaclass
5571 Result += ", 0,2, sizeof(struct _objc_class), 0";
5572 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5573 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5574 Result += IDecl->getNameAsString();
5575 Result += "\n";
5576 }
5577 else
5578 Result += ", 0\n";
5579 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5580 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5581 Result += CDecl->getNameAsString();
5582 Result += ",0,0\n";
5583 }
5584 else
5585 Result += "\t,0,0,0,0\n";
5586 Result += "};\n";
5587
5588 // class metadata generation.
5589 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5590 Result += CDecl->getNameAsString();
5591 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5592 "{\n\t&_OBJC_METACLASS_";
5593 Result += CDecl->getNameAsString();
5594 if (SuperClass) {
5595 Result += ", \"";
5596 Result += SuperClass->getNameAsString();
5597 Result += "\", \"";
5598 Result += CDecl->getNameAsString();
5599 Result += "\"";
5600 }
5601 else {
5602 Result += ", 0, \"";
5603 Result += CDecl->getNameAsString();
5604 Result += "\"";
5605 }
5606 // 'info' field is initialized to CLS_CLASS(1) for class
5607 Result += ", 0,1";
5608 if (!ObjCSynthesizedStructs.count(CDecl))
5609 Result += ",0";
5610 else {
5611 // class has size. Must synthesize its size.
5612 Result += ",sizeof(struct ";
5613 Result += CDecl->getNameAsString();
5614 if (LangOpts.MicrosoftExt)
5615 Result += "_IMPL";
5616 Result += ")";
5617 }
5618 if (NumIvars > 0) {
5619 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5620 Result += CDecl->getNameAsString();
5621 Result += "\n\t";
5622 }
5623 else
5624 Result += ",0";
5625 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5626 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5627 Result += CDecl->getNameAsString();
5628 Result += ", 0\n\t";
5629 }
5630 else
5631 Result += ",0,0";
5632 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5633 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5634 Result += CDecl->getNameAsString();
5635 Result += ", 0,0\n";
5636 }
5637 else
5638 Result += ",0,0,0\n";
5639 Result += "};\n";
5640}
5641
5642void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5643 int ClsDefCount = ClassImplementation.size();
5644 int CatDefCount = CategoryImplementation.size();
5645
5646 // For each implemented class, write out all its meta data.
5647 for (int i = 0; i < ClsDefCount; i++)
5648 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5649
5650 // For each implemented category, write out all its meta data.
5651 for (int i = 0; i < CatDefCount; i++)
5652 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5653
5654 // Write objc_symtab metadata
5655 /*
5656 struct _objc_symtab
5657 {
5658 long sel_ref_cnt;
5659 SEL *refs;
5660 short cls_def_cnt;
5661 short cat_def_cnt;
5662 void *defs[cls_def_cnt + cat_def_cnt];
5663 };
5664 */
5665
5666 Result += "\nstruct _objc_symtab {\n";
5667 Result += "\tlong sel_ref_cnt;\n";
5668 Result += "\tSEL *refs;\n";
5669 Result += "\tshort cls_def_cnt;\n";
5670 Result += "\tshort cat_def_cnt;\n";
5671 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5672 Result += "};\n\n";
5673
5674 Result += "static struct _objc_symtab "
5675 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5676 Result += "\t0, 0, " + utostr(ClsDefCount)
5677 + ", " + utostr(CatDefCount) + "\n";
5678 for (int i = 0; i < ClsDefCount; i++) {
5679 Result += "\t,&_OBJC_CLASS_";
5680 Result += ClassImplementation[i]->getNameAsString();
5681 Result += "\n";
5682 }
5683
5684 for (int i = 0; i < CatDefCount; i++) {
5685 Result += "\t,&_OBJC_CATEGORY_";
5686 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5687 Result += "_";
5688 Result += CategoryImplementation[i]->getNameAsString();
5689 Result += "\n";
5690 }
5691
5692 Result += "};\n\n";
5693
5694 // Write objc_module metadata
5695
5696 /*
5697 struct _objc_module {
5698 long version;
5699 long size;
5700 const char *name;
5701 struct _objc_symtab *symtab;
5702 }
5703 */
5704
5705 Result += "\nstruct _objc_module {\n";
5706 Result += "\tlong version;\n";
5707 Result += "\tlong size;\n";
5708 Result += "\tconst char *name;\n";
5709 Result += "\tstruct _objc_symtab *symtab;\n";
5710 Result += "};\n\n";
5711 Result += "static struct _objc_module "
5712 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5713 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5714 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5715 Result += "};\n\n";
5716
5717 if (LangOpts.MicrosoftExt) {
5718 if (ProtocolExprDecls.size()) {
5719 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5720 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5721 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5722 E = ProtocolExprDecls.end(); I != E; ++I) {
5723 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5724 Result += (*I)->getNameAsString();
5725 Result += " = &_OBJC_PROTOCOL_";
5726 Result += (*I)->getNameAsString();
5727 Result += ";\n";
5728 }
5729 Result += "#pragma data_seg(pop)\n\n";
5730 }
5731 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5732 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5733 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5734 Result += "&_OBJC_MODULES;\n";
5735 Result += "#pragma data_seg(pop)\n\n";
5736 }
5737}
5738
5739/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5740/// implementation.
5741void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5742 std::string &Result) {
5743 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5744 // Find category declaration for this implementation.
5745 ObjCCategoryDecl *CDecl;
5746 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5747 CDecl = CDecl->getNextClassCategory())
5748 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5749 break;
5750
5751 std::string FullCategoryName = ClassDecl->getNameAsString();
5752 FullCategoryName += '_';
5753 FullCategoryName += IDecl->getNameAsString();
5754
5755 // Build _objc_method_list for class's instance methods if needed
5756 SmallVector<ObjCMethodDecl *, 32>
5757 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5758
5759 // If any of our property implementations have associated getters or
5760 // setters, produce metadata for them as well.
5761 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5762 PropEnd = IDecl->propimpl_end();
5763 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00005764 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005765 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005766 if (!Prop->getPropertyIvarDecl())
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005767 continue;
David Blaikie262bc182012-04-30 02:36:29 +00005768 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005769 if (!PD)
5770 continue;
5771 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5772 InstanceMethods.push_back(Getter);
5773 if (PD->isReadOnly())
5774 continue;
5775 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5776 InstanceMethods.push_back(Setter);
5777 }
5778 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5779 true, "CATEGORY_", FullCategoryName.c_str(),
5780 Result);
5781
5782 // Build _objc_method_list for class's class methods if needed
5783 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5784 false, "CATEGORY_", FullCategoryName.c_str(),
5785 Result);
5786
5787 // Protocols referenced in class declaration?
5788 // Null CDecl is case of a category implementation with no category interface
5789 if (CDecl)
5790 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5791 FullCategoryName, Result);
5792 /* struct _objc_category {
5793 char *category_name;
5794 char *class_name;
5795 struct _objc_method_list *instance_methods;
5796 struct _objc_method_list *class_methods;
5797 struct _objc_protocol_list *protocols;
5798 // Objective-C 1.0 extensions
5799 uint32_t size; // sizeof (struct _objc_category)
5800 struct _objc_property_list *instance_properties; // category's own
5801 // @property decl.
5802 };
5803 */
5804
5805 static bool objc_category = false;
5806 if (!objc_category) {
5807 Result += "\nstruct _objc_category {\n";
5808 Result += "\tchar *category_name;\n";
5809 Result += "\tchar *class_name;\n";
5810 Result += "\tstruct _objc_method_list *instance_methods;\n";
5811 Result += "\tstruct _objc_method_list *class_methods;\n";
5812 Result += "\tstruct _objc_protocol_list *protocols;\n";
5813 Result += "\tunsigned int size;\n";
5814 Result += "\tstruct _objc_property_list *instance_properties;\n";
5815 Result += "};\n";
5816 objc_category = true;
5817 }
5818 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5819 Result += FullCategoryName;
5820 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5821 Result += IDecl->getNameAsString();
5822 Result += "\"\n\t, \"";
5823 Result += ClassDecl->getNameAsString();
5824 Result += "\"\n";
5825
5826 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5827 Result += "\t, (struct _objc_method_list *)"
5828 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5829 Result += FullCategoryName;
5830 Result += "\n";
5831 }
5832 else
5833 Result += "\t, 0\n";
5834 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5835 Result += "\t, (struct _objc_method_list *)"
5836 "&_OBJC_CATEGORY_CLASS_METHODS_";
5837 Result += FullCategoryName;
5838 Result += "\n";
5839 }
5840 else
5841 Result += "\t, 0\n";
5842
5843 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5844 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5845 Result += FullCategoryName;
5846 Result += "\n";
5847 }
5848 else
5849 Result += "\t, 0\n";
5850 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5851}
5852
5853// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5854/// class methods.
5855template<typename MethodIterator>
5856void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5857 MethodIterator MethodEnd,
5858 bool IsInstanceMethod,
5859 StringRef prefix,
5860 StringRef ClassName,
5861 std::string &Result) {
5862 if (MethodBegin == MethodEnd) return;
5863
5864 if (!objc_impl_method) {
5865 /* struct _objc_method {
5866 SEL _cmd;
5867 char *method_types;
5868 void *_imp;
5869 }
5870 */
5871 Result += "\nstruct _objc_method {\n";
5872 Result += "\tSEL _cmd;\n";
5873 Result += "\tchar *method_types;\n";
5874 Result += "\tvoid *_imp;\n";
5875 Result += "};\n";
5876
5877 objc_impl_method = true;
5878 }
5879
5880 // Build _objc_method_list for class's methods if needed
5881
5882 /* struct {
5883 struct _objc_method_list *next_method;
5884 int method_count;
5885 struct _objc_method method_list[];
5886 }
5887 */
5888 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5889 Result += "\nstatic struct {\n";
5890 Result += "\tstruct _objc_method_list *next_method;\n";
5891 Result += "\tint method_count;\n";
5892 Result += "\tstruct _objc_method method_list[";
5893 Result += utostr(NumMethods);
5894 Result += "];\n} _OBJC_";
5895 Result += prefix;
5896 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5897 Result += "_METHODS_";
5898 Result += ClassName;
5899 Result += " __attribute__ ((used, section (\"__OBJC, __";
5900 Result += IsInstanceMethod ? "inst" : "cls";
5901 Result += "_meth\")))= ";
5902 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5903
5904 Result += "\t,{{(SEL)\"";
5905 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5906 std::string MethodTypeString;
5907 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5908 Result += "\", \"";
5909 Result += MethodTypeString;
5910 Result += "\", (void *)";
5911 Result += MethodInternalNames[*MethodBegin];
5912 Result += "}\n";
5913 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5914 Result += "\t ,{(SEL)\"";
5915 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5916 std::string MethodTypeString;
5917 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5918 Result += "\", \"";
5919 Result += MethodTypeString;
5920 Result += "\", (void *)";
5921 Result += MethodInternalNames[*MethodBegin];
5922 Result += "}\n";
5923 }
5924 Result += "\t }\n};\n";
5925}
5926
5927Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5928 SourceRange OldRange = IV->getSourceRange();
5929 Expr *BaseExpr = IV->getBase();
5930
5931 // Rewrite the base, but without actually doing replaces.
5932 {
5933 DisableReplaceStmtScope S(*this);
5934 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5935 IV->setBase(BaseExpr);
5936 }
5937
5938 ObjCIvarDecl *D = IV->getDecl();
5939
5940 Expr *Replacement = IV;
5941 if (CurMethodDef) {
5942 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5943 const ObjCInterfaceType *iFaceDecl =
5944 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5945 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5946 // lookup which class implements the instance variable.
5947 ObjCInterfaceDecl *clsDeclared = 0;
5948 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5949 clsDeclared);
5950 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5951
5952 // Synthesize an explicit cast to gain access to the ivar.
5953 std::string RecName = clsDeclared->getIdentifier()->getName();
5954 RecName += "_IMPL";
5955 IdentifierInfo *II = &Context->Idents.get(RecName);
5956 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5957 SourceLocation(), SourceLocation(),
5958 II);
5959 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5960 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5961 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5962 CK_BitCast,
5963 IV->getBase());
5964 // Don't forget the parens to enforce the proper binding.
5965 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5966 OldRange.getEnd(),
5967 castExpr);
5968 if (IV->isFreeIvar() &&
Douglas Gregor60ef3082011-12-15 00:29:59 +00005969 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005970 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5971 IV->getLocation(),
5972 D->getType(),
5973 VK_LValue, OK_Ordinary);
5974 Replacement = ME;
5975 } else {
5976 IV->setBase(PE);
5977 }
5978 }
5979 } else { // we are outside a method.
5980 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5981
5982 // Explicit ivar refs need to have a cast inserted.
5983 // FIXME: consider sharing some of this code with the code above.
5984 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5985 const ObjCInterfaceType *iFaceDecl =
5986 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5987 // lookup which class implements the instance variable.
5988 ObjCInterfaceDecl *clsDeclared = 0;
5989 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5990 clsDeclared);
5991 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5992
5993 // Synthesize an explicit cast to gain access to the ivar.
5994 std::string RecName = clsDeclared->getIdentifier()->getName();
5995 RecName += "_IMPL";
5996 IdentifierInfo *II = &Context->Idents.get(RecName);
5997 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5998 SourceLocation(), SourceLocation(),
5999 II);
6000 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6001 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6002 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6003 CK_BitCast,
6004 IV->getBase());
6005 // Don't forget the parens to enforce the proper binding.
6006 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6007 IV->getBase()->getLocEnd(), castExpr);
6008 // Cannot delete IV->getBase(), since PE points to it.
6009 // Replace the old base with the cast. This is important when doing
6010 // embedded rewrites. For example, [newInv->_container addObject:0].
6011 IV->setBase(PE);
6012 }
6013 }
6014
6015 ReplaceStmtWithRange(IV, Replacement, OldRange);
6016 return Replacement;
6017}
6018