blob: 428418a09d95761a9cf44a5e99038d1cfd758cff [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 Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
56
Chris Lattner2c64b7b2007-10-16 21:07:07 +000057 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000058 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000059 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000060 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000061 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000062
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;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000068 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000073 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000074 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
75 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000078 // Remember all the @protocol(<expr>) expressions.
79 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000080
81 llvm::DenseSet<uint64_t> CopyDestroyCache;
82
Steve Naroffd82a9ab2008-03-15 00:55:56 +000083 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000084
Steve Naroffebf2b562007-10-23 23:50:29 +000085 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000086 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000087 FunctionDecl *MsgSendStretFunctionDecl;
88 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000089 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000090 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000091 FunctionDecl *GetMetaClassFunctionDecl;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +000092 FunctionDecl *GetSuperClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000093 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000094 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000095 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000096
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000098 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000099 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Fariborz Jahanianb586cce2008-01-16 00:09:11 +0000101 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000102 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Steve Naroff874e2322007-11-15 10:28:18 +0000104 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000105 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000106 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000107 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Steve Naroff621edce2009-04-29 16:37:50 +0000109 TypeDecl *ProtocolTypeDecl;
110 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000111
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000112 // Needed for header files being rewritten
113 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Steve Naroffa7b402d2008-03-28 22:26:09 +0000115 std::string InFileName;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000117
118 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000119 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000120
Steve Naroffba92b2e2008-03-27 22:29:16 +0000121 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000122
123 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroff4c3580e2008-12-04 23:50:32 +0000141 // This maps an original source AST to it's rewritten form. This allows
142 // us to avoid rewriting the same node twice (which is very uncommon).
143 // This is needed to support some of the exotic property rewriting.
144 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000145
Steve Naroff54055232008-10-27 17:20:55 +0000146 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000147 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000148 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Steve Naroffb619d952008-12-09 12:56:34 +0000150 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000151 class DisableReplaceStmtScope {
152 RewriteObjC &R;
153 bool SavedValue;
154
155 public:
156 DisableReplaceStmtScope(RewriteObjC &R)
157 : R(R), SavedValue(R.DisableReplaceStmt) {
158 R.DisableReplaceStmt = true;
159 }
160 ~DisableReplaceStmtScope() {
161 R.DisableReplaceStmt = SavedValue;
162 }
163 };
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Nick Lewycky7e749242010-10-31 21:07:24 +0000165 static const int OBJC_ABI_VERSION = 7;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000166 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000167 virtual void Initialize(ASTContext &context);
168
Chris Lattnerf04da132007-10-24 17:06:59 +0000169 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000170 virtual void HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000171 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
172 if (isa<ObjCClassDecl>((*I))) {
173 RewriteForwardClassDecl(D);
174 break;
175 }
Chris Lattner682bf922009-03-29 16:50:03 +0000176 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000177 }
Chris Lattner682bf922009-03-29 16:50:03 +0000178 }
179 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000180 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000181 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000182 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000183 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000184
185 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000187 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000189 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000190 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Steve Naroff4c3580e2008-12-04 23:50:32 +0000192 if (ReplacingStmt)
193 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000194
Steve Naroffb619d952008-12-09 12:56:34 +0000195 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000196 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000197
Steve Naroff4c3580e2008-12-04 23:50:32 +0000198 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000199 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000200 ReplacedNodes[Old] = New;
201 return;
202 }
203 if (SilenceRewriteMacroWarning)
204 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000205 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
206 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000207 }
Steve Naroffb619d952008-12-09 12:56:34 +0000208
209 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000210 if (DisableReplaceStmt)
211 return;
212
Nick Lewycky7e749242010-10-31 21:07:24 +0000213 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000214 int Size = Rewrite.getRangeSize(SrcRange);
215 if (Size == -1) {
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 return;
219 }
220 // Get the new text.
221 std::string SStr;
222 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000223 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000224 const std::string &Str = S.str();
225
226 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000227 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000228 ReplacedNodes[Old] = New;
229 return;
230 }
231 if (SilenceRewriteMacroWarning)
232 return;
233 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
234 << Old->getSourceRange();
235 }
236
Chris Lattner5f9e2722011-07-23 10:55:15 +0000237 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000238 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000244 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000248 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000249 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000250 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000251 SilenceRewriteMacroWarning)
252 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattneraadaf782008-01-31 19:51:04 +0000254 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
255 }
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattnerf04da132007-10-24 17:06:59 +0000257 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000258 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000259 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000260 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
261 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
262 const std::string &typedefString);
263
Steve Naroffa0876e82008-12-02 17:36:43 +0000264 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
265 ObjCImplementationDecl *IMD,
266 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000267 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000268 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000269 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
270 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000271 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
272 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000273 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000274 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000275 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
276 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
277 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
278 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000279 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000280 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000281 void RewriteBlockPointerType(std::string& Str, QualType Type);
282 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000283 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000284 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000285 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000286 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000287 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000288 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000289 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000290 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000291 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000292
Chris Lattnerf04da132007-10-24 17:06:59 +0000293 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000294 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Steve Naroff8599e7a2008-12-08 16:43:47 +0000296 Stmt *CurrentBody;
297 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattnere64b7772007-10-24 16:57:36 +0000299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000300 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
301 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000303 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000304 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000305 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000306 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000307 void WarnAboutReturnGotoStmts(Stmt *S);
308 void HasReturnStmts(Stmt *S, bool &hasReturns);
309 void RewriteTryReturnStmts(Stmt *S);
310 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000311 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000312 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000313 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000314 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
315 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000316 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000317 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000318 Expr **args, unsigned nargs,
319 SourceLocation StartLoc=SourceLocation(),
320 SourceLocation EndLoc=SourceLocation());
321 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
322 SourceLocation StartLoc=SourceLocation(),
323 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000324 Stmt *RewriteBreakStmt(BreakStmt *S);
325 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000326 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Steve Naroff09b266e2007-10-30 23:14:51 +0000328 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000329 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000330 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000331 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000332 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000333 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000334 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000335 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000336 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000337 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Chris Lattnerf04da132007-10-24 17:06:59 +0000339 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000340 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000341 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000343 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000344 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Douglas Gregor653f1b12009-04-23 01:02:12 +0000346 template<typename MethodIterator>
347 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
348 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000349 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 StringRef prefix,
351 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000352 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff621edce2009-04-29 16:37:50 +0000354 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000355 StringRef prefix,
356 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000357 std::string &Result);
358 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000359 StringRef prefix,
360 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000361 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000362 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000363 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000364 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000365 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000366 void RewriteImplementations();
367 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Steve Naroff54055232008-10-27 17:20:55 +0000369 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000370 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000371 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Steve Naroff54055232008-10-27 17:20:55 +0000373 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
374 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000375
376 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000377 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000378 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000379 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000380 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000381 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000382 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
384 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000385 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000386 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000387 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000388 std::string SynthesizeBlockImpl(BlockExpr *CE,
389 std::string Tag, std::string Desc);
390 std::string SynthesizeBlockDescriptor(std::string DescTag,
391 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000392 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000393 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000394 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000397 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Steve Naroff54055232008-10-27 17:20:55 +0000399 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000400 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000401 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000402 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000403 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Steve Naroff54055232008-10-27 17:20:55 +0000405 // We avoid calling Type::isBlockPointerType(), since it operates on the
406 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000407 bool isTopLevelBlockPointerType(QualType T) {
408 return isa<BlockPointerType>(T);
409 }
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000411 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
412 /// to a function pointer type and upon success, returns true; false
413 /// otherwise.
414 bool convertBlockPointerToFunctionPointer(QualType &T) {
415 if (isTopLevelBlockPointerType(T)) {
416 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
417 T = Context->getPointerType(BPT->getPointeeType());
418 return true;
419 }
420 return false;
421 }
422
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000423 void convertToUnqualifiedObjCType(QualType &T) {
424 if (T->isObjCQualifiedIdType())
425 T = Context->getObjCIdType();
426 else if (T->isObjCQualifiedClassType())
427 T = Context->getObjCClassType();
428 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000429 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
430 if (const ObjCObjectPointerType * OBJPT =
431 T->getAsObjCInterfacePointerType()) {
432 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
433 T = QualType(IFaceT, 0);
434 T = Context->getPointerType(T);
435 }
436 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000437 }
438
Steve Naroff54055232008-10-27 17:20:55 +0000439 // FIXME: This predicate seems like it would be useful to add to ASTContext.
440 bool isObjCType(QualType T) {
441 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
442 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Steve Naroff54055232008-10-27 17:20:55 +0000444 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Steve Naroff54055232008-10-27 17:20:55 +0000446 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
447 OCT == Context->getCanonicalType(Context->getObjCClassType()))
448 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Ted Kremenek6217b802009-07-29 21:53:49 +0000450 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000451 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000452 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000453 return true;
454 }
455 return false;
456 }
457 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000458 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000459 void GetExtentOfArgList(const char *Name, const char *&LParen,
460 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000461 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Chris Lattner5f9e2722011-07-23 10:55:15 +0000463 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000464 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000465 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Steve Naroff621edce2009-04-29 16:37:50 +0000467 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000468 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000469 if (From[i] == '"')
470 To += "\\\"";
471 else
472 To += From[i];
473 }
474 }
John McCalle23cf432010-12-14 08:05:40 +0000475
476 QualType getSimpleFunctionType(QualType result,
477 const QualType *args,
478 unsigned numArgs,
479 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000480 if (result == Context->getObjCInstanceType())
481 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000482 FunctionProtoType::ExtProtoInfo fpi;
483 fpi.Variadic = variadic;
484 return Context->getFunctionType(result, args, numArgs, fpi);
485 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000486 };
John McCall9d125032010-01-15 18:39:57 +0000487
488 // Helper function: create a CStyleCastExpr with trivial type source info.
489 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000490 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000491 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000492 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000493 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000494 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000495}
496
Mike Stump1eb44332009-09-09 15:08:12 +0000497void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
498 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000499 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000500 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000501 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000502 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000503 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000504 // All the args are checked/rewritten. Don't call twice!
505 RewriteBlockPointerDecl(D);
506 break;
507 }
508 }
509}
510
511void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000512 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000513 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000514 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000515}
516
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000517static bool IsHeaderFile(const std::string &Filename) {
518 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000520 if (DotPos == std::string::npos) {
521 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000522 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000525 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
526 // C header: .h
527 // C++ header: .hh or .H;
528 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000529}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000530
Chris Lattner5f9e2722011-07-23 10:55:15 +0000531RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000532 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000533 bool silenceMacroWarn)
534 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
535 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000536 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000537 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000538 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000539 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
540 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000541 "rewriter doesn't support user-specified control flow semantics "
542 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000543}
544
Eli Friedmanbce831b2009-05-18 22:29:17 +0000545ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000546 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000547 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000548 const LangOptions &LOpts,
549 bool SilenceRewriteMacroWarning) {
550 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000551}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000552
Steve Naroffb29b4272008-04-14 22:03:09 +0000553void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000554 Context = &context;
555 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000556 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000557 MsgSendFunctionDecl = 0;
558 MsgSendSuperFunctionDecl = 0;
559 MsgSendStretFunctionDecl = 0;
560 MsgSendSuperStretFunctionDecl = 0;
561 MsgSendFpretFunctionDecl = 0;
562 GetClassFunctionDecl = 0;
563 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000564 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000565 SelGetUidFunctionDecl = 0;
566 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000567 ConstantStringClassReference = 0;
568 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000569 CurMethodDef = 0;
570 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000571 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000572 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000573 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000574 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000575 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000576 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000577 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000578 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000579 PropParentMap = 0;
580 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000581 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000582 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000584 // Get the ID and start/end of the main file.
585 MainFileID = SM->getMainFileID();
586 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
587 MainFileStart = MainBuf->getBufferStart();
588 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner2c78b872009-04-14 23:22:57 +0000590 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000592 // declaring objc_selector outside the parameter list removes a silly
593 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000595 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000596 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000597 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000599 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000600 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000601 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
602 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000604 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000606 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
607 Preamble += "typedef struct objc_object Protocol;\n";
608 Preamble += "#define _REWRITER_typedef_Protocol\n";
609 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000610 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000611 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
612 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
613 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000614 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000615 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000617 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000618 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Fariborz Jahanian336c8f72011-10-11 23:02:37 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000622 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000627 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
628 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000629 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000630 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000631 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
632 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
634 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000636 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000637 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000638 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
639 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
640 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000641 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
642 Preamble += "struct __objcFastEnumerationState {\n\t";
643 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000644 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000645 Preamble += "unsigned long *mutationsPtr;\n\t";
646 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000647 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000648 Preamble += "#define __FASTENUMERATIONSTATE\n";
649 Preamble += "#endif\n";
650 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
651 Preamble += "struct __NSConstantStringImpl {\n";
652 Preamble += " int *isa;\n";
653 Preamble += " int flags;\n";
654 Preamble += " char *str;\n";
655 Preamble += " long length;\n";
656 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000657 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
658 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
659 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000660 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000661 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000662 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
663 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000664 // Blocks preamble.
665 Preamble += "#ifndef BLOCK_IMPL\n";
666 Preamble += "#define BLOCK_IMPL\n";
667 Preamble += "struct __block_impl {\n";
668 Preamble += " void *isa;\n";
669 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000670 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000671 Preamble += " void *FuncPtr;\n";
672 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000673 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000674 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000675 Preamble += "extern \"C\" __declspec(dllexport) "
676 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000677 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
678 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
679 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
680 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000681 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
682 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000683 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
684 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
685 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000686 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000687 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000688 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
689 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000690 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000691 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000692 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000693 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000694 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000695 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000696 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000697 Preamble += "#define __weak\n";
698 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000699 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
700 // as this avoids warning in any 64bit/32bit compilation model.
701 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000702}
703
704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Top Level Driver Code
707//===----------------------------------------------------------------------===//
708
Chris Lattner682bf922009-03-29 16:50:03 +0000709void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000710 if (Diags.hasErrorOccurred())
711 return;
712
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000713 // Two cases: either the decl could be in the main file, or it could be in a
714 // #included file. If the former, rewrite it now. If the later, check to see
715 // if we rewrote the #include/#import.
716 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000717 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000719 // If this is for a builtin, ignore it.
720 if (Loc.isInvalid()) return;
721
Steve Naroffebf2b562007-10-23 23:50:29 +0000722 // Look for built-in declarations that we need to refer during the rewrite.
723 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000724 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000725 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000726 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000727 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000728 ConstantStringClassReference = FVD;
729 return;
730 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000731 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000732 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000733 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000734 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000735 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000736 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000737 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000738 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000739 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000740 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
741 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000742 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
743 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000744 DI != DIEnd; ) {
745 if (isa<ObjCClassDecl>((*DI))) {
746 SmallVector<Decl *, 8> DG;
747 Decl *D = (*DI);
748 SourceLocation Loc = D->getLocation();
749 while (DI != DIEnd &&
750 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
751 DG.push_back(D);
752 ++DI;
753 D = (*DI);
754 }
755 RewriteForwardClassDecl(DG);
756 continue;
757 }
Chris Lattner682bf922009-03-29 16:50:03 +0000758 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000759 ++DI;
760 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000761 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000762 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000763 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000764 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000765}
766
Chris Lattnerf04da132007-10-24 17:06:59 +0000767//===----------------------------------------------------------------------===//
768// Syntactic (non-AST) Rewriting Code
769//===----------------------------------------------------------------------===//
770
Steve Naroffb29b4272008-04-14 22:03:09 +0000771void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000772 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000773 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000774 const char *MainBufStart = MainBuf.begin();
775 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000776 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000778 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000779 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
780 if (*BufPtr == '#') {
781 if (++BufPtr == MainBufEnd)
782 return;
783 while (*BufPtr == ' ' || *BufPtr == '\t')
784 if (++BufPtr == MainBufEnd)
785 return;
786 if (!strncmp(BufPtr, "import", ImportLen)) {
787 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000788 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000789 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000790 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000791 BufPtr += ImportLen;
792 }
793 }
794 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000795}
796
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000797static std::string getIvarAccessString(ObjCIvarDecl *OID) {
798 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000799 std::string S;
800 S = "((struct ";
801 S += ClassDecl->getIdentifier()->getName();
802 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000803 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000804 return S;
805}
806
Steve Naroffa0876e82008-12-02 17:36:43 +0000807void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
808 ObjCImplementationDecl *IMD,
809 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000810 static bool objcGetPropertyDefined = false;
811 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000812 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000813 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000814 const char *startBuf = SM->getCharacterData(startLoc);
815 assert((*startBuf == '@') && "bogus @synthesize location");
816 const char *semiBuf = strchr(startBuf, ';');
817 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000818 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000819 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000820
821 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
822 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Steve Naroffeb0646c2008-12-02 15:48:25 +0000824 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000825 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000826 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000828 if (!OID)
829 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000830 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000831 if (!PD->getGetterMethodDecl()->isDefined()) {
832 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
833 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
834 ObjCPropertyDecl::OBJC_PR_copy));
835 std::string Getr;
836 if (GenGetProperty && !objcGetPropertyDefined) {
837 objcGetPropertyDefined = true;
838 // FIXME. Is this attribute correct in all cases?
839 Getr = "\nextern \"C\" __declspec(dllimport) "
840 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000841 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000842 RewriteObjCMethodDecl(OID->getContainingInterface(),
843 PD->getGetterMethodDecl(), Getr);
844 Getr += "{ ";
845 // Synthesize an explicit cast to gain access to the ivar.
846 // See objc-act.c:objc_synthesize_new_getter() for details.
847 if (GenGetProperty) {
848 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
849 Getr += "typedef ";
850 const FunctionType *FPRetType = 0;
851 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
852 FPRetType);
853 Getr += " _TYPE";
854 if (FPRetType) {
855 Getr += ")"; // close the precedence "scope" for "*".
856
857 // Now, emit the argument types (if any).
858 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
859 Getr += "(";
860 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
861 if (i) Getr += ", ";
862 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000863 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000864 Getr += ParamStr;
865 }
866 if (FT->isVariadic()) {
867 if (FT->getNumArgs()) Getr += ", ";
868 Getr += "...";
869 }
870 Getr += ")";
871 } else
872 Getr += "()";
873 }
874 Getr += ";\n";
875 Getr += "return (_TYPE)";
876 Getr += "objc_getProperty(self, _cmd, ";
877 SynthesizeIvarOffsetComputation(OID, Getr);
878 Getr += ", 1)";
879 }
880 else
881 Getr += "return " + getIvarAccessString(OID);
882 Getr += "; }";
883 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000884 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000885
886 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000887 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Steve Naroffeb0646c2008-12-02 15:48:25 +0000889 // Generate the 'setter' function.
890 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000891 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
892 ObjCPropertyDecl::OBJC_PR_copy);
893 if (GenSetProperty && !objcSetPropertyDefined) {
894 objcSetPropertyDefined = true;
895 // FIXME. Is this attribute correct in all cases?
896 Setr = "\nextern \"C\" __declspec(dllimport) "
897 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
898 }
899
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000900 RewriteObjCMethodDecl(OID->getContainingInterface(),
901 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000902 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000903 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000904 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000905 if (GenSetProperty) {
906 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000907 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000908 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000909 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000910 Setr += ", ";
911 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
912 Setr += "0, ";
913 else
914 Setr += "1, ";
915 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
916 Setr += "1)";
917 else
918 Setr += "0)";
919 }
920 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000921 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000922 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000923 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000924 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000925 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000926}
Chris Lattner8a12c272007-10-11 18:38:32 +0000927
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000928static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
929 std::string &typedefString) {
930 typedefString += "#ifndef _REWRITER_typedef_";
931 typedefString += ForwardDecl->getNameAsString();
932 typedefString += "\n";
933 typedefString += "#define _REWRITER_typedef_";
934 typedefString += ForwardDecl->getNameAsString();
935 typedefString += "\n";
936 typedefString += "typedef struct objc_object ";
937 typedefString += ForwardDecl->getNameAsString();
938 typedefString += ";\n#endif\n";
939}
940
941void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
942 const std::string &typedefString) {
943 SourceLocation startLoc = ClassDecl->getLocation();
944 const char *startBuf = SM->getCharacterData(startLoc);
945 const char *semiPtr = strchr(startBuf, ';');
946 // Replace the @class with typedefs corresponding to the classes.
947 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
948}
949
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000950void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000951 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000952 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
953 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
954 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
955 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000956 // Translate to typedef's that forward reference structs with the same name
957 // as the class. As a convenience, we include the original declaration
958 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000959 typedefString += "// @class ";
960 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000961 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000962 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000963 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000964 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000965 DeclGroupRef::iterator I = D.begin();
966 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
967}
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000969void RewriteObjC::RewriteForwardClassDecl(
970 const llvm::SmallVector<Decl*, 8> &D) {
971 std::string typedefString;
972 for (unsigned i = 0; i < D.size(); i++) {
973 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
974 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
975 if (i == 0) {
976 typedefString += "// @class ";
977 typedefString += ForwardDecl->getNameAsString();
978 typedefString += ";\n";
979 }
980 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
981 }
982 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000983}
984
Steve Naroffb29b4272008-04-14 22:03:09 +0000985void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000986 // When method is a synthesized one, such as a getter/setter there is
987 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000988 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000989 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000990 SourceLocation LocStart = Method->getLocStart();
991 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Chandler Carruth64211622011-07-25 21:09:52 +0000993 if (SM->getExpansionLineNumber(LocEnd) >
994 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000995 InsertText(LocStart, "#if 0\n");
996 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000997 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000999 }
1000}
1001
Mike Stump1eb44332009-09-09 15:08:12 +00001002void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +00001003 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Benjamin Kramerd999b372010-02-14 14:14:16 +00001005 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001006 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001007}
1008
Steve Naroffb29b4272008-04-14 22:03:09 +00001009void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001010 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Steve Naroff423cb562007-10-30 13:30:57 +00001012 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001013 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001015 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1016 E = CatDecl->prop_end(); I != E; ++I)
1017 RewriteProperty(*I);
1018
Mike Stump1eb44332009-09-09 15:08:12 +00001019 for (ObjCCategoryDecl::instmeth_iterator
1020 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001021 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001022 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001023 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001024 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001025 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001026 RewriteMethodDeclaration(*I);
1027
Steve Naroff423cb562007-10-30 13:30:57 +00001028 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001029 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1030 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001031}
1032
Steve Naroffb29b4272008-04-14 22:03:09 +00001033void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001034 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Steve Naroff752d6ef2007-10-30 16:42:30 +00001036 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001037 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001038
1039 for (ObjCProtocolDecl::instmeth_iterator
1040 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001041 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001042 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001043 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001044 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001045 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001046 RewriteMethodDeclaration(*I);
1047
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001048 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1049 E = PDecl->prop_end(); I != E; ++I)
1050 RewriteProperty(*I);
1051
Steve Naroff752d6ef2007-10-30 16:42:30 +00001052 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001053 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001054 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001055
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001056 // Must comment out @optional/@required
1057 const char *startBuf = SM->getCharacterData(LocStart);
1058 const char *endBuf = SM->getCharacterData(LocEnd);
1059 for (const char *p = startBuf; p < endBuf; p++) {
1060 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001061 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001062 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001064 }
1065 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001066 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001067 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001069 }
1070 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001071}
1072
Steve Naroffb29b4272008-04-14 22:03:09 +00001073void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001074 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001075 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001076 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001077 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001078 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001079}
1080
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001081void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1082 const FunctionType *&FPRetType) {
1083 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001084 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001085 else if (T->isFunctionPointerType() ||
1086 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001087 // needs special handling, since pointer-to-functions have special
1088 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001089 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001090 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001091 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001092 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001093 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001094 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001095 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001096 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001097 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001098 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001099 }
1100 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001101 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001102}
1103
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001104void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1105 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001106 std::string &ResultStr) {
1107 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1108 const FunctionType *FPRetType = 0;
1109 ResultStr += "\nstatic ";
1110 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001111 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001113 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001114 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001116 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001117 NameStr += "_I_";
1118 else
1119 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001121 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001122 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001123
1124 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001125 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001126 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001127 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001130 {
1131 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 int len = selString.size();
1133 for (int i = 0; i < len; i++)
1134 if (selString[i] == ':')
1135 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001136 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001137 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001138 // Remember this name for metadata emission
1139 MethodInternalNames[OMD] = NameStr;
1140 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 // Rewrite arguments
1143 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001145 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001146 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001147 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001149 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001150 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001151 ResultStr += "struct ";
1152 }
1153 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001154 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001155 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 }
1157 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001158 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001159 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001161 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001162 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001165 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001166 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1167 E = OMD->param_end(); PI != E; ++PI) {
1168 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001170 if (PDecl->getType()->isObjCQualifiedIdType()) {
1171 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001172 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001173 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001174 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001175 QualType QT = PDecl->getType();
1176 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1177 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001178 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001179 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001180 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001181 ResultStr += Name;
1182 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001183 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001184 if (OMD->isVariadic())
1185 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001186 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Steve Naroff76e429d2008-07-16 14:40:40 +00001188 if (FPRetType) {
1189 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Steve Naroff76e429d2008-07-16 14:40:40 +00001191 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001192 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001193 ResultStr += "(";
1194 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1195 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001196 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001197 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001198 ResultStr += ParamStr;
1199 }
1200 if (FT->isVariadic()) {
1201 if (FT->getNumArgs()) ResultStr += ", ";
1202 ResultStr += "...";
1203 }
1204 ResultStr += ")";
1205 } else {
1206 ResultStr += "()";
1207 }
1208 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001209}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001210void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001211 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1212 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001214 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1218 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001219 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001222 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001224 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001225
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001226 const char *startBuf = SM->getCharacterData(LocStart);
1227 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001228 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 }
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001231 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001232 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1233 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001234 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001235 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001236 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001237 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001239 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001241 const char *startBuf = SM->getCharacterData(LocStart);
1242 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001243 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001244 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001245 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001246 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001247 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001248 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001249 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001250 }
1251
Benjamin Kramerd999b372010-02-14 14:14:16 +00001252 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001253}
1254
Steve Naroffb29b4272008-04-14 22:03:09 +00001255void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001256 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001257 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001258 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001259 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001260 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001261 ResultStr += "\n";
1262 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001263 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001264 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001265 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001266 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001267 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001268 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001269 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001270 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001271 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
1273 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001274 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001275 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001276 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001277 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001278 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001279 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001280 for (ObjCInterfaceDecl::classmeth_iterator
1281 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001282 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001283 RewriteMethodDeclaration(*I);
1284
Steve Naroff2feac5e2007-10-30 03:43:13 +00001285 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001286 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1287 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001288}
1289
John McCall4b9c2d22011-11-06 09:01:30 +00001290Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1291 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCall4b9c2d22011-11-06 09:01:30 +00001293 // We just magically know some things about the structure of this
1294 // expression.
1295 ObjCMessageExpr *OldMsg =
1296 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1297 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001298
John McCall4b9c2d22011-11-06 09:01:30 +00001299 // Because the rewriter doesn't allow us to rewrite rewritten code,
1300 // we need to suppress rewriting the sub-statements.
1301 Expr *Base, *RHS;
1302 {
1303 DisableReplaceStmtScope S(*this);
1304
1305 // Rebuild the base expression if we have one.
1306 Base = 0;
1307 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1308 Base = OldMsg->getInstanceReceiver();
1309 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1310 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1311 }
1312
1313 // Rebuild the RHS.
1314 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1315 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1316 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1317 }
1318
1319 // TODO: avoid this copy.
1320 SmallVector<SourceLocation, 1> SelLocs;
1321 OldMsg->getSelectorLocs(SelLocs);
1322
1323 ObjCMessageExpr *NewMsg;
1324 switch (OldMsg->getReceiverKind()) {
1325 case ObjCMessageExpr::Class:
1326 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1327 OldMsg->getValueKind(),
1328 OldMsg->getLeftLoc(),
1329 OldMsg->getClassReceiverTypeInfo(),
1330 OldMsg->getSelector(),
1331 SelLocs,
1332 OldMsg->getMethodDecl(),
1333 RHS,
1334 OldMsg->getRightLoc());
1335 break;
1336
1337 case ObjCMessageExpr::Instance:
1338 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1339 OldMsg->getValueKind(),
1340 OldMsg->getLeftLoc(),
1341 Base,
1342 OldMsg->getSelector(),
1343 SelLocs,
1344 OldMsg->getMethodDecl(),
1345 RHS,
1346 OldMsg->getRightLoc());
1347 break;
1348
1349 case ObjCMessageExpr::SuperClass:
1350 case ObjCMessageExpr::SuperInstance:
1351 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1352 OldMsg->getValueKind(),
1353 OldMsg->getLeftLoc(),
1354 OldMsg->getSuperLoc(),
1355 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1356 OldMsg->getSuperType(),
1357 OldMsg->getSelector(),
1358 SelLocs,
1359 OldMsg->getMethodDecl(),
1360 RHS,
1361 OldMsg->getRightLoc());
1362 break;
1363 }
1364
1365 Stmt *Replacement = SynthMessageExpr(NewMsg);
1366 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1367 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001368}
1369
John McCall4b9c2d22011-11-06 09:01:30 +00001370Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1371 SourceRange OldRange = PseudoOp->getSourceRange();
1372
1373 // We just magically know some things about the structure of this
1374 // expression.
1375 ObjCMessageExpr *OldMsg =
1376 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1377
1378 // Because the rewriter doesn't allow us to rewrite rewritten code,
1379 // we need to suppress rewriting the sub-statements.
1380 Expr *Base = 0;
1381 {
1382 DisableReplaceStmtScope S(*this);
1383
1384 // Rebuild the base expression if we have one.
1385 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1386 Base = OldMsg->getInstanceReceiver();
1387 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1388 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001389 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001390 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001391
John McCall4b9c2d22011-11-06 09:01:30 +00001392 // Intentionally empty.
1393 SmallVector<SourceLocation, 1> SelLocs;
1394 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001395
John McCall4b9c2d22011-11-06 09:01:30 +00001396 ObjCMessageExpr *NewMsg;
1397 switch (OldMsg->getReceiverKind()) {
1398 case ObjCMessageExpr::Class:
1399 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1400 OldMsg->getValueKind(),
1401 OldMsg->getLeftLoc(),
1402 OldMsg->getClassReceiverTypeInfo(),
1403 OldMsg->getSelector(),
1404 SelLocs,
1405 OldMsg->getMethodDecl(),
1406 Args,
1407 OldMsg->getRightLoc());
1408 break;
1409
1410 case ObjCMessageExpr::Instance:
1411 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1412 OldMsg->getValueKind(),
1413 OldMsg->getLeftLoc(),
1414 Base,
1415 OldMsg->getSelector(),
1416 SelLocs,
1417 OldMsg->getMethodDecl(),
1418 Args,
1419 OldMsg->getRightLoc());
1420 break;
1421
1422 case ObjCMessageExpr::SuperClass:
1423 case ObjCMessageExpr::SuperInstance:
1424 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1425 OldMsg->getValueKind(),
1426 OldMsg->getLeftLoc(),
1427 OldMsg->getSuperLoc(),
1428 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1429 OldMsg->getSuperType(),
1430 OldMsg->getSelector(),
1431 SelLocs,
1432 OldMsg->getMethodDecl(),
1433 Args,
1434 OldMsg->getRightLoc());
1435 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001436 }
John McCall4b9c2d22011-11-06 09:01:30 +00001437
1438 Stmt *Replacement = SynthMessageExpr(NewMsg);
1439 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1440 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001441}
1442
John McCall4b9c2d22011-11-06 09:01:30 +00001443Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
1444 SourceRange OldRange = IV->getSourceRange();
1445 Expr *BaseExpr = IV->getBase();
1446
1447 // Rewrite the base, but without actually doing replaces.
1448 {
1449 DisableReplaceStmtScope S(*this);
1450 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
1451 IV->setBase(BaseExpr);
1452 }
1453
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001454 ObjCIvarDecl *D = IV->getDecl();
John McCall4b9c2d22011-11-06 09:01:30 +00001455
1456 Expr *Replacement = IV;
Steve Naroff54055232008-10-27 17:20:55 +00001457 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001458 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001459 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001460 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001461 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001462 // lookup which class implements the instance variable.
1463 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001464 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001465 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001466 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Steve Narofff0757612008-05-08 17:52:16 +00001468 // Synthesize an explicit cast to gain access to the ivar.
1469 std::string RecName = clsDeclared->getIdentifier()->getName();
1470 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001471 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001472 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001473 SourceLocation(), SourceLocation(),
1474 II);
Steve Narofff0757612008-05-08 17:52:16 +00001475 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1476 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001478 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001479 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001480 // Don't forget the parens to enforce the proper binding.
John McCall4b9c2d22011-11-06 09:01:30 +00001481 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
1482 OldRange.getEnd(),
John McCallf89e55a2010-11-18 06:31:45 +00001483 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001484 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001485 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001486 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001487 IV->getLocation(),
1488 D->getType(),
1489 VK_LValue, OK_Ordinary);
John McCall4b9c2d22011-11-06 09:01:30 +00001490 Replacement = ME;
1491 } else {
1492 IV->setBase(PE);
Steve Naroffc2a689b2007-11-15 11:33:00 +00001493 }
1494 }
Steve Naroff84472a82008-04-18 21:55:08 +00001495 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001496 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Steve Naroff9f525972008-05-06 23:20:07 +00001498 // Explicit ivar refs need to have a cast inserted.
1499 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001500 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001501 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001502 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001503 // lookup which class implements the instance variable.
1504 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001505 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001506 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001507 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Steve Naroff9f525972008-05-06 23:20:07 +00001509 // Synthesize an explicit cast to gain access to the ivar.
1510 std::string RecName = clsDeclared->getIdentifier()->getName();
1511 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001512 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001513 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001514 SourceLocation(), SourceLocation(),
1515 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001516 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1517 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001518 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001519 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001520 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001521 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001522 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001523 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001524 // Cannot delete IV->getBase(), since PE points to it.
1525 // Replace the old base with the cast. This is important when doing
1526 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001527 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001528 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001529 }
Steve Naroff7e3411b2007-11-15 02:58:25 +00001530
John McCall4b9c2d22011-11-06 09:01:30 +00001531 ReplaceStmtWithRange(IV, Replacement, OldRange);
1532 return Replacement;
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001533}
1534
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001535/// SynthCountByEnumWithState - To print:
1536/// ((unsigned int (*)
1537/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001538/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001539/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001540/// "countByEnumeratingWithState:objects:count:"),
1541/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542/// (id *)items, (unsigned int)16)
1543///
Steve Naroffb29b4272008-04-14 22:03:09 +00001544void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001545 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1546 "id *, unsigned int))(void *)objc_msgSend)";
1547 buf += "\n\t\t";
1548 buf += "((id)l_collection,\n\t\t";
1549 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1550 buf += "\n\t\t";
1551 buf += "&enumState, "
1552 "(id *)items, (unsigned int)16)";
1553}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001554
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001555/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1556/// statement to exit to its outer synthesized loop.
1557///
Steve Naroffb29b4272008-04-14 22:03:09 +00001558Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001559 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1560 return S;
1561 // replace break with goto __break_label
1562 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001564 SourceLocation startLoc = S->getLocStart();
1565 buf = "goto __break_label_";
1566 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001567 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001568
1569 return 0;
1570}
1571
1572/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1573/// statement to continue with its inner synthesized loop.
1574///
Steve Naroffb29b4272008-04-14 22:03:09 +00001575Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001576 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1577 return S;
1578 // replace continue with goto __continue_label
1579 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001580
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001581 SourceLocation startLoc = S->getLocStart();
1582 buf = "goto __continue_label_";
1583 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001584 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001586 return 0;
1587}
1588
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001589/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001590/// It rewrites:
1591/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001593/// Into:
1594/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001595/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001596/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001597/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001598/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001599/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001600/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001601/// if (limit) {
1602/// unsigned long startMutations = *enumState.mutationsPtr;
1603/// do {
1604/// unsigned long counter = 0;
1605/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001606/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001607/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001608/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001609/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001610/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001611/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001612/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001613/// objects:items count:16]);
1614/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001615/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001616/// }
1617/// else
1618/// elem = nil;
1619/// }
1620///
Steve Naroffb29b4272008-04-14 22:03:09 +00001621Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001622 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001623 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001624 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001625 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001626 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001627 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001629 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001631 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001632 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 std::string buf;
1634 buf = "\n{\n\t";
1635 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1636 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001637 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001638 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001639 if (ElementType->isObjCQualifiedIdType() ||
1640 ElementType->isObjCQualifiedInterfaceType())
1641 // Simply use 'id' for all qualified types.
1642 elementTypeAsString = "id";
1643 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001644 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001645 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001646 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001647 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001648 buf += elementName;
1649 buf += ";\n\t";
1650 }
Chris Lattner06767512008-04-08 05:52:18 +00001651 else {
1652 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001653 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001654 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1655 if (VD->getType()->isObjCQualifiedIdType() ||
1656 VD->getType()->isObjCQualifiedInterfaceType())
1657 // Simply use 'id' for all qualified types.
1658 elementTypeAsString = "id";
1659 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001660 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001661 }
Mike Stump1eb44332009-09-09 15:08:12 +00001662
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001663 // struct __objcFastEnumerationState enumState = { 0 };
1664 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1665 // id items[16];
1666 buf += "id items[16];\n\t";
1667 // id l_collection = (id)
1668 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001669 // Find start location of 'collection' the hard way!
1670 const char *startCollectionBuf = startBuf;
1671 startCollectionBuf += 3; // skip 'for'
1672 startCollectionBuf = strchr(startCollectionBuf, '(');
1673 startCollectionBuf++; // skip '('
1674 // find 'in' and skip it.
1675 while (*startCollectionBuf != ' ' ||
1676 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1677 (*(startCollectionBuf+3) != ' ' &&
1678 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1679 startCollectionBuf++;
1680 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001681
1682 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001683 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001684 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001685 SourceLocation rightParenLoc = S->getRParenLoc();
1686 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001687 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001690 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1691 // objects:items count:16];
1692 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001693 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001694 // ((unsigned int (*)
1695 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001696 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001697 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001698 // "countByEnumeratingWithState:objects:count:"),
1699 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001700 // (id *)items, (unsigned int)16);
1701 buf += "unsigned long limit =\n\t\t";
1702 SynthCountByEnumWithState(buf);
1703 buf += ";\n\t";
1704 /// if (limit) {
1705 /// unsigned long startMutations = *enumState.mutationsPtr;
1706 /// do {
1707 /// unsigned long counter = 0;
1708 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001709 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001710 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001711 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001712 buf += "if (limit) {\n\t";
1713 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1714 buf += "do {\n\t\t";
1715 buf += "unsigned long counter = 0;\n\t\t";
1716 buf += "do {\n\t\t\t";
1717 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1718 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1719 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001720 buf += " = (";
1721 buf += elementTypeAsString;
1722 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001723 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001724 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001726 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001727 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001728 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001729 /// objects:items count:16]);
1730 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001731 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001732 /// }
1733 /// else
1734 /// elem = nil;
1735 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001736 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001737 buf = ";\n\t";
1738 buf += "__continue_label_";
1739 buf += utostr(ObjCBcLabelNo.back());
1740 buf += ": ;";
1741 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001742 buf += "} while (counter < limit);\n\t";
1743 buf += "} while (limit = ";
1744 SynthCountByEnumWithState(buf);
1745 buf += ");\n\t";
1746 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001747 buf += " = ((";
1748 buf += elementTypeAsString;
1749 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001750 buf += "__break_label_";
1751 buf += utostr(ObjCBcLabelNo.back());
1752 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001753 buf += "}\n\t";
1754 buf += "else\n\t\t";
1755 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001756 buf += " = ((";
1757 buf += elementTypeAsString;
1758 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001759 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001762 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001763 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001764 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001765 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001766 } else {
1767 /* Need to treat single statements specially. For example:
1768 *
1769 * for (A *a in b) if (stuff()) break;
1770 * for (A *a in b) xxxyy;
1771 *
1772 * The following code simply scans ahead to the semi to find the actual end.
1773 */
1774 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1775 const char *semiBuf = strchr(stmtBuf, ';');
1776 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001777 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001778 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001779 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001780 Stmts.pop_back();
1781 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001782 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001783}
1784
Mike Stump1eb44332009-09-09 15:08:12 +00001785/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001786/// This routine rewrites @synchronized(expr) stmt;
1787/// into:
1788/// objc_sync_enter(expr);
1789/// @try stmt @finally { objc_sync_exit(expr); }
1790///
Steve Naroffb29b4272008-04-14 22:03:09 +00001791Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001792 // Get the start location and compute the semi location.
1793 SourceLocation startLoc = S->getLocStart();
1794 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001796 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001797
1798 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001799 buf = "objc_sync_enter((id)";
1800 const char *lparenBuf = startBuf;
1801 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001802 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001803 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1804 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001805 // been rewritten! (which implies the SourceLocation's are invalid).
1806 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001807 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001808 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001809 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001810 buf = ");\n";
1811 // declare a new scope with two variables, _stack and _rethrow.
1812 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1813 buf += "int buf[18/*32-bit i386*/];\n";
1814 buf += "char *pointers[4];} _stack;\n";
1815 buf += "id volatile _rethrow = 0;\n";
1816 buf += "objc_exception_try_enter(&_stack);\n";
1817 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001818 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001819 startLoc = S->getSynchBody()->getLocEnd();
1820 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Steve Naroffc7089f12008-08-19 13:04:19 +00001822 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001823 SourceLocation lastCurlyLoc = startLoc;
1824 buf = "}\nelse {\n";
1825 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001826 buf += "}\n";
1827 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001828 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001829
1830 std::string syncBuf;
1831 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001832
1833 Expr *syncExpr = S->getSynchExpr();
1834 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1835 ? CK_BitCast :
1836 syncExpr->getType()->isBlockPointerType()
1837 ? CK_BlockPointerToObjCPointerCast
1838 : CK_CPointerToObjCPointerCast;
1839 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1840 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001841 std::string syncExprBufS;
1842 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001843 syncExpr->printPretty(syncExprBuf, *Context, 0,
1844 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001845 syncBuf += syncExprBuf.str();
1846 syncBuf += ");";
1847
1848 buf += syncBuf;
1849 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001850 buf += "}\n";
1851 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Benjamin Kramerd999b372010-02-14 14:14:16 +00001853 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001854
1855 bool hasReturns = false;
1856 HasReturnStmts(S->getSynchBody(), hasReturns);
1857 if (hasReturns)
1858 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1859
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001860 return 0;
1861}
1862
Steve Naroffb85e77a2009-12-05 21:43:12 +00001863void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1864{
Steve Naroff8c565152008-12-05 17:03:39 +00001865 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001866 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001867 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001868 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001869
Steve Naroffb85e77a2009-12-05 21:43:12 +00001870 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001871 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001872 TryFinallyContainsReturnDiag);
1873 }
1874 return;
1875}
1876
Steve Naroffb85e77a2009-12-05 21:43:12 +00001877void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1878{
1879 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001880 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001881 if (*CI)
1882 HasReturnStmts(*CI, hasReturns);
1883
1884 if (isa<ReturnStmt>(S))
1885 hasReturns = true;
1886 return;
1887}
1888
1889void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1890 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001891 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001892 if (*CI) {
1893 RewriteTryReturnStmts(*CI);
1894 }
1895 if (isa<ReturnStmt>(S)) {
1896 SourceLocation startLoc = S->getLocStart();
1897 const char *startBuf = SM->getCharacterData(startLoc);
1898
1899 const char *semiBuf = strchr(startBuf, ';');
1900 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001901 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001902
1903 std::string buf;
1904 buf = "{ objc_exception_try_exit(&_stack); return";
1905
Benjamin Kramerd999b372010-02-14 14:14:16 +00001906 ReplaceText(startLoc, 6, buf);
1907 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001908 }
1909 return;
1910}
1911
1912void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1913 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001914 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001915 if (*CI) {
1916 RewriteSyncReturnStmts(*CI, syncExitBuf);
1917 }
1918 if (isa<ReturnStmt>(S)) {
1919 SourceLocation startLoc = S->getLocStart();
1920 const char *startBuf = SM->getCharacterData(startLoc);
1921
1922 const char *semiBuf = strchr(startBuf, ';');
1923 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001924 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001925
1926 std::string buf;
1927 buf = "{ objc_exception_try_exit(&_stack);";
1928 buf += syncExitBuf;
1929 buf += " return";
1930
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 ReplaceText(startLoc, 6, buf);
1932 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001933 }
1934 return;
1935}
1936
Steve Naroffb29b4272008-04-14 22:03:09 +00001937Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001938 // Get the start location and compute the semi location.
1939 SourceLocation startLoc = S->getLocStart();
1940 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Steve Naroff75730982007-11-07 04:08:17 +00001942 assert((*startBuf == '@') && "bogus @try location");
1943
1944 std::string buf;
1945 // declare a new scope with two variables, _stack and _rethrow.
1946 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1947 buf += "int buf[18/*32-bit i386*/];\n";
1948 buf += "char *pointers[4];} _stack;\n";
1949 buf += "id volatile _rethrow = 0;\n";
1950 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001951 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001952
Benjamin Kramerd999b372010-02-14 14:14:16 +00001953 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroff75730982007-11-07 04:08:17 +00001955 startLoc = S->getTryBody()->getLocEnd();
1956 startBuf = SM->getCharacterData(startLoc);
1957
1958 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Steve Naroff75730982007-11-07 04:08:17 +00001960 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001961 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001962 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001963 buf = " /* @catch begin */ else {\n";
1964 buf += " id _caught = objc_exception_extract(&_stack);\n";
1965 buf += " objc_exception_try_enter (&_stack);\n";
1966 buf += " if (_setjmp(_stack.buf))\n";
1967 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1968 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Benjamin Kramerd999b372010-02-14 14:14:16 +00001970 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001971 } else { /* no catch list */
1972 buf = "}\nelse {\n";
1973 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1974 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001975 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001976 }
Steve Naroff75730982007-11-07 04:08:17 +00001977 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001978 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1979 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001980 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001981
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001982 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001983 buf = "if ("; // we are generating code for the first catch clause
1984 else
1985 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001986 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001987 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001988
Steve Naroff75730982007-11-07 04:08:17 +00001989 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Steve Naroff75730982007-11-07 04:08:17 +00001991 const char *lParenLoc = strchr(startBuf, '(');
1992
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001993 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001994 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001995 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001996 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1997 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001998 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001999 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002000 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Steve Naroffe12e6922008-02-01 20:02:07 +00002002 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002003 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002004 } else if (catchDecl) {
2005 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002006 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002007 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002008 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002009 } else if (const ObjCObjectPointerType *Ptr =
2010 t->getAs<ObjCObjectPointerType>()) {
2011 // Should be a pointer to a class.
2012 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2013 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002014 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002015 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002016 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002017 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002018 }
2019 }
2020 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002021 lastCatchBody = Catch->getCatchBody();
2022 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002023 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2024 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2025 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2026 assert((*rParenBuf == ')') && "bogus @catch paren location");
2027 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Mike Stump1eb44332009-09-09 15:08:12 +00002029 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002030 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002031 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002032 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002033 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002034 }
Steve Naroff75730982007-11-07 04:08:17 +00002035 }
2036 // Complete the catch list...
2037 if (lastCatchBody) {
2038 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002039 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2040 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Steve Naroff378f47a2008-09-11 15:29:03 +00002042 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002043 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002044 buf = "} /* last catch end */\n";
2045 buf += "else {\n";
2046 buf += " _rethrow = _caught;\n";
2047 buf += " objc_exception_try_exit(&_stack);\n";
2048 buf += "} } /* @catch end */\n";
2049 if (!S->getFinallyStmt())
2050 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002051 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Steve Naroff75730982007-11-07 04:08:17 +00002053 // Set lastCurlyLoc
2054 lastCurlyLoc = lastCatchBody->getLocEnd();
2055 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002056 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002057 startLoc = finalStmt->getLocStart();
2058 startBuf = SM->getCharacterData(startLoc);
2059 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Benjamin Kramerd999b372010-02-14 14:14:16 +00002061 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Steve Naroff75730982007-11-07 04:08:17 +00002063 Stmt *body = finalStmt->getFinallyBody();
2064 SourceLocation startLoc = body->getLocStart();
2065 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002066 assert(*SM->getCharacterData(startLoc) == '{' &&
2067 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002068 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002069 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002071 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002072 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002073 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002074 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroff75730982007-11-07 04:08:17 +00002076 // Set lastCurlyLoc
2077 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Steve Naroff8c565152008-12-05 17:03:39 +00002079 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002080 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002081 } else { /* no finally clause - make sure we synthesize an implicit one */
2082 buf = "{ /* implicit finally clause */\n";
2083 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2084 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2085 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002086 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002087
2088 // Now check for any return/continue/go statements within the @try.
2089 // The implicit finally clause won't called if the @try contains any
2090 // jump statements.
2091 bool hasReturns = false;
2092 HasReturnStmts(S->getTryBody(), hasReturns);
2093 if (hasReturns)
2094 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002095 }
2096 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002097 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002098 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002099 return 0;
2100}
2101
Mike Stump1eb44332009-09-09 15:08:12 +00002102// This can't be done with ReplaceStmt(S, ThrowExpr), since
2103// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002104// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002105Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002106 // Get the start location and compute the semi location.
2107 SourceLocation startLoc = S->getLocStart();
2108 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Steve Naroff2bd03922007-11-07 15:32:26 +00002110 assert((*startBuf == '@') && "bogus @throw location");
2111
2112 std::string buf;
2113 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002114 if (S->getThrowExpr())
2115 buf = "objc_exception_throw(";
2116 else // add an implicit argument
2117 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002119 // handle "@ throw" correctly.
2120 const char *wBuf = strchr(startBuf, 'w');
2121 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002122 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Steve Naroff2bd03922007-11-07 15:32:26 +00002124 const char *semiBuf = strchr(startBuf, ';');
2125 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002126 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002127 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002128 return 0;
2129}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002130
Steve Naroffb29b4272008-04-14 22:03:09 +00002131Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002132 // Create a new string expression.
2133 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002134 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002135 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002136 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002137 StringLiteral::Ascii, false,
2138 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002139 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Chris Lattner07506182007-11-30 22:53:43 +00002141 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002142 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002143 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002144}
2145
Steve Naroffb29b4272008-04-14 22:03:09 +00002146Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002147 if (!SelGetUidFunctionDecl)
2148 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002149 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2150 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002151 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002152 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002153 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002154 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002155 StringLiteral::Ascii, false,
2156 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002157 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2158 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002159 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002160 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002161 return SelExp;
2162}
2163
Steve Naroffb29b4272008-04-14 22:03:09 +00002164CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002165 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2166 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002167 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002168 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Steve Naroffebf2b562007-10-23 23:50:29 +00002170 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002171 DeclRefExpr *DRE =
2172 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Steve Naroffebf2b562007-10-23 23:50:29 +00002174 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002175 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002176 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002177 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002178 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002179
John McCall183700f2009-09-21 23:43:11 +00002180 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002182 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002183 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002184 FT->getCallResultType(*Context),
2185 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002186 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002187}
2188
Steve Naroffd5255f52007-11-01 13:24:47 +00002189static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2190 const char *&startRef, const char *&endRef) {
2191 while (startBuf < endBuf) {
2192 if (*startBuf == '<')
2193 startRef = startBuf; // mark the start.
2194 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002195 if (startRef && *startRef == '<') {
2196 endRef = startBuf; // mark the end.
2197 return true;
2198 }
2199 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002200 }
2201 startBuf++;
2202 }
2203 return false;
2204}
2205
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002206static void scanToNextArgument(const char *&argRef) {
2207 int angle = 0;
2208 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2209 if (*argRef == '<')
2210 angle++;
2211 else if (*argRef == '>')
2212 angle--;
2213 argRef++;
2214 }
2215 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2216}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002217
Steve Naroffb29b4272008-04-14 22:03:09 +00002218bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002219 if (T->isObjCQualifiedIdType())
2220 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002221 if (const PointerType *PT = T->getAs<PointerType>()) {
2222 if (PT->getPointeeType()->isObjCQualifiedIdType())
2223 return true;
2224 }
2225 if (T->isObjCObjectPointerType()) {
2226 T = T->getPointeeType();
2227 return T->isObjCQualifiedInterfaceType();
2228 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002229 if (T->isArrayType()) {
2230 QualType ElemTy = Context->getBaseElementType(T);
2231 return needToScanForQualifiers(ElemTy);
2232 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002233 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002234}
2235
Steve Naroff4f95b752008-07-29 18:15:38 +00002236void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2237 QualType Type = E->getType();
2238 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002239 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Steve Naroffcda658e2008-11-19 21:15:47 +00002241 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2242 Loc = ECE->getLParenLoc();
2243 EndLoc = ECE->getRParenLoc();
2244 } else {
2245 Loc = E->getLocStart();
2246 EndLoc = E->getLocEnd();
2247 }
2248 // This will defend against trying to rewrite synthesized expressions.
2249 if (Loc.isInvalid() || EndLoc.isInvalid())
2250 return;
2251
Steve Naroff4f95b752008-07-29 18:15:38 +00002252 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002253 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002254 const char *startRef = 0, *endRef = 0;
2255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002257 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2258 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002259 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002262 }
2263 }
2264}
2265
Steve Naroffb29b4272008-04-14 22:03:09 +00002266void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002267 SourceLocation Loc;
2268 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002269 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002270 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2271 Loc = VD->getLocation();
2272 Type = VD->getType();
2273 }
2274 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2275 Loc = FD->getLocation();
2276 // Check for ObjC 'id' and class types that have been adorned with protocol
2277 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002278 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002279 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002280 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002281 if (!proto)
2282 return;
2283 Type = proto->getResultType();
2284 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002285 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2286 Loc = FD->getLocation();
2287 Type = FD->getType();
2288 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002289 else
2290 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002291
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002292 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002293 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Steve Naroffd5255f52007-11-01 13:24:47 +00002295 const char *endBuf = SM->getCharacterData(Loc);
2296 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002297 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002298 startBuf--; // scan backward (from the decl location) for return type.
2299 const char *startRef = 0, *endRef = 0;
2300 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2301 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002302 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2303 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002304 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002305 InsertText(LessLoc, "/*");
2306 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002307 }
2308 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002309 if (!proto)
2310 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002311 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002312 const char *startBuf = SM->getCharacterData(Loc);
2313 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002314 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2315 if (needToScanForQualifiers(proto->getArgType(i))) {
2316 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002317
Steve Naroffd5255f52007-11-01 13:24:47 +00002318 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002319 // scan forward (from the decl location) for argument types.
2320 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002321 const char *startRef = 0, *endRef = 0;
2322 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2323 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002324 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002325 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002326 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002327 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002328 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002329 InsertText(LessLoc, "/*");
2330 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002331 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002332 startBuf = ++endBuf;
2333 }
2334 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002335 // If the function name is derived from a macro expansion, then the
2336 // argument buffer will not follow the name. Need to speak with Chris.
2337 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002338 startBuf++; // scan forward (from the decl location) for argument types.
2339 startBuf++;
2340 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002341 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002342}
2343
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002344void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2345 QualType QT = ND->getType();
2346 const Type* TypePtr = QT->getAs<Type>();
2347 if (!isa<TypeOfExprType>(TypePtr))
2348 return;
2349 while (isa<TypeOfExprType>(TypePtr)) {
2350 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2351 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2352 TypePtr = QT->getAs<Type>();
2353 }
2354 // FIXME. This will not work for multiple declarators; as in:
2355 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002356 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002357 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2358 const char *startBuf = SM->getCharacterData(DeclLoc);
2359 if (ND->getInit()) {
2360 std::string Name(ND->getNameAsString());
2361 TypeAsString += " " + Name + " = ";
2362 Expr *E = ND->getInit();
2363 SourceLocation startLoc;
2364 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2365 startLoc = ECE->getLParenLoc();
2366 else
2367 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002368 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002369 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002370 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002371 }
2372 else {
2373 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002374 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002375 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002376 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002377 }
2378}
2379
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002380// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002381void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002382 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002383 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002384 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002385 QualType getFuncType =
2386 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002387 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002388 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002389 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002390 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002391 SC_Extern,
2392 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002393}
2394
Steve Naroffb29b4272008-04-14 22:03:09 +00002395void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002396 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002397 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002398 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002399 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002400 return;
2401 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002402 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002403}
2404
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002405void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002406 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002407 const char *argPtr = TypeString.c_str();
2408 if (!strchr(argPtr, '^')) {
2409 Str += TypeString;
2410 return;
2411 }
2412 while (*argPtr) {
2413 Str += (*argPtr == '^' ? '*' : *argPtr);
2414 argPtr++;
2415 }
2416}
2417
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002418// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002419void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2420 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002421 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002422 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002423 const char *argPtr = TypeString.c_str();
2424 int paren = 0;
2425 while (*argPtr) {
2426 switch (*argPtr) {
2427 case '(':
2428 Str += *argPtr;
2429 paren++;
2430 break;
2431 case ')':
2432 Str += *argPtr;
2433 paren--;
2434 break;
2435 case '^':
2436 Str += '*';
2437 if (paren == 1)
2438 Str += VD->getNameAsString();
2439 break;
2440 default:
2441 Str += *argPtr;
2442 break;
2443 }
2444 argPtr++;
2445 }
2446}
2447
2448
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002449void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2450 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2451 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2452 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2453 if (!proto)
2454 return;
2455 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002456 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002457 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002458 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002459 FdStr += "(";
2460 unsigned numArgs = proto->getNumArgs();
2461 for (unsigned i = 0; i < numArgs; i++) {
2462 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002463 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002464 if (i+1 < numArgs)
2465 FdStr += ", ";
2466 }
2467 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002468 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002469 CurFunctionDeclToDeclareForBlock = 0;
2470}
2471
Steve Naroffc0a123c2008-03-11 17:37:02 +00002472// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002473void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002474 if (SuperContructorFunctionDecl)
2475 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002476 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002477 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002478 QualType argT = Context->getObjCIdType();
2479 assert(!argT.isNull() && "Can't find 'id' type");
2480 ArgTys.push_back(argT);
2481 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002482 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2483 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002484 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002485 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002486 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002487 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002488 SC_Extern,
2489 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002490}
2491
Steve Naroff09b266e2007-10-30 23:14:51 +00002492// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002493void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002495 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002496 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002497 assert(!argT.isNull() && "Can't find 'id' type");
2498 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002499 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002502 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2503 &ArgTys[0], ArgTys.size(),
2504 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002505 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002506 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002507 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002508 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002509 SC_Extern,
2510 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002511}
2512
Steve Naroff874e2322007-11-15 10:28:18 +00002513// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002514void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002515 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002516 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002517 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002518 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002519 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002520 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2521 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2522 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002524 assert(!argT.isNull() && "Can't find 'SEL' type");
2525 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002526 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2527 &ArgTys[0], ArgTys.size(),
2528 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002529 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002530 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002531 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002532 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002533 SC_Extern,
2534 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002535}
2536
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002537// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002538void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002539 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002540 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002541 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002542 assert(!argT.isNull() && "Can't find 'id' type");
2543 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002544 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545 assert(!argT.isNull() && "Can't find 'SEL' type");
2546 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002547 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002548 &ArgTys[0], ArgTys.size(),
2549 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002550 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002551 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002552 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002553 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002554 SC_Extern,
2555 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002556}
2557
Mike Stump1eb44332009-09-09 15:08:12 +00002558// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002559// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002560void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002561 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002563 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002564 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002565 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002566 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002567 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2568 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2569 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002570 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571 assert(!argT.isNull() && "Can't find 'SEL' type");
2572 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002573 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002574 &ArgTys[0], ArgTys.size(),
2575 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002576 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002577 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002578 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002579 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002580 SC_Extern,
2581 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002582}
2583
Steve Naroff1284db82008-05-08 22:02:18 +00002584// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002585void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002586 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002587 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002588 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002589 assert(!argT.isNull() && "Can't find 'id' type");
2590 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002591 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002592 assert(!argT.isNull() && "Can't find 'SEL' type");
2593 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002594 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2595 &ArgTys[0], ArgTys.size(),
2596 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002597 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002598 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002599 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002600 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002601 SC_Extern,
2602 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002603}
2604
Steve Naroff09b266e2007-10-30 23:14:51 +00002605// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002606void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002608 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002609 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002610 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2611 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002612 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002613 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002614 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002615 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002616 SC_Extern,
2617 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002618}
2619
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002620// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2621void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2622 IdentifierInfo *getSuperClassIdent =
2623 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002624 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002625 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002626 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2627 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002628 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002629 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002630 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002631 getSuperClassIdent,
2632 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002633 SC_Extern,
2634 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002635 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002636}
2637
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002638// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002639void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002640 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002641 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002642 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002643 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2644 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002645 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002646 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002647 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002648 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002649 SC_Extern,
2650 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002651}
2652
Steve Naroffb29b4272008-04-14 22:03:09 +00002653Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002654 QualType strType = getConstantStringStructType();
2655
2656 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002657
2658 std::string tmpName = InFileName;
2659 unsigned i;
2660 for (i=0; i < tmpName.length(); i++) {
2661 char c = tmpName.at(i);
2662 // replace any non alphanumeric characters with '_'.
2663 if (!isalpha(c) && (c < '0' || c > '9'))
2664 tmpName[i] = '_';
2665 }
2666 S += tmpName;
2667 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002668 S += utostr(NumObjCStringLiterals++);
2669
Steve Naroffba92b2e2008-03-27 22:29:16 +00002670 Preamble += "static __NSConstantStringImpl " + S;
2671 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2672 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002673 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002674 std::string prettyBufS;
2675 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002676 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2677 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002678 Preamble += prettyBuf.str();
2679 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002680 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002681
2682 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002683 SourceLocation(), &Context->Idents.get(S),
2684 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002685 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2686 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002687 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002688 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002689 VK_RValue, OK_Ordinary,
2690 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002691 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002692 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002693 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002694 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002695 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002696 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002697}
2698
Steve Naroff874e2322007-11-15 10:28:18 +00002699// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002700QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002701 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002702 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002703 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002704 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002705 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Steve Naroff874e2322007-11-15 10:28:18 +00002707 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002708 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002709 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002710 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002711
Steve Naroff874e2322007-11-15 10:28:18 +00002712 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002713 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002714 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002715 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002716 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002717 FieldTypes[i], 0,
2718 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002719 /*Mutable=*/false,
2720 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002721 }
Mike Stump1eb44332009-09-09 15:08:12 +00002722
Douglas Gregor838db382010-02-11 01:19:42 +00002723 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002724 }
2725 return Context->getTagDeclType(SuperStructDecl);
2726}
2727
Steve Naroffb29b4272008-04-14 22:03:09 +00002728QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002729 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002730 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002731 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002732 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002733 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002735 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002736 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002737 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002738 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002739 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002740 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002741 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002742 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002743
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002744 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002745 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002746 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2747 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002748 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002749 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002750 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002751 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002752 /*Mutable=*/true,
2753 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002754 }
2755
Douglas Gregor838db382010-02-11 01:19:42 +00002756 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002757 }
2758 return Context->getTagDeclType(ConstantStringDecl);
2759}
2760
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002761Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2762 SourceLocation StartLoc,
2763 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002764 if (!SelGetUidFunctionDecl)
2765 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002766 if (!MsgSendFunctionDecl)
2767 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002768 if (!MsgSendSuperFunctionDecl)
2769 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002770 if (!MsgSendStretFunctionDecl)
2771 SynthMsgSendStretFunctionDecl();
2772 if (!MsgSendSuperStretFunctionDecl)
2773 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002774 if (!MsgSendFpretFunctionDecl)
2775 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002776 if (!GetClassFunctionDecl)
2777 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002778 if (!GetSuperClassFunctionDecl)
2779 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002780 if (!GetMetaClassFunctionDecl)
2781 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002782
Steve Naroff874e2322007-11-15 10:28:18 +00002783 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002784 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2785 // May need to use objc_msgSend_stret() as well.
2786 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002787 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2788 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002789 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002790 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002791 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002792 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002793 }
Mike Stump1eb44332009-09-09 15:08:12 +00002794
Steve Naroff934f2762007-10-24 22:48:43 +00002795 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002796 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002797 switch (Exp->getReceiverKind()) {
2798 case ObjCMessageExpr::SuperClass: {
2799 MsgSendFlavor = MsgSendSuperFunctionDecl;
2800 if (MsgSendStretFlavor)
2801 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2802 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Douglas Gregor04badcf2010-04-21 00:45:42 +00002804 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002805
Chris Lattner5f9e2722011-07-23 10:55:15 +00002806 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002807
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 // set the receiver to self, the first argument to all methods.
2809 InitExprs.push_back(
2810 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002811 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002812 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002813 Context->getObjCIdType(),
2814 VK_RValue,
2815 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002816 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002817
Douglas Gregor04badcf2010-04-21 00:45:42 +00002818 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002819 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002820 QualType argType = Context->getPointerType(Context->CharTy);
2821 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002822 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002823 StringLiteral::Ascii, false,
2824 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002825 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2826 &ClsExprs[0],
2827 ClsExprs.size(),
2828 StartLoc,
2829 EndLoc);
2830 // (Class)objc_getClass("CurrentClass")
2831 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2832 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002833 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002834 ClsExprs.clear();
2835 ClsExprs.push_back(ArgExpr);
2836 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2837 &ClsExprs[0], ClsExprs.size(),
2838 StartLoc, EndLoc);
2839
2840 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2841 // To turn off a warning, type-cast to 'id'
2842 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2843 NoTypeInfoCStyleCastExpr(Context,
2844 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002845 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002846 // struct objc_super
2847 QualType superType = getSuperStructType();
2848 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002849
Francois Pichet62ec1f22011-09-17 17:15:52 +00002850 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002851 SynthSuperContructorFunctionDecl();
2852 // Simulate a contructor call...
2853 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002854 superType, VK_LValue,
2855 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002856 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2857 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002858 superType, VK_LValue,
2859 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002860 // The code for super is a little tricky to prevent collision with
2861 // the structure definition in the header. The rewriter has it's own
2862 // internal definition (__rw_objc_super) that is uses. This is why
2863 // we need the cast below. For example:
2864 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2865 //
John McCall2de56d12010-08-25 11:45:40 +00002866 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002867 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002868 VK_RValue, OK_Ordinary,
2869 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002870 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2871 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002872 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002873 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002874 // (struct objc_super) { <exprs from above> }
2875 InitListExpr *ILE =
2876 new (Context) InitListExpr(*Context, SourceLocation(),
2877 &InitExprs[0], InitExprs.size(),
2878 SourceLocation());
2879 TypeSourceInfo *superTInfo
2880 = Context->getTrivialTypeSourceInfo(superType);
2881 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002882 superType, VK_LValue,
2883 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002884 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002885 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002886 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002887 VK_RValue, OK_Ordinary,
2888 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002889 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002890 MsgExprs.push_back(SuperRep);
2891 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002892 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002893
2894 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002895 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002896 QualType argType = Context->getPointerType(Context->CharTy);
2897 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002898 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002899 IdentifierInfo *clsName = Class->getIdentifier();
2900 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002901 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002902 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002903 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002904 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2905 &ClsExprs[0],
2906 ClsExprs.size(),
2907 StartLoc, EndLoc);
2908 MsgExprs.push_back(Cls);
2909 break;
2910 }
2911
2912 case ObjCMessageExpr::SuperInstance:{
2913 MsgSendFlavor = MsgSendSuperFunctionDecl;
2914 if (MsgSendStretFlavor)
2915 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2916 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2917 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002918 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002919
2920 InitExprs.push_back(
2921 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002922 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002924 Context->getObjCIdType(),
2925 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002926 ); // set the 'receiver'.
2927
2928 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002929 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002930 QualType argType = Context->getPointerType(Context->CharTy);
2931 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002932 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002933 StringLiteral::Ascii, false, argType,
2934 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002935 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2936 &ClsExprs[0],
2937 ClsExprs.size(),
2938 StartLoc, EndLoc);
2939 // (Class)objc_getClass("CurrentClass")
2940 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2941 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002942 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002943 ClsExprs.clear();
2944 ClsExprs.push_back(ArgExpr);
2945 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2946 &ClsExprs[0], ClsExprs.size(),
2947 StartLoc, EndLoc);
2948
2949 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2950 // To turn off a warning, type-cast to 'id'
2951 InitExprs.push_back(
2952 // set 'super class', using class_getSuperclass().
2953 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002954 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 // struct objc_super
2956 QualType superType = getSuperStructType();
2957 Expr *SuperRep;
2958
Francois Pichet62ec1f22011-09-17 17:15:52 +00002959 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002960 SynthSuperContructorFunctionDecl();
2961 // Simulate a contructor call...
2962 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002963 superType, VK_LValue,
2964 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002965 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2966 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002967 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002968 // The code for super is a little tricky to prevent collision with
2969 // the structure definition in the header. The rewriter has it's own
2970 // internal definition (__rw_objc_super) that is uses. This is why
2971 // we need the cast below. For example:
2972 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2973 //
John McCall2de56d12010-08-25 11:45:40 +00002974 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002975 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002976 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002977 SourceLocation());
2978 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2979 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002980 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002981 } else {
2982 // (struct objc_super) { <exprs from above> }
2983 InitListExpr *ILE =
2984 new (Context) InitListExpr(*Context, SourceLocation(),
2985 &InitExprs[0], InitExprs.size(),
2986 SourceLocation());
2987 TypeSourceInfo *superTInfo
2988 = Context->getTrivialTypeSourceInfo(superType);
2989 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002990 superType, VK_RValue, ILE,
2991 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002992 }
2993 MsgExprs.push_back(SuperRep);
2994 break;
2995 }
2996
2997 case ObjCMessageExpr::Instance: {
2998 // Remove all type-casts because it may contain objc-style types; e.g.
2999 // Foo<Proto> *.
3000 Expr *recExpr = Exp->getInstanceReceiver();
3001 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3002 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003003 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3004 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3005 ? CK_BlockPointerToObjCPointerCast
3006 : CK_CPointerToObjCPointerCast;
3007
Douglas Gregor04badcf2010-04-21 00:45:42 +00003008 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003009 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003010 MsgExprs.push_back(recExpr);
3011 break;
3012 }
3013 }
3014
Steve Naroffbeaf2992007-11-03 11:27:19 +00003015 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003016 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003017 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003018 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003019 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003020 StringLiteral::Ascii, false,
3021 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003022 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003023 &SelExprs[0], SelExprs.size(),
3024 StartLoc,
3025 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003026 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Steve Naroff934f2762007-10-24 22:48:43 +00003028 // Now push any user supplied arguments.
3029 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003030 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003031 // Make all implicit casts explicit...ICE comes in handy:-)
3032 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3033 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003034 QualType type = ICE->getType();
3035 if (needToScanForQualifiers(type))
3036 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003037 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003038 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003039 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003040 CastKind CK;
3041 if (SubExpr->getType()->isIntegralType(*Context) &&
3042 type->isBooleanType()) {
3043 CK = CK_IntegralToBoolean;
3044 } else if (type->isObjCObjectPointerType()) {
3045 if (SubExpr->getType()->isBlockPointerType()) {
3046 CK = CK_BlockPointerToObjCPointerCast;
3047 } else if (SubExpr->getType()->isPointerType()) {
3048 CK = CK_CPointerToObjCPointerCast;
3049 } else {
3050 CK = CK_BitCast;
3051 }
3052 } else {
3053 CK = CK_BitCast;
3054 }
3055
3056 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003057 }
3058 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003059 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003060 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003061 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003062 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003063 CastKind CK;
3064 if (userExpr->getType()->isIntegralType(*Context)) {
3065 CK = CK_IntegralToPointer;
3066 } else if (userExpr->getType()->isBlockPointerType()) {
3067 CK = CK_BlockPointerToObjCPointerCast;
3068 } else if (userExpr->getType()->isPointerType()) {
3069 CK = CK_CPointerToObjCPointerCast;
3070 } else {
3071 CK = CK_BitCast;
3072 }
John McCall9d125032010-01-15 18:39:57 +00003073 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003074 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003077 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003078 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3079 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003080 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003081 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003082 }
Steve Naroffab972d32007-11-04 22:37:50 +00003083 // Generate the funky cast.
3084 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003085 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003086 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Steve Naroffab972d32007-11-04 22:37:50 +00003088 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003089 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3090 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3091 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003092 ArgTypes.push_back(Context->getObjCIdType());
3093 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003094 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003095 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003096 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3097 E = OMD->param_end(); PI != E; ++PI) {
3098 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003099 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003100 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003101 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003102 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003103 ArgTypes.push_back(t);
3104 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003105 returnType = Exp->getType();
3106 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003107 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003108 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003109 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003110 }
3111 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003112 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003113
Steve Naroffab972d32007-11-04 22:37:50 +00003114 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003115 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003116 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003117
Mike Stump1eb44332009-09-09 15:08:12 +00003118 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003119 // If we don't do this cast, we get the following bizarre warning/note:
3120 // xx.m:13: warning: function called through a non-compatible type
3121 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003122 cast = NoTypeInfoCStyleCastExpr(Context,
3123 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003124 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003125
Steve Naroffab972d32007-11-04 22:37:50 +00003126 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003127 QualType castType =
3128 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3129 // If we don't have a method decl, force a variadic cast.
3130 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003131 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003132 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003133 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003134
3135 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003136 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003137
John McCall183700f2009-09-21 23:43:11 +00003138 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003139 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003140 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003141 FT->getResultType(), VK_RValue,
3142 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003143 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003144 if (MsgSendStretFlavor) {
3145 // We have the method which returns a struct/union. Must also generate
3146 // call to objc_msgSend_stret and hang both varieties on a conditional
3147 // expression which dictate which one to envoke depending on size of
3148 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003150 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003151 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003152 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003153 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003154 cast = NoTypeInfoCStyleCastExpr(Context,
3155 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003156 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003157 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003158 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3159 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003160 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003161 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003162 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003164 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003165 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003166
John McCall183700f2009-09-21 23:43:11 +00003167 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003168 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003169 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003170 FT->getResultType(), VK_RValue,
3171 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003172
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003173 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003174 UnaryExprOrTypeTraitExpr *sizeofExpr =
3175 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3176 Context->getTrivialTypeSourceInfo(returnType),
3177 Context->getSizeType(), SourceLocation(),
3178 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003179 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3180 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3181 // For X86 it is more complicated and some kind of target specific routine
3182 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003183 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003184 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003185 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3186 llvm::APInt(IntSize, 8),
3187 Context->IntTy,
3188 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003189 BinaryOperator *lessThanExpr =
3190 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3191 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003192 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003193 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003194 new (Context) ConditionalOperator(lessThanExpr,
3195 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003196 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003197 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003198 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3199 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003200 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003201 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003202 return ReplacingStmt;
3203}
3204
Steve Naroffb29b4272008-04-14 22:03:09 +00003205Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003206 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3207 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003208
Steve Naroff934f2762007-10-24 22:48:43 +00003209 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003210 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003211
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003212 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003213 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003214}
3215
Steve Naroff621edce2009-04-29 16:37:50 +00003216// typedef struct objc_object Protocol;
3217QualType RewriteObjC::getProtocolType() {
3218 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003219 TypeSourceInfo *TInfo
3220 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003221 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003222 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003223 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003224 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003225 }
3226 return Context->getTypeDeclType(ProtocolTypeDecl);
3227}
3228
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003229/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003230/// a synthesized/forward data reference (to the protocol's metadata).
3231/// The forward references (and metadata) are generated in
3232/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003233Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003234 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3235 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003236 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003237 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003238 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003239 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3240 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003241 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003242 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003243 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003244 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003245 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003246 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003247 ReplaceStmt(Exp, castExpr);
3248 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003249 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003250 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003251
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003252}
3253
Mike Stump1eb44332009-09-09 15:08:12 +00003254bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003255 const char *endBuf) {
3256 while (startBuf < endBuf) {
3257 if (*startBuf == '#') {
3258 // Skip whitespace.
3259 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3260 ;
3261 if (!strncmp(startBuf, "if", strlen("if")) ||
3262 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3263 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3264 !strncmp(startBuf, "define", strlen("define")) ||
3265 !strncmp(startBuf, "undef", strlen("undef")) ||
3266 !strncmp(startBuf, "else", strlen("else")) ||
3267 !strncmp(startBuf, "elif", strlen("elif")) ||
3268 !strncmp(startBuf, "endif", strlen("endif")) ||
3269 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3270 !strncmp(startBuf, "include", strlen("include")) ||
3271 !strncmp(startBuf, "import", strlen("import")) ||
3272 !strncmp(startBuf, "include_next", strlen("include_next")))
3273 return true;
3274 }
3275 startBuf++;
3276 }
3277 return false;
3278}
3279
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003280/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003281/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003282void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003283 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003284 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003285 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003286 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003287 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003288 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003289 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003290 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003291 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003292 SourceLocation LocStart = CDecl->getLocStart();
3293 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003294
Steve Narofffea763e82007-11-14 19:25:57 +00003295 const char *startBuf = SM->getCharacterData(LocStart);
3296 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003298 // If no ivars and no root or if its root, directly or indirectly,
3299 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003300 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3301 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003302 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003303 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003304 return;
3305 }
Mike Stump1eb44332009-09-09 15:08:12 +00003306
3307 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003308 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003309 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003310 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003311 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003312 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003313
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003314 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003315 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003316 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003317 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003318 // If the buffer contains preprocessor directives, we do more fine-grained
3319 // rewrites. This is intended to fix code that looks like (which occurs in
3320 // NSURL.h, for example):
3321 //
3322 // #ifdef XYZ
3323 // @interface Foo : NSObject
3324 // #else
3325 // @interface FooBar : NSObject
3326 // #endif
3327 // {
3328 // int i;
3329 // }
3330 // @end
3331 //
3332 // This clause is segregated to avoid breaking the common case.
3333 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003334 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003335 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003336 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003337 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003338
Chris Lattnercafeb352009-02-20 18:18:36 +00003339 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003340 // advance to the end of the referenced protocols.
3341 while (endHeader < cursor && *endHeader != '>') endHeader++;
3342 endHeader++;
3343 }
3344 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003345 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003346 } else {
3347 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003348 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003349 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003350 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003351 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003352 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003353 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003354 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003355 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003356
Steve Narofffea763e82007-11-14 19:25:57 +00003357 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003358 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003359 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003360 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003361 }
3362 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003363
Steve Narofffea763e82007-11-14 19:25:57 +00003364 // Now comment out any visibility specifiers.
3365 while (cursor < endBuf) {
3366 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003367 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003368 // Skip whitespace.
3369 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3370 /*scan*/;
3371
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003372 // FIXME: presence of @public, etc. inside comment results in
3373 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003374 if (!strncmp(cursor, "public", strlen("public")) ||
3375 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003376 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003377 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003378 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003379 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003380 // FIXME: If there are cases where '<' is used in ivar declaration part
3381 // of user code, then scan the ivar list and use needToScanForQualifiers
3382 // for type checking.
3383 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003384 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003385 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003386 cursor = strchr(cursor, '>');
3387 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003388 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003389 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003390 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003391 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003392 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003393 }
Steve Narofffea763e82007-11-14 19:25:57 +00003394 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003395 }
Steve Narofffea763e82007-11-14 19:25:57 +00003396 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003397 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003398 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003399 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003400 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003401 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003402 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003403 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003404 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003405 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003406 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003407 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003408 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003409 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003410}
3411
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003412// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003413/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003414template<typename MethodIterator>
3415void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3416 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003417 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003418 StringRef prefix,
3419 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003420 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003421 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003423 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003424 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003425 SEL _cmd;
3426 char *method_types;
3427 void *_imp;
3428 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003429 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003430 Result += "\nstruct _objc_method {\n";
3431 Result += "\tSEL _cmd;\n";
3432 Result += "\tchar *method_types;\n";
3433 Result += "\tvoid *_imp;\n";
3434 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003435
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003436 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003437 }
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003439 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Steve Naroff946a6932008-03-11 00:12:29 +00003441 /* struct {
3442 struct _objc_method_list *next_method;
3443 int method_count;
3444 struct _objc_method method_list[];
3445 }
3446 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003447 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003448 Result += "\nstatic struct {\n";
3449 Result += "\tstruct _objc_method_list *next_method;\n";
3450 Result += "\tint method_count;\n";
3451 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003452 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003453 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003454 Result += prefix;
3455 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3456 Result += "_METHODS_";
3457 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003458 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003459 Result += IsInstanceMethod ? "inst" : "cls";
3460 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003461 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003462
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003463 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003464 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003465 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003466 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003467 Result += "\", \"";
3468 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003469 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003470 Result += MethodInternalNames[*MethodBegin];
3471 Result += "}\n";
3472 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3473 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003474 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003475 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003476 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003477 Result += "\", \"";
3478 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003479 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003480 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003481 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003482 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003483 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003484}
3485
Steve Naroff621edce2009-04-29 16:37:50 +00003486/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003487void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003488RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3489 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003490 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003491
3492 // Output struct protocol_methods holder of method selector and type.
3493 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3494 /* struct protocol_methods {
3495 SEL _cmd;
3496 char *method_types;
3497 }
3498 */
3499 Result += "\nstruct _protocol_methods {\n";
3500 Result += "\tstruct objc_selector *_cmd;\n";
3501 Result += "\tchar *method_types;\n";
3502 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Steve Naroff621edce2009-04-29 16:37:50 +00003504 objc_protocol_methods = true;
3505 }
3506 // Do not synthesize the protocol more than once.
3507 if (ObjCSynthesizedProtocols.count(PDecl))
3508 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003510 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3511 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3512 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003513 /* struct _objc_protocol_method_list {
3514 int protocol_method_count;
3515 struct protocol_methods protocols[];
3516 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003517 */
Steve Naroff621edce2009-04-29 16:37:50 +00003518 Result += "\nstatic struct {\n";
3519 Result += "\tint protocol_method_count;\n";
3520 Result += "\tstruct _protocol_methods protocol_methods[";
3521 Result += utostr(NumMethods);
3522 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3523 Result += PDecl->getNameAsString();
3524 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3525 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Steve Naroff621edce2009-04-29 16:37:50 +00003527 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003528 for (ObjCProtocolDecl::instmeth_iterator
3529 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003530 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003531 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003532 Result += "\t ,{{(struct objc_selector *)\"";
3533 else
3534 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003535 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003536 std::string MethodTypeString;
3537 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3538 Result += "\", \"";
3539 Result += MethodTypeString;
3540 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003541 }
Steve Naroff621edce2009-04-29 16:37:50 +00003542 Result += "\t }\n};\n";
3543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Steve Naroff621edce2009-04-29 16:37:50 +00003545 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3547 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003548 if (NumMethods > 0) {
3549 /* struct _objc_protocol_method_list {
3550 int protocol_method_count;
3551 struct protocol_methods protocols[];
3552 }
3553 */
3554 Result += "\nstatic struct {\n";
3555 Result += "\tint protocol_method_count;\n";
3556 Result += "\tstruct _protocol_methods protocol_methods[";
3557 Result += utostr(NumMethods);
3558 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3559 Result += PDecl->getNameAsString();
3560 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3561 "{\n\t";
3562 Result += utostr(NumMethods);
3563 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Steve Naroff621edce2009-04-29 16:37:50 +00003565 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003566 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003567 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003568 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003569 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003570 Result += "\t ,{{(struct objc_selector *)\"";
3571 else
3572 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003573 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003574 std::string MethodTypeString;
3575 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3576 Result += "\", \"";
3577 Result += MethodTypeString;
3578 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003579 }
Steve Naroff621edce2009-04-29 16:37:50 +00003580 Result += "\t }\n};\n";
3581 }
3582
3583 // Output:
3584 /* struct _objc_protocol {
3585 // Objective-C 1.0 extensions
3586 struct _objc_protocol_extension *isa;
3587 char *protocol_name;
3588 struct _objc_protocol **protocol_list;
3589 struct _objc_protocol_method_list *instance_methods;
3590 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003591 };
Steve Naroff621edce2009-04-29 16:37:50 +00003592 */
3593 static bool objc_protocol = false;
3594 if (!objc_protocol) {
3595 Result += "\nstruct _objc_protocol {\n";
3596 Result += "\tstruct _objc_protocol_extension *isa;\n";
3597 Result += "\tchar *protocol_name;\n";
3598 Result += "\tstruct _objc_protocol **protocol_list;\n";
3599 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3600 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003601 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003602
Steve Naroff621edce2009-04-29 16:37:50 +00003603 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003604 }
Mike Stump1eb44332009-09-09 15:08:12 +00003605
Steve Naroff621edce2009-04-29 16:37:50 +00003606 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3607 Result += PDecl->getNameAsString();
3608 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3609 "{\n\t0, \"";
3610 Result += PDecl->getNameAsString();
3611 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003612 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003613 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3614 Result += PDecl->getNameAsString();
3615 Result += ", ";
3616 }
3617 else
3618 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003619 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003620 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3621 Result += PDecl->getNameAsString();
3622 Result += "\n";
3623 }
3624 else
3625 Result += "0\n";
3626 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Steve Naroff621edce2009-04-29 16:37:50 +00003628 // Mark this protocol as having been generated.
3629 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003630 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003631
3632}
3633
3634void RewriteObjC::
3635RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003636 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003637 std::string &Result) {
3638 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Steve Naroff621edce2009-04-29 16:37:50 +00003640 for (unsigned i = 0; i != Protocols.size(); i++)
3641 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3642
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003643 // Output the top lovel protocol meta-data for the class.
3644 /* struct _objc_protocol_list {
3645 struct _objc_protocol_list *next;
3646 int protocol_count;
3647 struct _objc_protocol *class_protocols[];
3648 }
3649 */
3650 Result += "\nstatic struct {\n";
3651 Result += "\tstruct _objc_protocol_list *next;\n";
3652 Result += "\tint protocol_count;\n";
3653 Result += "\tstruct _objc_protocol *class_protocols[";
3654 Result += utostr(Protocols.size());
3655 Result += "];\n} _OBJC_";
3656 Result += prefix;
3657 Result += "_PROTOCOLS_";
3658 Result += ClassName;
3659 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3660 "{\n\t0, ";
3661 Result += utostr(Protocols.size());
3662 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003664 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003665 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003666 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003668 for (unsigned i = 1; i != Protocols.size(); i++) {
3669 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003671 Result += "\n";
3672 }
3673 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003674}
3675
Steve Naroff621edce2009-04-29 16:37:50 +00003676
Mike Stump1eb44332009-09-09 15:08:12 +00003677/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003678/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003679void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003680 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003681 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003682 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003683 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003684 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003685 CDecl = CDecl->getNextClassCategory())
3686 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3687 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003689 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003690 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003691 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003693 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003694 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003695 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003696
3697 // If any of our property implementations have associated getters or
3698 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003699 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3700 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003701 Prop != PropEnd; ++Prop) {
3702 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3703 continue;
3704 if (!(*Prop)->getPropertyIvarDecl())
3705 continue;
3706 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3707 if (!PD)
3708 continue;
3709 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3710 InstanceMethods.push_back(Getter);
3711 if (PD->isReadOnly())
3712 continue;
3713 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3714 InstanceMethods.push_back(Setter);
3715 }
3716 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003717 true, "CATEGORY_", FullCategoryName.c_str(),
3718 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003719
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003720 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003721 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003722 false, "CATEGORY_", FullCategoryName.c_str(),
3723 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003725 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003726 // Null CDecl is case of a category implementation with no category interface
3727 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003728 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003729 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003730 /* struct _objc_category {
3731 char *category_name;
3732 char *class_name;
3733 struct _objc_method_list *instance_methods;
3734 struct _objc_method_list *class_methods;
3735 struct _objc_protocol_list *protocols;
3736 // Objective-C 1.0 extensions
3737 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003738 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003739 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003740 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003741 */
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003743 static bool objc_category = false;
3744 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003745 Result += "\nstruct _objc_category {\n";
3746 Result += "\tchar *category_name;\n";
3747 Result += "\tchar *class_name;\n";
3748 Result += "\tstruct _objc_method_list *instance_methods;\n";
3749 Result += "\tstruct _objc_method_list *class_methods;\n";
3750 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003751 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003752 Result += "\tstruct _objc_property_list *instance_properties;\n";
3753 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003754 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003755 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003756 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3757 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003758 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003759 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003760 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003761 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003762 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003763
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003764 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003765 Result += "\t, (struct _objc_method_list *)"
3766 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3767 Result += FullCategoryName;
3768 Result += "\n";
3769 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003770 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003771 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003772 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003773 Result += "\t, (struct _objc_method_list *)"
3774 "&_OBJC_CATEGORY_CLASS_METHODS_";
3775 Result += FullCategoryName;
3776 Result += "\n";
3777 }
3778 else
3779 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003780
Chris Lattnercafeb352009-02-20 18:18:36 +00003781 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003782 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003783 Result += FullCategoryName;
3784 Result += "\n";
3785 }
3786 else
3787 Result += "\t, 0\n";
3788 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003789}
3790
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003791/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3792/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003793void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003794 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003795 if (ivar->isBitField()) {
3796 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3797 // place all bitfields at offset 0.
3798 Result += "0";
3799 } else {
3800 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003801 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003802 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003803 Result += "_IMPL";
3804 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003805 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003806 Result += ")";
3807 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003808}
3809
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003810//===----------------------------------------------------------------------===//
3811// Meta Data Emission
3812//===----------------------------------------------------------------------===//
3813
Steve Naroffb29b4272008-04-14 22:03:09 +00003814void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003815 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003816 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003818 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003819 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003820 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003821 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003822 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003823 }
Mike Stump1eb44332009-09-09 15:08:12 +00003824
Chris Lattnerbe6df082007-12-12 07:56:42 +00003825 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003826 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003827 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003828 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003829 if (NumIvars > 0) {
3830 static bool objc_ivar = false;
3831 if (!objc_ivar) {
3832 /* struct _objc_ivar {
3833 char *ivar_name;
3834 char *ivar_type;
3835 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003836 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003837 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003838 Result += "\nstruct _objc_ivar {\n";
3839 Result += "\tchar *ivar_name;\n";
3840 Result += "\tchar *ivar_type;\n";
3841 Result += "\tint ivar_offset;\n";
3842 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003843
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003844 objc_ivar = true;
3845 }
3846
Steve Naroff946a6932008-03-11 00:12:29 +00003847 /* struct {
3848 int ivar_count;
3849 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003850 };
Steve Naroff946a6932008-03-11 00:12:29 +00003851 */
Mike Stump1eb44332009-09-09 15:08:12 +00003852 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003853 Result += "\tint ivar_count;\n";
3854 Result += "\tstruct _objc_ivar ivar_list[";
3855 Result += utostr(NumIvars);
3856 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003857 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003858 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003859 "{\n\t";
3860 Result += utostr(NumIvars);
3861 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003863 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003864 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003865 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003866 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003867 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003868 IV != IVEnd; ++IV)
3869 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003870 IVI = IDecl->ivar_begin();
3871 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003872 } else {
3873 IVI = CDecl->ivar_begin();
3874 IVE = CDecl->ivar_end();
3875 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003876 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003877 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003878 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003879 std::string TmpString, StrEncoding;
3880 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3881 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003882 Result += StrEncoding;
3883 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003884 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003885 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003886 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003887 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003888 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003889 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003890 std::string TmpString, StrEncoding;
3891 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3892 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003893 Result += StrEncoding;
3894 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003895 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003896 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003897 }
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003899 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003902 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003903 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003904 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003905
3906 // If any of our property implementations have associated getters or
3907 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003908 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3909 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003910 Prop != PropEnd; ++Prop) {
3911 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3912 continue;
3913 if (!(*Prop)->getPropertyIvarDecl())
3914 continue;
3915 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3916 if (!PD)
3917 continue;
3918 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003919 if (!Getter->isDefined())
3920 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003921 if (PD->isReadOnly())
3922 continue;
3923 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003924 if (!Setter->isDefined())
3925 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003926 }
3927 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003928 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003930 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003931 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003932 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003934 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003935 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003936 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003937
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003938 // Declaration of class/meta-class metadata
3939 /* struct _objc_class {
3940 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003941 const char *super_class_name;
3942 char *name;
3943 long version;
3944 long info;
3945 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003946 struct _objc_ivar_list *ivars;
3947 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003948 struct objc_cache *cache;
3949 struct objc_protocol_list *protocols;
3950 const char *ivar_layout;
3951 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003952 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003953 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003954 static bool objc_class = false;
3955 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003956 Result += "\nstruct _objc_class {\n";
3957 Result += "\tstruct _objc_class *isa;\n";
3958 Result += "\tconst char *super_class_name;\n";
3959 Result += "\tchar *name;\n";
3960 Result += "\tlong version;\n";
3961 Result += "\tlong info;\n";
3962 Result += "\tlong instance_size;\n";
3963 Result += "\tstruct _objc_ivar_list *ivars;\n";
3964 Result += "\tstruct _objc_method_list *methods;\n";
3965 Result += "\tstruct objc_cache *cache;\n";
3966 Result += "\tstruct _objc_protocol_list *protocols;\n";
3967 Result += "\tconst char *ivar_layout;\n";
3968 Result += "\tstruct _objc_class_ext *ext;\n";
3969 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003970 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003973 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003974 ObjCInterfaceDecl *RootClass = 0;
3975 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003976 while (SuperClass) {
3977 RootClass = SuperClass;
3978 SuperClass = SuperClass->getSuperClass();
3979 }
3980 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003981
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003982 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003983 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003984 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003985 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003986 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003987 Result += "\"";
3988
3989 if (SuperClass) {
3990 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003991 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003992 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003993 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003994 Result += "\"";
3995 }
3996 else {
3997 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003998 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003999 Result += "\"";
4000 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004001 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004002 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004003 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004004 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004005 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004006 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004007 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004008 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004009 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004010 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004011 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004012 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004013 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += ",0,0\n";
4015 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004016 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004017 Result += "\t,0,0,0,0\n";
4018 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004020 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004022 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004023 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004024 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004025 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004026 if (SuperClass) {
4027 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004028 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004029 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004030 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004031 Result += "\"";
4032 }
4033 else {
4034 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004035 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004036 Result += "\"";
4037 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004038 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004039 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004040 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004041 Result += ",0";
4042 else {
4043 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004044 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004045 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004046 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004047 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004048 Result += ")";
4049 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004050 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004051 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004052 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 Result += "\n\t";
4054 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004055 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004056 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004057 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004058 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004059 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004060 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004062 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004063 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004064 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004065 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004066 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004067 Result += ", 0,0\n";
4068 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004069 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004070 Result += ",0,0,0\n";
4071 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004072}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004073
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004074/// RewriteImplementations - This routine rewrites all method implementations
4075/// and emits meta-data.
4076
Steve Narofface66252008-11-13 20:07:04 +00004077void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004078 int ClsDefCount = ClassImplementation.size();
4079 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004081 // Rewrite implemented methods
4082 for (int i = 0; i < ClsDefCount; i++)
4083 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004085 for (int i = 0; i < CatDefCount; i++)
4086 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004087}
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Steve Narofface66252008-11-13 20:07:04 +00004089void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4090 int ClsDefCount = ClassImplementation.size();
4091 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004092
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004093 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004094 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004095 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004097 // For each implemented category, write out all its meta data.
4098 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004099 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004100
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004101 // Write objc_symtab metadata
4102 /*
4103 struct _objc_symtab
4104 {
4105 long sel_ref_cnt;
4106 SEL *refs;
4107 short cls_def_cnt;
4108 short cat_def_cnt;
4109 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004110 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004111 */
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004113 Result += "\nstruct _objc_symtab {\n";
4114 Result += "\tlong sel_ref_cnt;\n";
4115 Result += "\tSEL *refs;\n";
4116 Result += "\tshort cls_def_cnt;\n";
4117 Result += "\tshort cat_def_cnt;\n";
4118 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4119 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004121 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004122 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004123 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004124 + ", " + utostr(CatDefCount) + "\n";
4125 for (int i = 0; i < ClsDefCount; i++) {
4126 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004127 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004128 Result += "\n";
4129 }
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004131 for (int i = 0; i < CatDefCount; i++) {
4132 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004133 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004134 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004135 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004136 Result += "\n";
4137 }
Mike Stump1eb44332009-09-09 15:08:12 +00004138
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004139 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004141 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004143 /*
4144 struct _objc_module {
4145 long version;
4146 long size;
4147 const char *name;
4148 struct _objc_symtab *symtab;
4149 }
4150 */
Mike Stump1eb44332009-09-09 15:08:12 +00004151
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004152 Result += "\nstruct _objc_module {\n";
4153 Result += "\tlong version;\n";
4154 Result += "\tlong size;\n";
4155 Result += "\tconst char *name;\n";
4156 Result += "\tstruct _objc_symtab *symtab;\n";
4157 Result += "};\n\n";
4158 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004159 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004160 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004161 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004162 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004163
Francois Pichet62ec1f22011-09-17 17:15:52 +00004164 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004165 if (ProtocolExprDecls.size()) {
4166 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4167 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004168 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004169 E = ProtocolExprDecls.end(); I != E; ++I) {
4170 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4171 Result += (*I)->getNameAsString();
4172 Result += " = &_OBJC_PROTOCOL_";
4173 Result += (*I)->getNameAsString();
4174 Result += ";\n";
4175 }
4176 Result += "#pragma data_seg(pop)\n\n";
4177 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004178 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004179 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004180 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4181 Result += "&_OBJC_MODULES;\n";
4182 Result += "#pragma data_seg(pop)\n\n";
4183 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004184}
Chris Lattner311ff022007-10-16 22:36:42 +00004185
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004186void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4187 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004188 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004189 assert(BlockByRefDeclNo.count(VD) &&
4190 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004191 if (def)
4192 ResultStr += "struct ";
4193 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004194 "_" + utostr(BlockByRefDeclNo[VD]) ;
4195}
4196
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004197static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4198 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4199 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4200 return false;
4201}
4202
Steve Naroff54055232008-10-27 17:20:55 +00004203std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004204 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004205 std::string Tag) {
4206 const FunctionType *AFT = CE->getFunctionType();
4207 QualType RT = AFT->getResultType();
4208 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004209 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004210 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004211
Steve Naroff54055232008-10-27 17:20:55 +00004212 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Douglas Gregor72564e72009-02-26 23:50:07 +00004214 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004215 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004216 // block (to reference imported block decl refs).
4217 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004218 } else if (BD->param_empty()) {
4219 S += "(" + StructRef + " *__cself)";
4220 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004221 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004222 assert(FT && "SynthesizeBlockFunc: No function proto");
4223 S += '(';
4224 // first add the implicit argument.
4225 S += StructRef + " *__cself, ";
4226 std::string ParamStr;
4227 for (BlockDecl::param_iterator AI = BD->param_begin(),
4228 E = BD->param_end(); AI != E; ++AI) {
4229 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004230 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004231 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004232 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004233 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004234 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004235 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004236 S += ParamStr;
4237 }
4238 if (FT->isVariadic()) {
4239 if (!BD->param_empty()) S += ", ";
4240 S += "...";
4241 }
4242 S += ')';
4243 }
4244 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Steve Naroff54055232008-10-27 17:20:55 +00004246 // Create local declarations to avoid rewriting all closure decl ref exprs.
4247 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004248 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004249 E = BlockByRefDecls.end(); I != E; ++I) {
4250 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004251 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004252 std::string TypeString;
4253 RewriteByRefString(TypeString, Name, (*I));
4254 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004255 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004256 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004257 }
Steve Naroff54055232008-10-27 17:20:55 +00004258 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004259 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004260 E = BlockByCopyDecls.end(); I != E; ++I) {
4261 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004262 // Handle nested closure invocation. For example:
4263 //
4264 // void (^myImportedClosure)(void);
4265 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004266 //
Steve Naroff54055232008-10-27 17:20:55 +00004267 // void (^anotherClosure)(void);
4268 // anotherClosure = ^(void) {
4269 // myImportedClosure(); // import and invoke the closure
4270 // };
4271 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004272 if (isTopLevelBlockPointerType((*I)->getType())) {
4273 RewriteBlockPointerTypeVariable(S, (*I));
4274 S += " = (";
4275 RewriteBlockPointerType(S, (*I)->getType());
4276 S += ")";
4277 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4278 }
4279 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004280 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004281 QualType QT = (*I)->getType();
4282 if (HasLocalVariableExternalStorage(*I))
4283 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004284 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004285 S += Name + " = __cself->" +
4286 (*I)->getNameAsString() + "; // bound by copy\n";
4287 }
Steve Naroff54055232008-10-27 17:20:55 +00004288 }
4289 std::string RewrittenStr = RewrittenBlockExprs[CE];
4290 const char *cstr = RewrittenStr.c_str();
4291 while (*cstr++ != '{') ;
4292 S += cstr;
4293 S += "\n";
4294 return S;
4295}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004296
Steve Naroff54055232008-10-27 17:20:55 +00004297std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004298 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004299 std::string Tag) {
4300 std::string StructRef = "struct " + Tag;
4301 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004302
Steve Naroff54055232008-10-27 17:20:55 +00004303 S += funcName;
4304 S += "_block_copy_" + utostr(i);
4305 S += "(" + StructRef;
4306 S += "*dst, " + StructRef;
4307 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004308 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004309 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004310 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004311 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004312 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004313 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004314 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004315 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004316 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004317 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004318 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004319 else
4320 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004321 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004322 S += "}\n";
4323
Steve Naroff54055232008-10-27 17:20:55 +00004324 S += "\nstatic void __";
4325 S += funcName;
4326 S += "_block_dispose_" + utostr(i);
4327 S += "(" + StructRef;
4328 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004329 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004330 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004331 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004332 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004333 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004334 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004335 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004336 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004337 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004338 else
4339 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004340 }
Mike Stump1eb44332009-09-09 15:08:12 +00004341 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004342 return S;
4343}
4344
Steve Naroff01aec112009-12-06 21:14:13 +00004345std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4346 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004347 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004348 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Steve Naroff54055232008-10-27 17:20:55 +00004350 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004351 S += " struct " + Desc;
4352 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004353
Steve Naroff01aec112009-12-06 21:14:13 +00004354 Constructor += "(void *fp, "; // Invoke function pointer.
4355 Constructor += "struct " + Desc; // Descriptor pointer.
4356 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Steve Naroff54055232008-10-27 17:20:55 +00004358 if (BlockDeclRefs.size()) {
4359 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004360 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004361 E = BlockByCopyDecls.end(); I != E; ++I) {
4362 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004363 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004364 std::string ArgName = "_" + FieldName;
4365 // Handle nested closure invocation. For example:
4366 //
4367 // void (^myImportedBlock)(void);
4368 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004369 //
Steve Naroff54055232008-10-27 17:20:55 +00004370 // void (^anotherBlock)(void);
4371 // anotherBlock = ^(void) {
4372 // myImportedBlock(); // import and invoke the closure
4373 // };
4374 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004375 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004376 S += "struct __block_impl *";
4377 Constructor += ", void *" + ArgName;
4378 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004379 QualType QT = (*I)->getType();
4380 if (HasLocalVariableExternalStorage(*I))
4381 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004382 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4383 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004384 Constructor += ", " + ArgName;
4385 }
4386 S += FieldName + ";\n";
4387 }
4388 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004389 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004390 E = BlockByRefDecls.end(); I != E; ++I) {
4391 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004392 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004393 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004394 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004395 std::string TypeString;
4396 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004397 TypeString += " *";
4398 FieldName = TypeString + FieldName;
4399 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004400 Constructor += ", " + ArgName;
4401 }
4402 S += FieldName + "; // by ref\n";
4403 }
4404 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004405 Constructor += ", int flags=0)";
4406 // Initialize all "by copy" arguments.
4407 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004408 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004409 E = BlockByCopyDecls.end(); I != E; ++I) {
4410 std::string Name = (*I)->getNameAsString();
4411 if (firsTime) {
4412 Constructor += " : ";
4413 firsTime = false;
4414 }
4415 else
4416 Constructor += ", ";
4417 if (isTopLevelBlockPointerType((*I)->getType()))
4418 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4419 else
4420 Constructor += Name + "(_" + Name + ")";
4421 }
4422 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004423 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004424 E = BlockByRefDecls.end(); I != E; ++I) {
4425 std::string Name = (*I)->getNameAsString();
4426 if (firsTime) {
4427 Constructor += " : ";
4428 firsTime = false;
4429 }
4430 else
4431 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004432 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004433 }
4434
4435 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004436 if (GlobalVarDecl)
4437 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4438 else
4439 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004440 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004441
Steve Naroff01aec112009-12-06 21:14:13 +00004442 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004443 } else {
4444 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004445 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004446 if (GlobalVarDecl)
4447 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4448 else
4449 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004450 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4451 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004452 }
4453 Constructor += " ";
4454 Constructor += "}\n";
4455 S += Constructor;
4456 S += "};\n";
4457 return S;
4458}
4459
Steve Naroff01aec112009-12-06 21:14:13 +00004460std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4461 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004462 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004463 unsigned hasCopy) {
4464 std::string S = "\nstatic struct " + DescTag;
4465
4466 S += " {\n unsigned long reserved;\n";
4467 S += " unsigned long Block_size;\n";
4468 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004469 S += " void (*copy)(struct ";
4470 S += ImplTag; S += "*, struct ";
4471 S += ImplTag; S += "*);\n";
4472
4473 S += " void (*dispose)(struct ";
4474 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004475 }
4476 S += "} ";
4477
4478 S += DescTag + "_DATA = { 0, sizeof(struct ";
4479 S += ImplTag + ")";
4480 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004481 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4482 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004483 }
4484 S += "};\n";
4485 return S;
4486}
4487
Steve Naroff54055232008-10-27 17:20:55 +00004488void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004489 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004490 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004491 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004492 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004493 bool RewriteSC = (GlobalVarDecl &&
4494 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004495 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004496 GlobalVarDecl->getType().getCVRQualifiers());
4497 if (RewriteSC) {
4498 std::string SC(" void __");
4499 SC += GlobalVarDecl->getNameAsString();
4500 SC += "() {}";
4501 InsertText(FunLocStart, SC);
4502 }
4503
Steve Naroff54055232008-10-27 17:20:55 +00004504 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004505 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4506 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004507 // Need to copy-in the inner copied-in variables not actually used in this
4508 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004509 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4510 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4511 ValueDecl *VD = Exp->getDecl();
4512 BlockDeclRefs.push_back(Exp);
4513 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4514 BlockByCopyDeclsPtrSet.insert(VD);
4515 BlockByCopyDecls.push_back(VD);
4516 }
4517 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4518 BlockByRefDeclsPtrSet.insert(VD);
4519 BlockByRefDecls.push_back(VD);
4520 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004521 // imported objects in the inner blocks not used in the outer
4522 // blocks must be copied/disposed in the outer block as well.
4523 if (Exp->isByRef() ||
4524 VD->getType()->isObjCObjectPointerType() ||
4525 VD->getType()->isBlockPointerType())
4526 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004527 }
Steve Naroff54055232008-10-27 17:20:55 +00004528
Daniel Dunbar4087f272010-08-17 22:39:59 +00004529 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4530 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004531
Steve Naroff01aec112009-12-06 21:14:13 +00004532 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004533
Benjamin Kramerd999b372010-02-14 14:14:16 +00004534 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004535
Steve Naroff01aec112009-12-06 21:14:13 +00004536 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004537
Benjamin Kramerd999b372010-02-14 14:14:16 +00004538 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004539
4540 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004541 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004542 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004543 }
Steve Naroff01aec112009-12-06 21:14:13 +00004544 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4545 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004546 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004547
Steve Naroff54055232008-10-27 17:20:55 +00004548 BlockDeclRefs.clear();
4549 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004550 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004551 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004552 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004553 ImportedBlockDecls.clear();
4554 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004555 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004556 // Must insert any 'const/volatile/static here. Since it has been
4557 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004558 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004559 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004560 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004561 if (GlobalVarDecl->getType().isConstQualified())
4562 SC += "const ";
4563 if (GlobalVarDecl->getType().isVolatileQualified())
4564 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004565 if (GlobalVarDecl->getType().isRestrictQualified())
4566 SC += "restrict ";
4567 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004568 }
4569
Steve Naroff54055232008-10-27 17:20:55 +00004570 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004571 InnerDeclRefsCount.clear();
4572 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004573 RewrittenBlockExprs.clear();
4574}
4575
4576void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4577 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004578 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Steve Naroff54055232008-10-27 17:20:55 +00004580 SynthesizeBlockLiterals(FunLocStart, FuncName);
4581}
4582
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004583static void BuildUniqueMethodName(std::string &Name,
4584 ObjCMethodDecl *MD) {
4585 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004586 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004587 Name += "__" + MD->getSelector().getAsString();
4588 // Convert colons to underscores.
4589 std::string::size_type loc = 0;
4590 while ((loc = Name.find(":", loc)) != std::string::npos)
4591 Name.replace(loc, 1, "_");
4592}
4593
Steve Naroff54055232008-10-27 17:20:55 +00004594void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004595 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4596 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004597 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004598 std::string FuncName;
4599 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004600 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004601}
4602
4603void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004604 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004605 if (*CI) {
4606 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4607 GetBlockDeclRefExprs(CBE->getBody());
4608 else
4609 GetBlockDeclRefExprs(*CI);
4610 }
4611 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004612 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004613 // FIXME: Handle enums.
4614 if (!isa<FunctionDecl>(CDRE->getDecl()))
4615 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004616 }
4617 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4618 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4619 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004620 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4621 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004622 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004623 BlockDeclRefs.push_back(BDRE);
4624 }
4625
Steve Naroff54055232008-10-27 17:20:55 +00004626 return;
4627}
4628
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004629void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004630 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004631 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004632 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004633 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004634 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4635 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004636 GetInnerBlockDeclRefExprs(CBE->getBody(),
4637 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004638 InnerContexts);
4639 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004640 else
4641 GetInnerBlockDeclRefExprs(*CI,
4642 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004643 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004644
4645 }
4646 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004647 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004648 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004649 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004650 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004651 }
4652 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4653 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4654 if (Var->isFunctionOrMethodVarDecl())
4655 ImportedLocalExternalDecls.insert(Var);
4656 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004657
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004658 return;
4659}
4660
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004661/// convertFunctionTypeOfBlocks - This routine converts a function type
4662/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004663/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004664/// all block pointers to function pointers.
4665QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4666 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4667 // FTP will be null for closures that don't take arguments.
4668 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004669 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004670 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004671 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004672
4673 if (FTP) {
4674 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4675 E = FTP->arg_type_end(); I && (I != E); ++I) {
4676 QualType t = *I;
4677 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004678 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004679 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004680 ArgTypes.push_back(t);
4681 }
4682 }
4683 QualType FuncType;
4684 // FIXME. Does this work if block takes no argument but has a return type
4685 // which is of block type?
4686 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004687 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004688 else FuncType = QualType(FT, 0);
4689 return FuncType;
4690}
4691
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004692Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004693 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004694 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004695
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004696 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004697 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004698 } else if (const BlockDeclRefExpr *CDRE =
4699 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004700 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004701 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004702 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004703 }
4704 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4705 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4706 }
4707 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4708 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4709 else if (const ConditionalOperator *CEXPR =
4710 dyn_cast<ConditionalOperator>(BlockExp)) {
4711 Expr *LHSExp = CEXPR->getLHS();
4712 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4713 Expr *RHSExp = CEXPR->getRHS();
4714 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4715 Expr *CONDExp = CEXPR->getCond();
4716 ConditionalOperator *CondExpr =
4717 new (Context) ConditionalOperator(CONDExp,
4718 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004719 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004720 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004721 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004722 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4723 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00004724 } else if (const PseudoObjectExpr *POE
4725 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4726 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004727 } else {
4728 assert(1 && "RewriteBlockClass: Bad type");
4729 }
4730 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004731 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004732 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004733 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004734 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004736 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004737 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004738 &Context->Idents.get("__block_impl"));
4739 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004740
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004741 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004742 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004743
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004744 // Push the block argument type.
4745 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004746 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004747 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004748 E = FTP->arg_type_end(); I && (I != E); ++I) {
4749 QualType t = *I;
4750 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004751 if (!convertBlockPointerToFunctionPointer(t))
4752 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004753 ArgTypes.push_back(t);
4754 }
Steve Naroff54055232008-10-27 17:20:55 +00004755 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004756 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004757 QualType PtrToFuncCastType
4758 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004760 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004761
John McCall9d125032010-01-15 18:39:57 +00004762 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004763 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004764 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004765 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004766 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4767 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004768 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Douglas Gregor44b43212008-12-11 16:49:14 +00004770 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004771 SourceLocation(),
4772 &Context->Idents.get("FuncPtr"),
4773 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004774 /*BitWidth=*/0, /*Mutable=*/true,
4775 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004776 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004777 FD->getType(), VK_LValue,
4778 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004780
John McCall9d125032010-01-15 18:39:57 +00004781 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004782 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004783 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004784
Chris Lattner5f9e2722011-07-23 10:55:15 +00004785 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004786 // Add the implicit argument.
4787 BlkExprs.push_back(BlkCast);
4788 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004789 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004790 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004791 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004792 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004793 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4794 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004795 Exp->getType(), VK_RValue,
4796 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004797 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004798}
4799
Steve Naroff621edce2009-04-29 16:37:50 +00004800// We need to return the rewritten expression to handle cases where the
4801// BlockDeclRefExpr is embedded in another expression being rewritten.
4802// For example:
4803//
4804// int main() {
4805// __block Foo *f;
4806// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004807//
Steve Naroff621edce2009-04-29 16:37:50 +00004808// void (^myblock)() = ^() {
4809// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4810// i = 77;
4811// };
4812//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004813Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004814 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004815 // for each DeclRefExp where BYREFVAR is name of the variable.
4816 ValueDecl *VD;
4817 bool isArrow = true;
4818 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4819 VD = BDRE->getDecl();
4820 else {
4821 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4822 isArrow = false;
4823 }
4824
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004825 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004826 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004827 &Context->Idents.get("__forwarding"),
4828 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004829 /*BitWidth=*/0, /*Mutable=*/true,
4830 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004831 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4832 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004833 FD->getType(), VK_LValue,
4834 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004835
Chris Lattner5f9e2722011-07-23 10:55:15 +00004836 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004837 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004838 &Context->Idents.get(Name),
4839 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004840 /*BitWidth=*/0, /*Mutable=*/true,
4841 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004842 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004843 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004844
4845
4846
Steve Naroffdf8570d2009-02-02 17:19:26 +00004847 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004848 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4849 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004850 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004851 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004852 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004853}
4854
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004855// Rewrites the imported local variable V with external storage
4856// (static, extern, etc.) as *V
4857//
4858Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4859 ValueDecl *VD = DRE->getDecl();
4860 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4861 if (!ImportedLocalExternalDecls.count(Var))
4862 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004863 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4864 VK_LValue, OK_Ordinary,
4865 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004866 // Need parens to enforce precedence.
4867 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4868 Exp);
4869 ReplaceStmt(DRE, PE);
4870 return PE;
4871}
4872
Steve Naroffb2f9e512008-11-03 23:29:32 +00004873void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4874 SourceLocation LocStart = CE->getLParenLoc();
4875 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004876
4877 // Need to avoid trying to rewrite synthesized casts.
4878 if (LocStart.isInvalid())
4879 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004880 // Need to avoid trying to rewrite casts contained in macros.
4881 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4882 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004883
Steve Naroff54055232008-10-27 17:20:55 +00004884 const char *startBuf = SM->getCharacterData(LocStart);
4885 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004886 QualType QT = CE->getType();
4887 const Type* TypePtr = QT->getAs<Type>();
4888 if (isa<TypeOfExprType>(TypePtr)) {
4889 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4890 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4891 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004892 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004893 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004894 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004895 return;
4896 }
Steve Naroff54055232008-10-27 17:20:55 +00004897 // advance the location to startArgList.
4898 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Steve Naroff54055232008-10-27 17:20:55 +00004900 while (*argPtr++ && (argPtr < endBuf)) {
4901 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004902 case '^':
4903 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004904 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004905 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004906 break;
Steve Naroff54055232008-10-27 17:20:55 +00004907 }
4908 }
4909 return;
4910}
4911
4912void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4913 SourceLocation DeclLoc = FD->getLocation();
4914 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Steve Naroff54055232008-10-27 17:20:55 +00004916 // We have 1 or more arguments that have closure pointers.
4917 const char *startBuf = SM->getCharacterData(DeclLoc);
4918 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Steve Naroff54055232008-10-27 17:20:55 +00004920 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Steve Naroff54055232008-10-27 17:20:55 +00004922 parenCount++;
4923 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004924 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004925 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004926
Steve Naroff54055232008-10-27 17:20:55 +00004927 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Steve Naroff54055232008-10-27 17:20:55 +00004929 while (*argPtr++ && parenCount) {
4930 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004931 case '^':
4932 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004933 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004934 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004935 break;
4936 case '(':
4937 parenCount++;
4938 break;
4939 case ')':
4940 parenCount--;
4941 break;
Steve Naroff54055232008-10-27 17:20:55 +00004942 }
4943 }
4944 return;
4945}
4946
4947bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004948 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004949 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004950 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004951 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004952 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004953 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004954 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004955 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004956 }
4957 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004958 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004959 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004960 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004961 return true;
4962 }
4963 return false;
4964}
4965
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004966bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4967 const FunctionProtoType *FTP;
4968 const PointerType *PT = QT->getAs<PointerType>();
4969 if (PT) {
4970 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4971 } else {
4972 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4973 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4974 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4975 }
4976 if (FTP) {
4977 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004978 E = FTP->arg_type_end(); I != E; ++I) {
4979 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004980 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004981 if ((*I)->isObjCObjectPointerType() &&
4982 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4983 return true;
4984 }
4985
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004986 }
4987 return false;
4988}
4989
Ted Kremenek8189cde2009-02-07 01:47:29 +00004990void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4991 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004992 const char *argPtr = strchr(Name, '(');
4993 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004994
Steve Naroff54055232008-10-27 17:20:55 +00004995 LParen = argPtr; // output the start.
4996 argPtr++; // skip past the left paren.
4997 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004998
Steve Naroff54055232008-10-27 17:20:55 +00004999 while (*argPtr && parenCount) {
5000 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005001 case '(': parenCount++; break;
5002 case ')': parenCount--; break;
5003 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005004 }
5005 if (parenCount) argPtr++;
5006 }
5007 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5008 RParen = argPtr; // output the end
5009}
5010
5011void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5012 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5013 RewriteBlockPointerFunctionArgs(FD);
5014 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005015 }
Steve Naroff54055232008-10-27 17:20:55 +00005016 // Handle Variables and Typedefs.
5017 SourceLocation DeclLoc = ND->getLocation();
5018 QualType DeclT;
5019 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5020 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005021 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005022 DeclT = TDD->getUnderlyingType();
5023 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5024 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005025 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005026 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005027
Steve Naroff54055232008-10-27 17:20:55 +00005028 const char *startBuf = SM->getCharacterData(DeclLoc);
5029 const char *endBuf = startBuf;
5030 // scan backward (from the decl location) for the end of the previous decl.
5031 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5032 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005033 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005034 std::string buf;
5035 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005036 // *startBuf != '^' if we are dealing with a pointer to function that
5037 // may take block argument types (which will be handled below).
5038 if (*startBuf == '^') {
5039 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005040 buf = '*';
5041 startBuf++;
5042 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005043 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005044 while (*startBuf != ')') {
5045 buf += *startBuf;
5046 startBuf++;
5047 OrigLength++;
5048 }
5049 buf += ')';
5050 OrigLength++;
5051
5052 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5053 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005054 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005055 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005056 DeclLoc = ND->getLocation();
5057 startBuf = SM->getCharacterData(DeclLoc);
5058 const char *argListBegin, *argListEnd;
5059 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5060 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005061 if (*argListBegin == '^')
5062 buf += '*';
5063 else if (*argListBegin == '<') {
5064 buf += "/*";
5065 buf += *argListBegin++;
5066 OrigLength++;;
5067 while (*argListBegin != '>') {
5068 buf += *argListBegin++;
5069 OrigLength++;
5070 }
5071 buf += *argListBegin;
5072 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005073 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005074 else
5075 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005076 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005077 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005078 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005079 buf += ')';
5080 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005081 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005082 ReplaceText(Start, OrigLength, buf);
5083
Steve Naroff54055232008-10-27 17:20:55 +00005084 return;
5085}
5086
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005087
5088/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5089/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5090/// struct Block_byref_id_object *src) {
5091/// _Block_object_assign (&_dest->object, _src->object,
5092/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5093/// [|BLOCK_FIELD_IS_WEAK]) // object
5094/// _Block_object_assign(&_dest->object, _src->object,
5095/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5096/// [|BLOCK_FIELD_IS_WEAK]) // block
5097/// }
5098/// And:
5099/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5100/// _Block_object_dispose(_src->object,
5101/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5102/// [|BLOCK_FIELD_IS_WEAK]) // object
5103/// _Block_object_dispose(_src->object,
5104/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5105/// [|BLOCK_FIELD_IS_WEAK]) // block
5106/// }
5107
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005108std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5109 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005110 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005111 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005112 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005113 CopyDestroyCache.insert(flag);
5114 S = "static void __Block_byref_id_object_copy_";
5115 S += utostr(flag);
5116 S += "(void *dst, void *src) {\n";
5117
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005118 // offset into the object pointer is computed as:
5119 // void * + void* + int + int + void* + void *
5120 unsigned IntSize =
5121 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5122 unsigned VoidPtrSize =
5123 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5124
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005125 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005126 S += " _Block_object_assign((char*)dst + ";
5127 S += utostr(offset);
5128 S += ", *(void * *) ((char*)src + ";
5129 S += utostr(offset);
5130 S += "), ";
5131 S += utostr(flag);
5132 S += ");\n}\n";
5133
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005134 S += "static void __Block_byref_id_object_dispose_";
5135 S += utostr(flag);
5136 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005137 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5138 S += utostr(offset);
5139 S += "), ";
5140 S += utostr(flag);
5141 S += ");\n}\n";
5142 return S;
5143}
5144
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005145/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5146/// the declaration into:
5147/// struct __Block_byref_ND {
5148/// void *__isa; // NULL for everything except __weak pointers
5149/// struct __Block_byref_ND *__forwarding;
5150/// int32_t __flags;
5151/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005152/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5153/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005154/// typex ND;
5155/// };
5156///
5157/// It then replaces declaration of ND variable with:
5158/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5159/// __size=sizeof(struct __Block_byref_ND),
5160/// ND=initializer-if-any};
5161///
5162///
5163void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005164 // Insert declaration for the function in which block literal is
5165 // used.
5166 if (CurFunctionDeclToDeclareForBlock)
5167 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005168 int flag = 0;
5169 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005170 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005171 if (DeclLoc.isInvalid())
5172 // If type location is missing, it is because of missing type (a warning).
5173 // Use variable's location which is good for this case.
5174 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005175 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005176 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005177 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005178 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005179 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005180 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005181 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005182 ByrefType += " {\n";
5183 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005184 RewriteByRefString(ByrefType, Name, ND);
5185 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005186 ByrefType += " int __flags;\n";
5187 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005188 // Add void *__Block_byref_id_object_copy;
5189 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005190 QualType Ty = ND->getType();
5191 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5192 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005193 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5194 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005195 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005196
5197 QualType T = Ty;
5198 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005199 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005200
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005201 ByrefType += " " + Name + ";\n";
5202 ByrefType += "};\n";
5203 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005204 SourceLocation FunLocStart;
5205 if (CurFunctionDef)
5206 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5207 else {
5208 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5209 FunLocStart = CurMethodDef->getLocStart();
5210 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005211 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005212 if (Ty.isObjCGCWeak()) {
5213 flag |= BLOCK_FIELD_IS_WEAK;
5214 isa = 1;
5215 }
5216
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005217 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005218 flag = BLOCK_BYREF_CALLER;
5219 QualType Ty = ND->getType();
5220 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5221 if (Ty->isBlockPointerType())
5222 flag |= BLOCK_FIELD_IS_BLOCK;
5223 else
5224 flag |= BLOCK_FIELD_IS_OBJECT;
5225 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005226 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005227 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005228 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005229
5230 // struct __Block_byref_ND ND =
5231 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5232 // initializer-if-any};
5233 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005234 unsigned flags = 0;
5235 if (HasCopyAndDispose)
5236 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005237 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005238 ByrefType.clear();
5239 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005240 std::string ForwardingCastType("(");
5241 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005242 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005243 ByrefType += " " + Name + " = {(void*)";
5244 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005245 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005246 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005247 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005248 ByrefType += "sizeof(";
5249 RewriteByRefString(ByrefType, Name, ND);
5250 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005251 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005252 ByrefType += ", __Block_byref_id_object_copy_";
5253 ByrefType += utostr(flag);
5254 ByrefType += ", __Block_byref_id_object_dispose_";
5255 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005256 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005257 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005258 unsigned nameSize = Name.size();
5259 // for block or function pointer declaration. Name is aleady
5260 // part of the declaration.
5261 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5262 nameSize = 1;
5263 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005264 }
5265 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005266 SourceLocation startLoc;
5267 Expr *E = ND->getInit();
5268 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5269 startLoc = ECE->getLParenLoc();
5270 else
5271 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005272 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005273 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005274 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005275 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005276 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005277 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005278 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005279 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005280 ByrefType += "sizeof(";
5281 RewriteByRefString(ByrefType, Name, ND);
5282 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005283 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005284 ByrefType += "__Block_byref_id_object_copy_";
5285 ByrefType += utostr(flag);
5286 ByrefType += ", __Block_byref_id_object_dispose_";
5287 ByrefType += utostr(flag);
5288 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005289 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005290 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005291
5292 // Complete the newly synthesized compound expression by inserting a right
5293 // curly brace before the end of the declaration.
5294 // FIXME: This approach avoids rewriting the initializer expression. It
5295 // also assumes there is only one declarator. For example, the following
5296 // isn't currently supported by this routine (in general):
5297 //
5298 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5299 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005300 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5301 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005302 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5303 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005304 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005305
Benjamin Kramerd999b372010-02-14 14:14:16 +00005306 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005307 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005308 return;
5309}
5310
Mike Stump1eb44332009-09-09 15:08:12 +00005311void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005312 // Add initializers for any closure decl refs.
5313 GetBlockDeclRefExprs(Exp->getBody());
5314 if (BlockDeclRefs.size()) {
5315 // Unique all "by copy" declarations.
5316 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005317 if (!BlockDeclRefs[i]->isByRef()) {
5318 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5319 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5320 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5321 }
5322 }
Steve Naroff54055232008-10-27 17:20:55 +00005323 // Unique all "by ref" declarations.
5324 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5325 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005326 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5327 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5328 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5329 }
Steve Naroff54055232008-10-27 17:20:55 +00005330 }
5331 // Find any imported blocks...they will need special attention.
5332 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005333 if (BlockDeclRefs[i]->isByRef() ||
5334 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005335 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005336 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005337 }
5338}
5339
Chris Lattner5f9e2722011-07-23 10:55:15 +00005340FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005341 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005342 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005343 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5344 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005345 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005346}
5347
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005348Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005349 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005350 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005351 Blocks.push_back(Exp);
5352
5353 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005354
5355 // Add inner imported variables now used in current block.
5356 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005357 if (!InnerBlockDeclRefs.empty()) {
5358 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5359 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5360 ValueDecl *VD = Exp->getDecl();
5361 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005362 // We need to save the copied-in variables in nested
5363 // blocks because it is needed at the end for some of the API generations.
5364 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005365 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5366 BlockDeclRefs.push_back(Exp);
5367 BlockByCopyDeclsPtrSet.insert(VD);
5368 BlockByCopyDecls.push_back(VD);
5369 }
5370 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5371 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5372 BlockDeclRefs.push_back(Exp);
5373 BlockByRefDeclsPtrSet.insert(VD);
5374 BlockByRefDecls.push_back(VD);
5375 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005376 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005377 // Find any imported blocks...they will need special attention.
5378 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5379 if (InnerBlockDeclRefs[i]->isByRef() ||
5380 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5381 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5382 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005383 }
5384 InnerDeclRefsCount.push_back(countOfInnerDecls);
5385
Steve Narofffa15fd92008-10-28 20:29:00 +00005386 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Steve Narofffa15fd92008-10-28 20:29:00 +00005388 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005389 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005390 else if (CurMethodDef)
5391 BuildUniqueMethodName(FuncName, CurMethodDef);
5392 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005393 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Steve Narofffa15fd92008-10-28 20:29:00 +00005395 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005396
Steve Narofffa15fd92008-10-28 20:29:00 +00005397 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5398 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Steve Narofffa15fd92008-10-28 20:29:00 +00005400 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005401 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5402 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005403
5404 FunctionDecl *FD;
5405 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Steve Narofffa15fd92008-10-28 20:29:00 +00005407 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005408 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005409 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5410 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Chris Lattner5f9e2722011-07-23 10:55:15 +00005412 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Steve Narofffdc03722008-10-29 21:23:59 +00005414 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005415 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005416 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005417 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005418 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005419 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005420 InitExprs.push_back(castExpr);
5421
Steve Naroff01aec112009-12-06 21:14:13 +00005422 // Initialize the block descriptor.
5423 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005424
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005425 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5426 SourceLocation(), SourceLocation(),
5427 &Context->Idents.get(DescData.c_str()),
5428 Context->VoidPtrTy, 0,
5429 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005430 UnaryOperator *DescRefExpr =
5431 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5432 Context->VoidPtrTy,
5433 VK_LValue,
5434 SourceLocation()),
5435 UO_AddrOf,
5436 Context->getPointerType(Context->VoidPtrTy),
5437 VK_RValue, OK_Ordinary,
5438 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005439 InitExprs.push_back(DescRefExpr);
5440
Steve Narofffa15fd92008-10-28 20:29:00 +00005441 // Add initializers for any closure decl refs.
5442 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005443 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005445 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005446 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005447 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005448 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005449 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005450 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5451 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005452 if (HasLocalVariableExternalStorage(*I)) {
5453 QualType QT = (*I)->getType();
5454 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005455 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5456 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005457 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005458 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005459 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005460 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5461 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005462 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005463 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005464 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005465 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005466 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5467 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005468 if (HasLocalVariableExternalStorage(*I)) {
5469 QualType QT = (*I)->getType();
5470 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005471 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5472 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005473 }
5474
Steve Narofffa15fd92008-10-28 20:29:00 +00005475 }
Mike Stump1eb44332009-09-09 15:08:12 +00005476 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005477 }
5478 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005479 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005480 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005481 ValueDecl *ND = (*I);
5482 std::string Name(ND->getNameAsString());
5483 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005484 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005485 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5486 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005487 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005488 SourceLocation(), SourceLocation(),
5489 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005490 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5491 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5492
Daniel Dunbar4087f272010-08-17 22:39:59 +00005493 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005494 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5495 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005496 bool isNestedCapturedVar = false;
5497 if (block)
5498 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5499 ce = block->capture_end(); ci != ce; ++ci) {
5500 const VarDecl *variable = ci->getVariable();
5501 if (variable == ND && ci->isNested()) {
5502 assert (ci->isByRef() &&
5503 "SynthBlockInitExpr - captured block variable is not byref");
5504 isNestedCapturedVar = true;
5505 break;
5506 }
5507 }
5508 // captured nested byref variable has its address passed. Do not take
5509 // its address again.
5510 if (!isNestedCapturedVar)
5511 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005512 Context->getPointerType(Exp->getType()),
5513 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005514 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005515 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005516 }
5517 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005518 if (ImportedBlockDecls.size()) {
5519 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5520 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005521 unsigned IntSize =
5522 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005523 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5524 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005525 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005526 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005527 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005528 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005529 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005530 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005531 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005532 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005533 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005534 BlockDeclRefs.clear();
5535 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005536 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005537 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005538 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005539 ImportedBlockDecls.clear();
5540 return NewRep;
5541}
5542
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005543bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5544 if (const ObjCForCollectionStmt * CS =
5545 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5546 return CS->getElement() == DS;
5547 return false;
5548}
5549
Steve Narofffa15fd92008-10-28 20:29:00 +00005550//===----------------------------------------------------------------------===//
5551// Function Body / Expression rewriting
5552//===----------------------------------------------------------------------===//
5553
5554Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005555 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005556 isa<DoStmt>(S) || isa<ForStmt>(S))
5557 Stmts.push_back(S);
5558 else if (isa<ObjCForCollectionStmt>(S)) {
5559 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005560 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005561 }
Mike Stump1eb44332009-09-09 15:08:12 +00005562
John McCall4b9c2d22011-11-06 09:01:30 +00005563 // Pseudo-object operations and ivar references need special
5564 // treatment because we're going to recursively rewrite them.
5565 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5566 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5567 return RewritePropertyOrImplicitSetter(PseudoOp);
5568 } else {
5569 return RewritePropertyOrImplicitGetter(PseudoOp);
5570 }
5571 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5572 return RewriteObjCIvarRefExpr(IvarRefExpr);
5573 }
5574
Steve Narofffa15fd92008-10-28 20:29:00 +00005575 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005576
Steve Narofffa15fd92008-10-28 20:29:00 +00005577 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005578 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005579 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00005580 Stmt *childStmt = (*CI);
5581 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005582 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00005583 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005584 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005585 }
Mike Stump1eb44332009-09-09 15:08:12 +00005586
Steve Narofffa15fd92008-10-28 20:29:00 +00005587 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005588 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005589 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5590 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005591 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005592 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005593 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005594 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005595 Stmt *SaveCurrentBody = CurrentBody;
5596 CurrentBody = BE->getBody();
5597 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005598 // block literal on rhs of a property-dot-sytax assignment
5599 // must be replaced by its synthesize ast so getRewrittenText
5600 // works as expected. In this case, what actually ends up on RHS
5601 // is the blockTranscribed which is the helper function for the
5602 // block literal; as in: self.c = ^() {[ace ARR];};
5603 bool saveDisableReplaceStmt = DisableReplaceStmt;
5604 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005605 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005606 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005607 CurrentBody = SaveCurrentBody;
5608 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005609 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005610 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005611 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005612 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005614 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5615
Steve Narofffa15fd92008-10-28 20:29:00 +00005616 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005617 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005618 return blockTranscribed;
5619 }
5620 // Handle specific things.
5621 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5622 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005623
Steve Narofffa15fd92008-10-28 20:29:00 +00005624 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5625 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005626
Steve Narofffa15fd92008-10-28 20:29:00 +00005627 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5628 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005629
Steve Narofffa15fd92008-10-28 20:29:00 +00005630 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005631#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005632 // Before we rewrite it, put the original message expression in a comment.
5633 SourceLocation startLoc = MessExpr->getLocStart();
5634 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005635
Steve Narofffa15fd92008-10-28 20:29:00 +00005636 const char *startBuf = SM->getCharacterData(startLoc);
5637 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005638
Steve Narofffa15fd92008-10-28 20:29:00 +00005639 std::string messString;
5640 messString += "// ";
5641 messString.append(startBuf, endBuf-startBuf+1);
5642 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005643
5644 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 // InsertText(clang::SourceLocation, char const*, unsigned int).
5646 // InsertText(startLoc, messString.c_str(), messString.size());
5647 // Tried this, but it didn't work either...
5648 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005649#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005650 return RewriteMessageExpr(MessExpr);
5651 }
Mike Stump1eb44332009-09-09 15:08:12 +00005652
Steve Narofffa15fd92008-10-28 20:29:00 +00005653 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5654 return RewriteObjCTryStmt(StmtTry);
5655
5656 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5657 return RewriteObjCSynchronizedStmt(StmtTry);
5658
5659 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5660 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005661
Steve Narofffa15fd92008-10-28 20:29:00 +00005662 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5663 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005664
5665 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005666 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005667 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005668 OrigStmtRange.getEnd());
5669 if (BreakStmt *StmtBreakStmt =
5670 dyn_cast<BreakStmt>(S))
5671 return RewriteBreakStmt(StmtBreakStmt);
5672 if (ContinueStmt *StmtContinueStmt =
5673 dyn_cast<ContinueStmt>(S))
5674 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005675
5676 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005677 // and cast exprs.
5678 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5679 // FIXME: What we're doing here is modifying the type-specifier that
5680 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005681 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005682 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5683 // the context of an ObjCForCollectionStmt. For example:
5684 // NSArray *someArray;
5685 // for (id <FooProtocol> index in someArray) ;
5686 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5687 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005688 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005689 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005690
Steve Narofffa15fd92008-10-28 20:29:00 +00005691 // Blocks rewrite rules.
5692 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5693 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005694 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005695 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005696 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005697 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005698 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005699 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005700 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005701 if (VD->hasAttr<BlocksAttr>()) {
5702 static unsigned uniqueByrefDeclCount = 0;
5703 assert(!BlockByRefDeclNo.count(ND) &&
5704 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5705 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005706 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005707 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005708 else
5709 RewriteTypeOfDecl(VD);
5710 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005711 }
Richard Smith162e1c12011-04-15 14:24:37 +00005712 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005713 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005714 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005715 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005716 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5717 }
5718 }
5719 }
Mike Stump1eb44332009-09-09 15:08:12 +00005720
Steve Narofffa15fd92008-10-28 20:29:00 +00005721 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5722 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005723
5724 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005725 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5726 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005727 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5728 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005729 && "Statement stack mismatch");
5730 Stmts.pop_back();
5731 }
5732 // Handle blocks rewriting.
5733 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5734 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005735 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005736 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005737 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5738 ValueDecl *VD = DRE->getDecl();
5739 if (VD->hasAttr<BlocksAttr>())
5740 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005741 if (HasLocalVariableExternalStorage(VD))
5742 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005743 }
5744
Steve Narofffa15fd92008-10-28 20:29:00 +00005745 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005746 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005747 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005748 ReplaceStmt(S, BlockCall);
5749 return BlockCall;
5750 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005751 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005752 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 RewriteCastExpr(CE);
5754 }
5755#if 0
5756 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005757 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5758 ICE->getSubExpr(),
5759 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005760 // Get the new text.
5761 std::string SStr;
5762 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005763 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 const std::string &Str = Buf.str();
5765
5766 printf("CAST = %s\n", &Str[0]);
5767 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5768 delete S;
5769 return Replacement;
5770 }
5771#endif
5772 // Return this stmt unmodified.
5773 return S;
5774}
5775
Steve Naroff3d7e7862009-12-05 15:55:59 +00005776void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5777 for (RecordDecl::field_iterator i = RD->field_begin(),
5778 e = RD->field_end(); i != e; ++i) {
5779 FieldDecl *FD = *i;
5780 if (isTopLevelBlockPointerType(FD->getType()))
5781 RewriteBlockPointerDecl(FD);
5782 if (FD->getType()->isObjCQualifiedIdType() ||
5783 FD->getType()->isObjCQualifiedInterfaceType())
5784 RewriteObjCQualifiedInterfaceTypes(FD);
5785 }
5786}
5787
Steve Narofffa15fd92008-10-28 20:29:00 +00005788/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5789/// main file of the input.
5790void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5791 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005792 if (FD->isOverloadedOperator())
5793 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005794
Steve Narofffa15fd92008-10-28 20:29:00 +00005795 // Since function prototypes don't have ParmDecl's, we check the function
5796 // prototype. This enables us to rewrite function declarations and
5797 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005798 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005799
Sebastian Redld3a413d2009-04-26 20:35:05 +00005800 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005801 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005802 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005803 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005804 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005805 Body =
5806 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5807 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005808 CurrentBody = 0;
5809 if (PropParentMap) {
5810 delete PropParentMap;
5811 PropParentMap = 0;
5812 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005813 // This synthesizes and inserts the block "impl" struct, invoke function,
5814 // and any copy/dispose helper functions.
5815 InsertBlockLiteralsWithinFunction(FD);
5816 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005817 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005818 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005819 return;
5820 }
5821 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005822 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005823 CurMethodDef = MD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005824 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005825 Body =
5826 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5827 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005828 CurrentBody = 0;
5829 if (PropParentMap) {
5830 delete PropParentMap;
5831 PropParentMap = 0;
5832 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005833 InsertBlockLiteralsWithinMethod(MD);
5834 CurMethodDef = 0;
5835 }
5836 }
5837 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5838 ClassImplementation.push_back(CI);
5839 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5840 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005841 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005842 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005843 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5844 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005845 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005846 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005847 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005848 CheckFunctionPointerDecl(VD->getType(), VD);
5849 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005850 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005851 RewriteCastExpr(CE);
5852 }
5853 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005854 } else if (VD->getType()->isRecordType()) {
5855 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00005856 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005857 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005858 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005859 if (VD->getInit()) {
5860 GlobalVarDecl = VD;
Steve Naroff8599e7a2008-12-08 16:43:47 +00005861 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005862 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005863 CurrentBody = 0;
5864 if (PropParentMap) {
5865 delete PropParentMap;
5866 PropParentMap = 0;
5867 }
Mike Stump1eb44332009-09-09 15:08:12 +00005868 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005869 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005870 GlobalVarDecl = 0;
5871
5872 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005873 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005874 RewriteCastExpr(CE);
5875 }
5876 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 return;
5878 }
Richard Smith162e1c12011-04-15 14:24:37 +00005879 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005880 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005881 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005882 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005883 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5884 return;
5885 }
5886 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
John McCall5e1cdac2011-10-07 06:10:15 +00005887 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005888 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 return;
5890 }
5891 // Nothing yet.
5892}
5893
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005894void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005895 if (Diags.hasErrorOccurred())
5896 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005897
Steve Narofffa15fd92008-10-28 20:29:00 +00005898 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005899
Steve Naroff621edce2009-04-29 16:37:50 +00005900 // Here's a great place to add any extra declarations that may be needed.
5901 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005902 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005903 E = ProtocolExprDecls.end(); I != E; ++I)
5904 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5905
Benjamin Kramerd999b372010-02-14 14:14:16 +00005906 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005907 if (ClassImplementation.size() || CategoryImplementation.size())
5908 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005909
Steve Narofffa15fd92008-10-28 20:29:00 +00005910 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5911 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005912 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005913 Rewrite.getRewriteBufferFor(MainFileID)) {
5914 //printf("Changed:\n");
5915 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5916 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005917 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005918 }
Steve Narofface66252008-11-13 20:07:04 +00005919
Steve Naroff621edce2009-04-29 16:37:50 +00005920 if (ClassImplementation.size() || CategoryImplementation.size() ||
5921 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005922 // Rewrite Objective-c meta data*
5923 std::string ResultStr;
5924 SynthesizeMetaDataIntoBuffer(ResultStr);
5925 // Emit metadata.
5926 *OutFile << ResultStr;
5927 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005928 OutFile->flush();
5929}