blob: 87272ebe9f23f3a525b3c8417b11868e1939f34b [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/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 {
36 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
37 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 */
41 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
42 helpers */
43 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
44 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;
Chris Lattnere365c502007-11-30 22:25:36 +000058 Diagnostic &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
Ted Kremeneka526c5c2008-01-07 19:49:32 +000070 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
72 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;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000076 llvm::SmallVector<Stmt *, 32> Stmts;
77 llvm::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;
Eli Friedman66d6f042009-05-18 22:20:00 +0000116 llvm::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.
124 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000125 llvm::SmallVector<int, 32> InnerDeclRefsCount;
126 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
127
Steve Naroff54055232008-10-27 17:20:55 +0000128 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000131 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
133 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
134 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 Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
142 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
145 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000158 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000159 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000160 virtual void Initialize(ASTContext &context);
161
Chris Lattnerf04da132007-10-24 17:06:59 +0000162 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000163 virtual void HandleTopLevelDecl(DeclGroupRef D) {
164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
165 HandleTopLevelSingleDecl(*I);
166 }
167 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000168 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000169 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000170 Diagnostic &D, const LangOptions &LOpts,
171 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000172
173 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000175 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000177 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Steve Naroff4c3580e2008-12-04 23:50:32 +0000180 if (ReplacingStmt)
181 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000182
Steve Naroffb619d952008-12-09 12:56:34 +0000183 if (DisableReplaceStmt)
184 return; // Used when rewriting the assignment of a property setter.
185
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000187 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000188 ReplacedNodes[Old] = New;
189 return;
190 }
191 if (SilenceRewriteMacroWarning)
192 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000193 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
194 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000195 }
Steve Naroffb619d952008-12-09 12:56:34 +0000196
197 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
198 // Measaure the old text.
199 int Size = Rewrite.getRangeSize(SrcRange);
200 if (Size == -1) {
201 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
202 << Old->getSourceRange();
203 return;
204 }
205 // Get the new text.
206 std::string SStr;
207 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000208 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000209 const std::string &Str = S.str();
210
211 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000212 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000213 ReplacedNodes[Old] = New;
214 return;
215 }
216 if (SilenceRewriteMacroWarning)
217 return;
218 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
219 << Old->getSourceRange();
220 }
221
Benjamin Kramerd999b372010-02-14 14:14:16 +0000222 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000223 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000224 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000225 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000226 SilenceRewriteMacroWarning)
227 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000229 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattneraadaf782008-01-31 19:51:04 +0000232 void RemoveText(SourceLocation Loc, unsigned StrLen) {
233 // If removal succeeded or warning disabled return with no warning.
234 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
235 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
238 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000239
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000243 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 SilenceRewriteMacroWarning)
245 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattneraadaf782008-01-31 19:51:04 +0000247 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
248 }
Mike Stump1eb44332009-09-09 15:08:12 +0000249
Chris Lattnerf04da132007-10-24 17:06:59 +0000250 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000251 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000252 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000253 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000254 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000255 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
256 ObjCImplementationDecl *IMD,
257 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000259 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000260 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
264 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000271 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000273 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000274 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000275 bool needToScanForQualifiers(QualType T);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000276 bool isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000277 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000278 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000279 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Chris Lattnerf04da132007-10-24 17:06:59 +0000281 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000282 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000283 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Steve Naroff8599e7a2008-12-08 16:43:47 +0000285 Stmt *CurrentBody;
286 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000289 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
290 bool &replaced);
291 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000292 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000293 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000294 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000295 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000296 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000297 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000298 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000299 void WarnAboutReturnGotoStmts(Stmt *S);
300 void HasReturnStmts(Stmt *S, bool &hasReturns);
301 void RewriteTryReturnStmts(Stmt *S);
302 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000303 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000304 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
306 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000310 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000311 Expr **args, unsigned nargs,
312 SourceLocation StartLoc=SourceLocation(),
313 SourceLocation EndLoc=SourceLocation());
314 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
315 SourceLocation StartLoc=SourceLocation(),
316 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000317 Stmt *RewriteBreakStmt(BreakStmt *S);
318 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000319 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Steve Naroff09b266e2007-10-30 23:14:51 +0000321 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000322 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000323 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000324 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000325 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000326 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000327 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000328 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000329 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000330 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattnerf04da132007-10-24 17:06:59 +0000332 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000333 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000334 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000336 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000337 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Douglas Gregor653f1b12009-04-23 01:02:12 +0000339 template<typename MethodIterator>
340 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
341 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000342 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000343 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000344 const char *ClassName,
345 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Steve Naroff621edce2009-04-29 16:37:50 +0000347 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
348 const char *prefix,
349 const char *ClassName,
350 std::string &Result);
351 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000352 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000353 const char *ClassName,
354 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000355 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000356 std::string &Result);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000357 void SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +0000358 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockCall(CallExpr *Exp);
372 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000373 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000374 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000375 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000376 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000377 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000378
379 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000380 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000382 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000383 std::string SynthesizeBlockImpl(BlockExpr *CE,
384 std::string Tag, std::string Desc);
385 std::string SynthesizeBlockDescriptor(std::string DescTag,
386 std::string ImplTag,
387 int i, const char *funcName,
388 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000389 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000390 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000391 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000392 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Steve Naroff54055232008-10-27 17:20:55 +0000394 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000395 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000396 void GetInnerBlockDeclRefExprs(Stmt *S,
397 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000398 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Steve Naroff54055232008-10-27 17:20:55 +0000400 // We avoid calling Type::isBlockPointerType(), since it operates on the
401 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000402 bool isTopLevelBlockPointerType(QualType T) {
403 return isa<BlockPointerType>(T);
404 }
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 // FIXME: This predicate seems like it would be useful to add to ASTContext.
407 bool isObjCType(QualType T) {
408 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
409 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Steve Naroff54055232008-10-27 17:20:55 +0000411 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Naroff54055232008-10-27 17:20:55 +0000413 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
414 OCT == Context->getCanonicalType(Context->getObjCClassType()))
415 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Ted Kremenek6217b802009-07-29 21:53:49 +0000417 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000418 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000419 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000420 return true;
421 }
422 return false;
423 }
424 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000425 void GetExtentOfArgList(const char *Name, const char *&LParen,
426 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000427 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Steve Narofffa15fd92008-10-28 20:29:00 +0000429 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000430 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
431 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Steve Naroff621edce2009-04-29 16:37:50 +0000433 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000435 if (From[i] == '"')
436 To += "\\\"";
437 else
438 To += From[i];
439 }
440 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000441 };
John McCall9d125032010-01-15 18:39:57 +0000442
443 // Helper function: create a CStyleCastExpr with trivial type source info.
444 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
445 CastExpr::CastKind Kind, Expr *E) {
446 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
447 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
448 SourceLocation(), SourceLocation());
449 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000450}
451
Mike Stump1eb44332009-09-09 15:08:12 +0000452void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
453 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000454 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000455 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000456 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000457 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000458 // All the args are checked/rewritten. Don't call twice!
459 RewriteBlockPointerDecl(D);
460 break;
461 }
462 }
463}
464
465void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000466 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000467 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000468 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000469}
470
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000471static bool IsHeaderFile(const std::string &Filename) {
472 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000474 if (DotPos == std::string::npos) {
475 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000476 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
480 // C header: .h
481 // C++ header: .hh or .H;
482 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000483}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000484
Eli Friedman66d6f042009-05-18 22:20:00 +0000485RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000486 Diagnostic &D, const LangOptions &LOpts,
487 bool silenceMacroWarn)
488 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
489 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000490 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000491 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000492 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000493 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000494 "rewriter doesn't support user-specified control flow semantics "
495 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000496}
497
Eli Friedmanbce831b2009-05-18 22:29:17 +0000498ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
499 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000501 const LangOptions &LOpts,
502 bool SilenceRewriteMacroWarning) {
503 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000504}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000505
Steve Naroffb29b4272008-04-14 22:03:09 +0000506void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000507 Context = &context;
508 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000509 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000510 MsgSendFunctionDecl = 0;
511 MsgSendSuperFunctionDecl = 0;
512 MsgSendStretFunctionDecl = 0;
513 MsgSendSuperStretFunctionDecl = 0;
514 MsgSendFpretFunctionDecl = 0;
515 GetClassFunctionDecl = 0;
516 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000517 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000518 SelGetUidFunctionDecl = 0;
519 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 ConstantStringClassReference = 0;
521 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000522 CurMethodDef = 0;
523 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000524 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000525 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000526 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000527 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000528 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000529 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000530 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000531 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000532 PropParentMap = 0;
533 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000534 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000535 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000537 // Get the ID and start/end of the main file.
538 MainFileID = SM->getMainFileID();
539 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
540 MainFileStart = MainBuf->getBufferStart();
541 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattner2c78b872009-04-14 23:22:57 +0000543 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000545 // declaring objc_selector outside the parameter list removes a silly
546 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000547 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000548 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000550 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000552 if (LangOpts.Microsoft) {
553 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000554 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
555 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000556 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000557 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000558 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
560 Preamble += "typedef struct objc_object Protocol;\n";
561 Preamble += "#define _REWRITER_typedef_Protocol\n";
562 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000563 if (LangOpts.Microsoft) {
564 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
565 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
566 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000567 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000577 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000580 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
581 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000582 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000584 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
586 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
587 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
588 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000589 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000590 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
592 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
593 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000594 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
595 Preamble += "struct __objcFastEnumerationState {\n\t";
596 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000597 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000598 Preamble += "unsigned long *mutationsPtr;\n\t";
599 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "#define __FASTENUMERATIONSTATE\n";
602 Preamble += "#endif\n";
603 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
604 Preamble += "struct __NSConstantStringImpl {\n";
605 Preamble += " int *isa;\n";
606 Preamble += " int flags;\n";
607 Preamble += " char *str;\n";
608 Preamble += " long length;\n";
609 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000610 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
611 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
612 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000613 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000614 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
616 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000617 // Blocks preamble.
618 Preamble += "#ifndef BLOCK_IMPL\n";
619 Preamble += "#define BLOCK_IMPL\n";
620 Preamble += "struct __block_impl {\n";
621 Preamble += " void *isa;\n";
622 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000623 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000624 Preamble += " void *FuncPtr;\n";
625 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000626 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000627 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000628 Preamble += "extern \"C\" __declspec(dllexport) "
629 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000630 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
631 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
632 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
633 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
635 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000636 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
637 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
638 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000639 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000640 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
642 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000643 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000644 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000645 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000646 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000647 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000648 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000649 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000650 Preamble += "#define __weak\n";
651 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000652 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
653 // as this avoids warning in any 64bit/32bit compilation model.
654 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000655}
656
657
Chris Lattnerf04da132007-10-24 17:06:59 +0000658//===----------------------------------------------------------------------===//
659// Top Level Driver Code
660//===----------------------------------------------------------------------===//
661
Chris Lattner682bf922009-03-29 16:50:03 +0000662void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000663 if (Diags.hasErrorOccurred())
664 return;
665
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000666 // Two cases: either the decl could be in the main file, or it could be in a
667 // #included file. If the former, rewrite it now. If the later, check to see
668 // if we rewrote the #include/#import.
669 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000670 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000672 // If this is for a builtin, ignore it.
673 if (Loc.isInvalid()) return;
674
Steve Naroffebf2b562007-10-23 23:50:29 +0000675 // Look for built-in declarations that we need to refer during the rewrite.
676 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000677 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000678 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000679 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000680 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000681 ConstantStringClassReference = FVD;
682 return;
683 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000684 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000685 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000686 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000687 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000689 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000690 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000691 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000692 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000693 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
694 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000695 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
696 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000697 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000698 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000699 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000700 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000701 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000702 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703}
704
Chris Lattnerf04da132007-10-24 17:06:59 +0000705//===----------------------------------------------------------------------===//
706// Syntactic (non-AST) Rewriting Code
707//===----------------------------------------------------------------------===//
708
Steve Naroffb29b4272008-04-14 22:03:09 +0000709void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000710 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000711 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
712 const char *MainBufStart = MainBuf.begin();
713 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000714 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000716 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000717 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
718 if (*BufPtr == '#') {
719 if (++BufPtr == MainBufEnd)
720 return;
721 while (*BufPtr == ' ' || *BufPtr == '\t')
722 if (++BufPtr == MainBufEnd)
723 return;
724 if (!strncmp(BufPtr, "import", ImportLen)) {
725 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000726 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000727 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000728 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000729 BufPtr += ImportLen;
730 }
731 }
732 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000733}
734
Steve Naroffb29b4272008-04-14 22:03:09 +0000735void RewriteObjC::RewriteTabs() {
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000736 llvm::StringRef MainBuf = SM->getBufferData(MainFileID);
737 const char *MainBufStart = MainBuf.begin();
738 const char *MainBufEnd = MainBuf.end();
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Chris Lattnerf04da132007-10-24 17:06:59 +0000740 // Loop over the whole file, looking for tabs.
741 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
742 if (*BufPtr != '\t')
743 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000744
Chris Lattnerf04da132007-10-24 17:06:59 +0000745 // Okay, we found a tab. This tab will turn into at least one character,
746 // but it depends on which 'virtual column' it is in. Compute that now.
747 unsigned VCol = 0;
748 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
749 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
750 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnerf04da132007-10-24 17:06:59 +0000752 // Okay, now that we know the virtual column, we know how many spaces to
753 // insert. We assume 8-character tab-stops.
754 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000757 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
758 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Chris Lattnerf04da132007-10-24 17:06:59 +0000760 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000761 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000762 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000763}
764
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
766 ObjCIvarDecl *OID) {
767 std::string S;
768 S = "((struct ";
769 S += ClassDecl->getIdentifier()->getName();
770 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000771 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772 return S;
773}
774
Steve Naroffa0876e82008-12-02 17:36:43 +0000775void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
776 ObjCImplementationDecl *IMD,
777 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000778 static bool objcGetPropertyDefined = false;
779 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000780 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000781 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000782 const char *startBuf = SM->getCharacterData(startLoc);
783 assert((*startBuf == '@') && "bogus @synthesize location");
784 const char *semiBuf = strchr(startBuf, ';');
785 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000786 SourceLocation onePastSemiLoc =
787 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000788
789 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
790 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000795 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000797 if (!OID)
798 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000799 unsigned Attributes = PD->getPropertyAttributes();
800 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
801 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
802 ObjCPropertyDecl::OBJC_PR_copy));
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000803 std::string Getr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 if (GenGetProperty && !objcGetPropertyDefined) {
805 objcGetPropertyDefined = true;
806 // FIXME. Is this attribute correct in all cases?
807 Getr = "\nextern \"C\" __declspec(dllimport) "
808 "id objc_getProperty(id, SEL, long, bool);\n";
809 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000810 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
Steve Naroff3539cdb2008-12-02 17:54:50 +0000813 // See objc-act.c:objc_synthesize_new_getter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
826 Getr += "(";
827 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
828 if (i) Getr += ", ";
829 std::string ParamStr = FT->getArgType(i).getAsString();
830 Getr += ParamStr;
831 }
832 if (FT->isVariadic()) {
833 if (FT->getNumArgs()) Getr += ", ";
834 Getr += "...";
835 }
836 Getr += ")";
837 } else
838 Getr += "()";
839 }
840 Getr += ";\n";
841 Getr += "return (_TYPE)";
842 Getr += "objc_getProperty(self, _cmd, ";
843 SynthesizeIvarOffsetComputation(ClassDecl, OID, Getr);
844 Getr += ", 1)";
845 }
846 else
847 Getr += "return " + getIvarAccessString(ClassDecl, OID);
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000848 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000849 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000850 if (PD->isReadOnly())
851 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroffeb0646c2008-12-02 15:48:25 +0000853 // Generate the 'setter' function.
854 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000855 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
856 ObjCPropertyDecl::OBJC_PR_copy);
857 if (GenSetProperty && !objcSetPropertyDefined) {
858 objcSetPropertyDefined = true;
859 // FIXME. Is this attribute correct in all cases?
860 Setr = "\nextern \"C\" __declspec(dllimport) "
861 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
862 }
863
Steve Naroffeb0646c2008-12-02 15:48:25 +0000864 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000865 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000866 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000867 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000868 if (GenSetProperty) {
869 Setr += "objc_setProperty (self, _cmd, ";
870 SynthesizeIvarOffsetComputation(ClassDecl, OID, Setr);
871 Setr += ", (id)";
872 Setr += PD->getNameAsCString();
873 Setr += ", ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
875 Setr += "0, ";
876 else
877 Setr += "1, ";
878 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
879 Setr += "1)";
880 else
881 Setr += "0)";
882 }
883 else {
884 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
885 Setr += PD->getNameAsCString();
886 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000887 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000888 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000889}
Chris Lattner8a12c272007-10-11 18:38:32 +0000890
Steve Naroffb29b4272008-04-14 22:03:09 +0000891void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000892 // Get the start location and compute the semi location.
893 SourceLocation startLoc = ClassDecl->getLocation();
894 const char *startBuf = SM->getCharacterData(startLoc);
895 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattnerf04da132007-10-24 17:06:59 +0000897 // Translate to typedef's that forward reference structs with the same name
898 // as the class. As a convenience, we include the original declaration
899 // as a comment.
900 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000901 typedefString += "// @class ";
902 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
903 I != E; ++I) {
904 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
905 typedefString += ForwardDecl->getNameAsString();
906 if (I+1 != E)
907 typedefString += ", ";
908 else
909 typedefString += ";\n";
910 }
911
Chris Lattner67956052009-02-20 18:04:31 +0000912 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
913 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000914 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000915 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000916 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000919 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000920 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000921 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000922 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000923 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Steve Naroff934f2762007-10-24 22:48:43 +0000926 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000928}
929
Steve Naroffb29b4272008-04-14 22:03:09 +0000930void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000931 // When method is a synthesized one, such as a getter/setter there is
932 // nothing to rewrite.
933 if (Method->isSynthesized())
934 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000935 SourceLocation LocStart = Method->getLocStart();
936 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Chris Lattner30fc9332009-02-04 01:06:56 +0000938 if (SM->getInstantiationLineNumber(LocEnd) >
939 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 InsertText(LocStart, "#if 0\n");
941 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000942 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000943 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000944 }
945}
946
Mike Stump1eb44332009-09-09 15:08:12 +0000947void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000948 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Benjamin Kramerd999b372010-02-14 14:14:16 +0000950 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000951 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000952}
953
Steve Naroffb29b4272008-04-14 22:03:09 +0000954void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000955 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000956
Steve Naroff423cb562007-10-30 13:30:57 +0000957 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000958 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000960 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
961 E = CatDecl->prop_end(); I != E; ++I)
962 RewriteProperty(*I);
963
Mike Stump1eb44332009-09-09 15:08:12 +0000964 for (ObjCCategoryDecl::instmeth_iterator
965 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000968 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000969 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000970 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000971 RewriteMethodDeclaration(*I);
972
Steve Naroff423cb562007-10-30 13:30:57 +0000973 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000974 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000975}
976
Steve Naroffb29b4272008-04-14 22:03:09 +0000977void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000978 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Steve Naroff752d6ef2007-10-30 16:42:30 +0000980 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000981 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000982
983 for (ObjCProtocolDecl::instmeth_iterator
984 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000985 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000986 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000987 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000988 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000989 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000990 RewriteMethodDeclaration(*I);
991
Steve Naroff752d6ef2007-10-30 16:42:30 +0000992 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000993 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000994 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000995
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000996 // Must comment out @optional/@required
997 const char *startBuf = SM->getCharacterData(LocStart);
998 const char *endBuf = SM->getCharacterData(LocEnd);
999 for (const char *p = startBuf; p < endBuf; p++) {
1000 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001001 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001002 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001004 }
1005 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001006 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001009 }
1010 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001011}
1012
Steve Naroffb29b4272008-04-14 22:03:09 +00001013void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001014 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001015 if (LocStart.isInvalid())
1016 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001017 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001018 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001019}
1020
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001021void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1022 const FunctionType *&FPRetType) {
1023 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001024 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001025 else if (T->isFunctionPointerType() ||
1026 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001027 // needs special handling, since pointer-to-functions have special
1028 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001029 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001030 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001032 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001033 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001034 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001035 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +00001036 ResultStr += FPRetType->getResultType().getAsString();
1037 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001038 }
1039 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001040 ResultStr += T.getAsString();
1041}
1042
1043void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
1044 std::string &ResultStr) {
1045 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1046 const FunctionType *FPRetType = 0;
1047 ResultStr += "\nstatic ";
1048 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001049 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001051 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001052 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001054 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001055 NameStr += "_I_";
1056 else
1057 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001059 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001060 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001061
1062 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001063 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001064 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001065 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001068 {
1069 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 int len = selString.size();
1071 for (int i = 0; i < len; i++)
1072 if (selString[i] == ':')
1073 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001074 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001076 // Remember this name for metadata emission
1077 MethodInternalNames[OMD] = NameStr;
1078 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 // Rewrite arguments
1081 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001084 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001085 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001087 if (!LangOpts.Microsoft) {
1088 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1089 ResultStr += "struct ";
1090 }
1091 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001092 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001093 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001094 }
1095 else
Steve Naroff621edce2009-04-29 16:37:50 +00001096 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001099 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001101
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001103 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1104 E = OMD->param_end(); PI != E; ++PI) {
1105 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001106 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001107 if (PDecl->getType()->isObjCQualifiedIdType()) {
1108 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001110 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001112 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001113 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001114 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001115 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1116 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001117 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001118 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001119 ResultStr += Name;
1120 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001121 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001122 if (OMD->isVariadic())
1123 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001124 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001125
Steve Naroff76e429d2008-07-16 14:40:40 +00001126 if (FPRetType) {
1127 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Steve Naroff76e429d2008-07-16 14:40:40 +00001129 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001130 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001131 ResultStr += "(";
1132 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1133 if (i) ResultStr += ", ";
1134 std::string ParamStr = FT->getArgType(i).getAsString();
1135 ResultStr += ParamStr;
1136 }
1137 if (FT->isVariadic()) {
1138 if (FT->getNumArgs()) ResultStr += ", ";
1139 ResultStr += "...";
1140 }
1141 ResultStr += ")";
1142 } else {
1143 ResultStr += "()";
1144 }
1145 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001147void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001148 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1149 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001150
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001151 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001153 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001154 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1155 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001156 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001158 ObjCMethodDecl *OMD = *I;
1159 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001161 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001162
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 const char *startBuf = SM->getCharacterData(LocStart);
1164 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001165 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 }
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001168 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001169 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1170 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001171 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001172 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001173 ObjCMethodDecl *OMD = *I;
1174 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001175 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001176 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001180 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001181 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001182 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001183 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001184 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001185 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001186 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001187 }
1188
Benjamin Kramerd999b372010-02-14 14:14:16 +00001189 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001190}
1191
Steve Naroffb29b4272008-04-14 22:03:09 +00001192void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001193 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001195 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001196 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001197 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001198 ResultStr += "\n";
1199 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001200 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001201 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001202 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001203 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001204 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001205 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001207 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001209
1210 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001212 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001213 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001214 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001215 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001216 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001217 for (ObjCInterfaceDecl::classmeth_iterator
1218 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001219 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001220 RewriteMethodDeclaration(*I);
1221
Steve Naroff2feac5e2007-10-30 03:43:13 +00001222 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001224}
1225
Steve Naroffb619d952008-12-09 12:56:34 +00001226Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1227 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001228 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1229 // This allows us to reuse all the fun and games in SynthMessageExpr().
1230 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1231 ObjCMessageExpr *MsgExpr;
1232 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1233 llvm::SmallVector<Expr *, 1> ExprVec;
1234 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Steve Naroff8599e7a2008-12-08 16:43:47 +00001236 Stmt *Receiver = PropRefExpr->getBase();
1237 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1238 if (PRE && PropGetters[PRE]) {
1239 // This allows us to handle chain/nested property getters.
1240 Receiver = PropGetters[PRE];
1241 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001242 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001243 PDecl->getSetterName(), PDecl->getType(),
1244 PDecl->getSetterMethodDecl(),
1245 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001246 &ExprVec[0], 1);
1247 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Steve Naroffc77a6362008-12-04 16:24:46 +00001249 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001250 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001251 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001252 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1253 // to things that stay around.
1254 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001255 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001256}
1257
Steve Naroffc77a6362008-12-04 16:24:46 +00001258Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001259 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1260 // This allows us to reuse all the fun and games in SynthMessageExpr().
1261 ObjCMessageExpr *MsgExpr;
1262 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001263
Steve Naroff8599e7a2008-12-08 16:43:47 +00001264 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Steve Naroff8599e7a2008-12-08 16:43:47 +00001266 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1267 if (PRE && PropGetters[PRE]) {
1268 // This allows us to handle chain/nested property getters.
1269 Receiver = PropGetters[PRE];
1270 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001271 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001272 PDecl->getGetterName(), PDecl->getType(),
1273 PDecl->getGetterMethodDecl(),
1274 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001275 0, 0);
1276
Steve Naroff4c3580e2008-12-04 23:50:32 +00001277 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001278
1279 if (!PropParentMap)
1280 PropParentMap = new ParentMap(CurrentBody);
1281
1282 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1283 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1284 // We stash away the ReplacingStmt since actually doing the
1285 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1286 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001287 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1288 // to things that stay around.
1289 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001290 return PropRefExpr; // return the original...
1291 } else {
1292 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001293 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001294 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1295 // to things that stay around.
1296 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001297 return ReplacingStmt;
1298 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001299}
1300
Mike Stump1eb44332009-09-09 15:08:12 +00001301Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001302 SourceLocation OrigStart,
1303 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001304 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001305 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001306 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001307 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001308 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001309 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001310 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001311 // lookup which class implements the instance variable.
1312 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001313 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001314 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001315 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Steve Narofff0757612008-05-08 17:52:16 +00001317 // Synthesize an explicit cast to gain access to the ivar.
1318 std::string RecName = clsDeclared->getIdentifier()->getName();
1319 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001320 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001321 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001322 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001323 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1324 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001325 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1326 CastExpr::CK_Unknown,
1327 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001328 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001329 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1330 IV->getBase()->getLocEnd(),
1331 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001332 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001333 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001334 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001335 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1336 IV->getLocation(),
1337 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001338 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001339 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001340 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001341 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001342 // Cannot delete IV->getBase(), since PE points to it.
1343 // Replace the old base with the cast. This is important when doing
1344 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001345 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001346 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001347 }
Steve Naroff84472a82008-04-18 21:55:08 +00001348 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001349 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001350
Steve Naroff9f525972008-05-06 23:20:07 +00001351 // Explicit ivar refs need to have a cast inserted.
1352 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001353 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001354 ObjCInterfaceType *iFaceDecl =
1355 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001356 // lookup which class implements the instance variable.
1357 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001358 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001359 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001360 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Steve Naroff9f525972008-05-06 23:20:07 +00001362 // Synthesize an explicit cast to gain access to the ivar.
1363 std::string RecName = clsDeclared->getIdentifier()->getName();
1364 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001365 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001366 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001367 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001368 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1369 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001370 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1371 CastExpr::CK_Unknown,
1372 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001373 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001374 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001375 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001376 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001377 // Cannot delete IV->getBase(), since PE points to it.
1378 // Replace the old base with the cast. This is important when doing
1379 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001380 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001381 return IV;
1382 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001383 }
Steve Naroff84472a82008-04-18 21:55:08 +00001384 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001385}
1386
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001387Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1388 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1389 CI != E; ++CI) {
1390 if (*CI) {
1391 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1392 if (newStmt)
1393 *CI = newStmt;
1394 }
1395 }
1396 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1397 SourceRange OrigStmtRange = S->getSourceRange();
1398 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1399 replaced);
1400 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001401 }
1402 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1403 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1404 return newStmt;
1405 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001406 return S;
1407}
1408
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001409/// SynthCountByEnumWithState - To print:
1410/// ((unsigned int (*)
1411/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001412/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001413/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001414/// "countByEnumeratingWithState:objects:count:"),
1415/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416/// (id *)items, (unsigned int)16)
1417///
Steve Naroffb29b4272008-04-14 22:03:09 +00001418void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001419 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1420 "id *, unsigned int))(void *)objc_msgSend)";
1421 buf += "\n\t\t";
1422 buf += "((id)l_collection,\n\t\t";
1423 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1424 buf += "\n\t\t";
1425 buf += "&enumState, "
1426 "(id *)items, (unsigned int)16)";
1427}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001428
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001429/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1430/// statement to exit to its outer synthesized loop.
1431///
Steve Naroffb29b4272008-04-14 22:03:09 +00001432Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001433 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1434 return S;
1435 // replace break with goto __break_label
1436 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001438 SourceLocation startLoc = S->getLocStart();
1439 buf = "goto __break_label_";
1440 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001441 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001442
1443 return 0;
1444}
1445
1446/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1447/// statement to continue with its inner synthesized loop.
1448///
Steve Naroffb29b4272008-04-14 22:03:09 +00001449Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001450 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1451 return S;
1452 // replace continue with goto __continue_label
1453 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001455 SourceLocation startLoc = S->getLocStart();
1456 buf = "goto __continue_label_";
1457 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001458 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460 return 0;
1461}
1462
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001463/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001464/// It rewrites:
1465/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001467/// Into:
1468/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001469/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001470/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001471/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001473/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001474/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001475/// if (limit) {
1476/// unsigned long startMutations = *enumState.mutationsPtr;
1477/// do {
1478/// unsigned long counter = 0;
1479/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001480/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001482/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001483/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001484/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001485/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001486/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487/// objects:items count:16]);
1488/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001489/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001490/// }
1491/// else
1492/// elem = nil;
1493/// }
1494///
Steve Naroffb29b4272008-04-14 22:03:09 +00001495Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001496 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001497 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001498 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001499 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001500 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001501 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001504 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001505 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001506 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001507 std::string buf;
1508 buf = "\n{\n\t";
1509 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1510 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001511 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001512 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001513 if (ElementType->isObjCQualifiedIdType() ||
1514 ElementType->isObjCQualifiedInterfaceType())
1515 // Simply use 'id' for all qualified types.
1516 elementTypeAsString = "id";
1517 else
1518 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001519 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001520 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001521 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001522 buf += elementName;
1523 buf += ";\n\t";
1524 }
Chris Lattner06767512008-04-08 05:52:18 +00001525 else {
1526 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001527 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001528 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1529 if (VD->getType()->isObjCQualifiedIdType() ||
1530 VD->getType()->isObjCQualifiedInterfaceType())
1531 // Simply use 'id' for all qualified types.
1532 elementTypeAsString = "id";
1533 else
1534 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001535 }
Mike Stump1eb44332009-09-09 15:08:12 +00001536
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001537 // struct __objcFastEnumerationState enumState = { 0 };
1538 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1539 // id items[16];
1540 buf += "id items[16];\n\t";
1541 // id l_collection = (id)
1542 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001543 // Find start location of 'collection' the hard way!
1544 const char *startCollectionBuf = startBuf;
1545 startCollectionBuf += 3; // skip 'for'
1546 startCollectionBuf = strchr(startCollectionBuf, '(');
1547 startCollectionBuf++; // skip '('
1548 // find 'in' and skip it.
1549 while (*startCollectionBuf != ' ' ||
1550 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1551 (*(startCollectionBuf+3) != ' ' &&
1552 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1553 startCollectionBuf++;
1554 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001555
1556 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001557 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001558 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001559 SourceLocation rightParenLoc = S->getRParenLoc();
1560 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1561 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001562 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1565 // objects:items count:16];
1566 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001567 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001568 // ((unsigned int (*)
1569 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001570 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001572 // "countByEnumeratingWithState:objects:count:"),
1573 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574 // (id *)items, (unsigned int)16);
1575 buf += "unsigned long limit =\n\t\t";
1576 SynthCountByEnumWithState(buf);
1577 buf += ";\n\t";
1578 /// if (limit) {
1579 /// unsigned long startMutations = *enumState.mutationsPtr;
1580 /// do {
1581 /// unsigned long counter = 0;
1582 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001583 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001584 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001585 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586 buf += "if (limit) {\n\t";
1587 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1588 buf += "do {\n\t\t";
1589 buf += "unsigned long counter = 0;\n\t\t";
1590 buf += "do {\n\t\t\t";
1591 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1592 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1593 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001594 buf += " = (";
1595 buf += elementTypeAsString;
1596 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001597 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001598 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001600 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001601 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001602 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001603 /// objects:items count:16]);
1604 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001605 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001606 /// }
1607 /// else
1608 /// elem = nil;
1609 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001610 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 buf = ";\n\t";
1612 buf += "__continue_label_";
1613 buf += utostr(ObjCBcLabelNo.back());
1614 buf += ": ;";
1615 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001616 buf += "} while (counter < limit);\n\t";
1617 buf += "} while (limit = ";
1618 SynthCountByEnumWithState(buf);
1619 buf += ");\n\t";
1620 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001621 buf += " = ((";
1622 buf += elementTypeAsString;
1623 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001624 buf += "__break_label_";
1625 buf += utostr(ObjCBcLabelNo.back());
1626 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001627 buf += "}\n\t";
1628 buf += "else\n\t\t";
1629 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001630 buf += " = ((";
1631 buf += elementTypeAsString;
1632 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001633 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001634
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001635 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001636 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001637 if (isa<CompoundStmt>(S->getBody())) {
1638 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001639 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001640 } else {
1641 /* Need to treat single statements specially. For example:
1642 *
1643 * for (A *a in b) if (stuff()) break;
1644 * for (A *a in b) xxxyy;
1645 *
1646 * The following code simply scans ahead to the semi to find the actual end.
1647 */
1648 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1649 const char *semiBuf = strchr(stmtBuf, ';');
1650 assert(semiBuf && "Can't find ';'");
1651 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001652 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001653 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001654 Stmts.pop_back();
1655 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001656 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001657}
1658
Mike Stump1eb44332009-09-09 15:08:12 +00001659/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001660/// This routine rewrites @synchronized(expr) stmt;
1661/// into:
1662/// objc_sync_enter(expr);
1663/// @try stmt @finally { objc_sync_exit(expr); }
1664///
Steve Naroffb29b4272008-04-14 22:03:09 +00001665Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001666 // Get the start location and compute the semi location.
1667 SourceLocation startLoc = S->getLocStart();
1668 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001669
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001670 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001671
1672 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001673 buf = "objc_sync_enter((id)";
1674 const char *lparenBuf = startBuf;
1675 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001676 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001677 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1678 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001679 // been rewritten! (which implies the SourceLocation's are invalid).
1680 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001681 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001682 while (*endBuf != ')') endBuf--;
1683 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001684 buf = ");\n";
1685 // declare a new scope with two variables, _stack and _rethrow.
1686 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1687 buf += "int buf[18/*32-bit i386*/];\n";
1688 buf += "char *pointers[4];} _stack;\n";
1689 buf += "id volatile _rethrow = 0;\n";
1690 buf += "objc_exception_try_enter(&_stack);\n";
1691 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001692 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001693 startLoc = S->getSynchBody()->getLocEnd();
1694 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Steve Naroffc7089f12008-08-19 13:04:19 +00001696 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001697 SourceLocation lastCurlyLoc = startLoc;
1698 buf = "}\nelse {\n";
1699 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001700 buf += "}\n";
1701 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001702 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703
1704 std::string syncBuf;
1705 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001706 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1707 CastExpr::CK_Unknown,
1708 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001709 std::string syncExprBufS;
1710 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001711 syncExpr->printPretty(syncExprBuf, *Context, 0,
1712 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001713 syncBuf += syncExprBuf.str();
1714 syncBuf += ");";
1715
1716 buf += syncBuf;
1717 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001718 buf += "}\n";
1719 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Benjamin Kramerd999b372010-02-14 14:14:16 +00001721 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001722
1723 bool hasReturns = false;
1724 HasReturnStmts(S->getSynchBody(), hasReturns);
1725 if (hasReturns)
1726 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1727
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001728 return 0;
1729}
1730
Steve Naroffb85e77a2009-12-05 21:43:12 +00001731void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1732{
Steve Naroff8c565152008-12-05 17:03:39 +00001733 // Perform a bottom up traversal of all children.
1734 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1735 CI != E; ++CI)
1736 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001737 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001738
Steve Naroffb85e77a2009-12-05 21:43:12 +00001739 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001740 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001741 TryFinallyContainsReturnDiag);
1742 }
1743 return;
1744}
1745
Steve Naroffb85e77a2009-12-05 21:43:12 +00001746void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1747{
1748 // Perform a bottom up traversal of all children.
1749 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1750 CI != E; ++CI)
1751 if (*CI)
1752 HasReturnStmts(*CI, hasReturns);
1753
1754 if (isa<ReturnStmt>(S))
1755 hasReturns = true;
1756 return;
1757}
1758
1759void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1760 // Perform a bottom up traversal of all children.
1761 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1762 CI != E; ++CI)
1763 if (*CI) {
1764 RewriteTryReturnStmts(*CI);
1765 }
1766 if (isa<ReturnStmt>(S)) {
1767 SourceLocation startLoc = S->getLocStart();
1768 const char *startBuf = SM->getCharacterData(startLoc);
1769
1770 const char *semiBuf = strchr(startBuf, ';');
1771 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1772 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1773
1774 std::string buf;
1775 buf = "{ objc_exception_try_exit(&_stack); return";
1776
Benjamin Kramerd999b372010-02-14 14:14:16 +00001777 ReplaceText(startLoc, 6, buf);
1778 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001779 }
1780 return;
1781}
1782
1783void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1784 // Perform a bottom up traversal of all children.
1785 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1786 CI != E; ++CI)
1787 if (*CI) {
1788 RewriteSyncReturnStmts(*CI, syncExitBuf);
1789 }
1790 if (isa<ReturnStmt>(S)) {
1791 SourceLocation startLoc = S->getLocStart();
1792 const char *startBuf = SM->getCharacterData(startLoc);
1793
1794 const char *semiBuf = strchr(startBuf, ';');
1795 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1796 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1797
1798 std::string buf;
1799 buf = "{ objc_exception_try_exit(&_stack);";
1800 buf += syncExitBuf;
1801 buf += " return";
1802
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 ReplaceText(startLoc, 6, buf);
1804 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001805 }
1806 return;
1807}
1808
Steve Naroffb29b4272008-04-14 22:03:09 +00001809Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001810 // Get the start location and compute the semi location.
1811 SourceLocation startLoc = S->getLocStart();
1812 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Steve Naroff75730982007-11-07 04:08:17 +00001814 assert((*startBuf == '@') && "bogus @try location");
1815
1816 std::string buf;
1817 // declare a new scope with two variables, _stack and _rethrow.
1818 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1819 buf += "int buf[18/*32-bit i386*/];\n";
1820 buf += "char *pointers[4];} _stack;\n";
1821 buf += "id volatile _rethrow = 0;\n";
1822 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001823 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001824
Benjamin Kramerd999b372010-02-14 14:14:16 +00001825 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Steve Naroff75730982007-11-07 04:08:17 +00001827 startLoc = S->getTryBody()->getLocEnd();
1828 startBuf = SM->getCharacterData(startLoc);
1829
1830 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Steve Naroff75730982007-11-07 04:08:17 +00001832 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001833 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1834 if (catchList) {
1835 startLoc = startLoc.getFileLocWithOffset(1);
1836 buf = " /* @catch begin */ else {\n";
1837 buf += " id _caught = objc_exception_extract(&_stack);\n";
1838 buf += " objc_exception_try_enter (&_stack);\n";
1839 buf += " if (_setjmp(_stack.buf))\n";
1840 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1841 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Benjamin Kramerd999b372010-02-14 14:14:16 +00001843 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001844 } else { /* no catch list */
1845 buf = "}\nelse {\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001848 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001849 }
Steve Naroff75730982007-11-07 04:08:17 +00001850 bool sawIdTypedCatch = false;
1851 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001852 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001853 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001854
Mike Stump1eb44332009-09-09 15:08:12 +00001855 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001856 buf = "if ("; // we are generating code for the first catch clause
1857 else
1858 buf = "else if (";
1859 startLoc = catchList->getLocStart();
1860 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Steve Naroff75730982007-11-07 04:08:17 +00001862 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Steve Naroff75730982007-11-07 04:08:17 +00001864 const char *lParenLoc = strchr(startBuf, '(');
1865
Steve Naroffbe4b3332008-02-01 22:08:12 +00001866 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001867 // Now rewrite the body...
1868 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001871 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1872 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001873 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Steve Naroffe12e6922008-02-01 20:02:07 +00001875 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001876 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001877 } else if (catchDecl) {
1878 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001879 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001880 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001881 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001882 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001883 } else if (t->isObjCObjectPointerType()) {
1884 QualType InterfaceTy = t->getPointeeType();
1885 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1886 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001887 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001888 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001889 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001890 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001891 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001892 }
1893 }
1894 // Now rewrite the body...
1895 lastCatchBody = catchList->getCatchBody();
1896 SourceLocation rParenLoc = catchList->getRParenLoc();
1897 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1898 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1899 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1900 assert((*rParenBuf == ')') && "bogus @catch paren location");
1901 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Mike Stump1eb44332009-09-09 15:08:12 +00001903 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001904 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001905 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001906 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001907 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001908 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001909 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001910 catchList = catchList->getNextCatchStmt();
1911 }
1912 // Complete the catch list...
1913 if (lastCatchBody) {
1914 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001915 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1916 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Steve Naroff378f47a2008-09-11 15:29:03 +00001918 // Insert the last (implicit) else clause *before* the right curly brace.
1919 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1920 buf = "} /* last catch end */\n";
1921 buf += "else {\n";
1922 buf += " _rethrow = _caught;\n";
1923 buf += " objc_exception_try_exit(&_stack);\n";
1924 buf += "} } /* @catch end */\n";
1925 if (!S->getFinallyStmt())
1926 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001927 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001928
Steve Naroff75730982007-11-07 04:08:17 +00001929 // Set lastCurlyLoc
1930 lastCurlyLoc = lastCatchBody->getLocEnd();
1931 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001932 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001933 startLoc = finalStmt->getLocStart();
1934 startBuf = SM->getCharacterData(startLoc);
1935 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Benjamin Kramerd999b372010-02-14 14:14:16 +00001937 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Steve Naroff75730982007-11-07 04:08:17 +00001939 Stmt *body = finalStmt->getFinallyBody();
1940 SourceLocation startLoc = body->getLocStart();
1941 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001942 assert(*SM->getCharacterData(startLoc) == '{' &&
1943 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001944 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001945 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001946
Steve Naroff75730982007-11-07 04:08:17 +00001947 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001948 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001949 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001950 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Steve Naroff75730982007-11-07 04:08:17 +00001952 // Set lastCurlyLoc
1953 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
Steve Naroff8c565152008-12-05 17:03:39 +00001955 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001956 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001957 } else { /* no finally clause - make sure we synthesize an implicit one */
1958 buf = "{ /* implicit finally clause */\n";
1959 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1960 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1961 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001962 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001963
1964 // Now check for any return/continue/go statements within the @try.
1965 // The implicit finally clause won't called if the @try contains any
1966 // jump statements.
1967 bool hasReturns = false;
1968 HasReturnStmts(S->getTryBody(), hasReturns);
1969 if (hasReturns)
1970 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001971 }
1972 // Now emit the final closing curly brace...
1973 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001974 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001975 return 0;
1976}
1977
Steve Naroffb29b4272008-04-14 22:03:09 +00001978Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001979 return 0;
1980}
1981
Steve Naroffb29b4272008-04-14 22:03:09 +00001982Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001983 return 0;
1984}
1985
Mike Stump1eb44332009-09-09 15:08:12 +00001986// This can't be done with ReplaceStmt(S, ThrowExpr), since
1987// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001988// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001989Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001990 // Get the start location and compute the semi location.
1991 SourceLocation startLoc = S->getLocStart();
1992 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Steve Naroff2bd03922007-11-07 15:32:26 +00001994 assert((*startBuf == '@') && "bogus @throw location");
1995
1996 std::string buf;
1997 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001998 if (S->getThrowExpr())
1999 buf = "objc_exception_throw(";
2000 else // add an implicit argument
2001 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002003 // handle "@ throw" correctly.
2004 const char *wBuf = strchr(startBuf, 'w');
2005 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002006 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002007
Steve Naroff2bd03922007-11-07 15:32:26 +00002008 const char *semiBuf = strchr(startBuf, ';');
2009 assert((*semiBuf == ';') && "@throw: can't find ';'");
2010 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002011 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002012 return 0;
2013}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002014
Steve Naroffb29b4272008-04-14 22:03:09 +00002015Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002016 // Create a new string expression.
2017 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002018 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002019 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00002020 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
2021 StrEncoding.length(), false,StrType,
2022 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002023 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Chris Lattner07506182007-11-30 22:53:43 +00002025 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00002026 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002027 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002028}
2029
Steve Naroffb29b4272008-04-14 22:03:09 +00002030Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002031 if (!SelGetUidFunctionDecl)
2032 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002033 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2034 // Create a call to sel_registerName("selName").
2035 llvm::SmallVector<Expr*, 8> SelExprs;
2036 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002037 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002038 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002039 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002040 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002041 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2042 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002043 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002044 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002045 return SelExp;
2046}
2047
Steve Naroffb29b4272008-04-14 22:03:09 +00002048CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002049 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2050 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002051 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002052 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Steve Naroffebf2b562007-10-23 23:50:29 +00002054 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002055 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Steve Naroffebf2b562007-10-23 23:50:29 +00002057 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002058 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00002059 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00002060 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002061 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00002062 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
John McCall183700f2009-09-21 23:43:11 +00002064 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002066 CallExpr *Exp =
2067 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
2068 EndLoc);
2069 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002070}
2071
Steve Naroffd5255f52007-11-01 13:24:47 +00002072static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2073 const char *&startRef, const char *&endRef) {
2074 while (startBuf < endBuf) {
2075 if (*startBuf == '<')
2076 startRef = startBuf; // mark the start.
2077 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002078 if (startRef && *startRef == '<') {
2079 endRef = startBuf; // mark the end.
2080 return true;
2081 }
2082 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002083 }
2084 startBuf++;
2085 }
2086 return false;
2087}
2088
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002089static void scanToNextArgument(const char *&argRef) {
2090 int angle = 0;
2091 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2092 if (*argRef == '<')
2093 angle++;
2094 else if (*argRef == '>')
2095 angle--;
2096 argRef++;
2097 }
2098 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2099}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002100
Steve Naroffb29b4272008-04-14 22:03:09 +00002101bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002102 if (T->isObjCQualifiedIdType())
2103 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002104 if (const PointerType *PT = T->getAs<PointerType>()) {
2105 if (PT->getPointeeType()->isObjCQualifiedIdType())
2106 return true;
2107 }
2108 if (T->isObjCObjectPointerType()) {
2109 T = T->getPointeeType();
2110 return T->isObjCQualifiedInterfaceType();
2111 }
2112 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002113}
2114
Steve Naroff4f95b752008-07-29 18:15:38 +00002115void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2116 QualType Type = E->getType();
2117 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002118 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Steve Naroffcda658e2008-11-19 21:15:47 +00002120 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2121 Loc = ECE->getLParenLoc();
2122 EndLoc = ECE->getRParenLoc();
2123 } else {
2124 Loc = E->getLocStart();
2125 EndLoc = E->getLocEnd();
2126 }
2127 // This will defend against trying to rewrite synthesized expressions.
2128 if (Loc.isInvalid() || EndLoc.isInvalid())
2129 return;
2130
Steve Naroff4f95b752008-07-29 18:15:38 +00002131 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002132 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002133 const char *startRef = 0, *endRef = 0;
2134 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2135 // Get the locations of the startRef, endRef.
2136 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2137 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2138 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002139 InsertText(LessLoc, "/*");
2140 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002141 }
2142 }
2143}
2144
Steve Naroffb29b4272008-04-14 22:03:09 +00002145void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002146 SourceLocation Loc;
2147 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002148 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002149 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2150 Loc = VD->getLocation();
2151 Type = VD->getType();
2152 }
2153 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2154 Loc = FD->getLocation();
2155 // Check for ObjC 'id' and class types that have been adorned with protocol
2156 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002157 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002158 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002159 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002160 if (!proto)
2161 return;
2162 Type = proto->getResultType();
2163 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002164 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2165 Loc = FD->getLocation();
2166 Type = FD->getType();
2167 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002168 else
2169 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002171 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002172 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002173
Steve Naroffd5255f52007-11-01 13:24:47 +00002174 const char *endBuf = SM->getCharacterData(Loc);
2175 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002176 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002177 startBuf--; // scan backward (from the decl location) for return type.
2178 const char *startRef = 0, *endRef = 0;
2179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
2181 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2182 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2183 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002186 }
2187 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002188 if (!proto)
2189 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002190 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002191 const char *startBuf = SM->getCharacterData(Loc);
2192 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002193 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2194 if (needToScanForQualifiers(proto->getArgType(i))) {
2195 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Steve Naroffd5255f52007-11-01 13:24:47 +00002197 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002198 // scan forward (from the decl location) for argument types.
2199 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002200 const char *startRef = 0, *endRef = 0;
2201 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2202 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002203 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002204 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002205 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002206 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002207 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002208 InsertText(LessLoc, "/*");
2209 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002210 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002211 startBuf = ++endBuf;
2212 }
2213 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002214 // If the function name is derived from a macro expansion, then the
2215 // argument buffer will not follow the name. Need to speak with Chris.
2216 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002217 startBuf++; // scan forward (from the decl location) for argument types.
2218 startBuf++;
2219 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002220 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002221}
2222
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002223void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2224 QualType QT = ND->getType();
2225 const Type* TypePtr = QT->getAs<Type>();
2226 if (!isa<TypeOfExprType>(TypePtr))
2227 return;
2228 while (isa<TypeOfExprType>(TypePtr)) {
2229 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2230 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2231 TypePtr = QT->getAs<Type>();
2232 }
2233 // FIXME. This will not work for multiple declarators; as in:
2234 // __typeof__(a) b,c,d;
2235 std::string TypeAsString(QT.getAsString());
2236 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2237 const char *startBuf = SM->getCharacterData(DeclLoc);
2238 if (ND->getInit()) {
2239 std::string Name(ND->getNameAsString());
2240 TypeAsString += " " + Name + " = ";
2241 Expr *E = ND->getInit();
2242 SourceLocation startLoc;
2243 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2244 startLoc = ECE->getLParenLoc();
2245 else
2246 startLoc = E->getLocStart();
2247 startLoc = SM->getInstantiationLoc(startLoc);
2248 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002249 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002250 }
2251 else {
2252 SourceLocation X = ND->getLocEnd();
2253 X = SM->getInstantiationLoc(X);
2254 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002255 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002256 }
2257}
2258
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002259// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002260void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002261 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2262 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002263 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002264 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002265 &ArgTys[0], ArgTys.size(),
2266 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002267 false, false, 0, 0,
2268 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002269 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002270 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002271 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002272 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002273}
2274
Steve Naroffb29b4272008-04-14 22:03:09 +00002275void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002276 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002277 if (FD->getIdentifier() &&
2278 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002279 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002280 return;
2281 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002283}
2284
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002285static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2286 std::string TypeString(Type.getAsString());
2287 const char *argPtr = TypeString.c_str();
2288 if (!strchr(argPtr, '^')) {
2289 Str += TypeString;
2290 return;
2291 }
2292 while (*argPtr) {
2293 Str += (*argPtr == '^' ? '*' : *argPtr);
2294 argPtr++;
2295 }
2296}
2297
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002298// FIXME. Consolidate this routine with RewriteBlockPointerType.
2299static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2300 QualType Type = VD->getType();
2301 std::string TypeString(Type.getAsString());
2302 const char *argPtr = TypeString.c_str();
2303 int paren = 0;
2304 while (*argPtr) {
2305 switch (*argPtr) {
2306 case '(':
2307 Str += *argPtr;
2308 paren++;
2309 break;
2310 case ')':
2311 Str += *argPtr;
2312 paren--;
2313 break;
2314 case '^':
2315 Str += '*';
2316 if (paren == 1)
2317 Str += VD->getNameAsString();
2318 break;
2319 default:
2320 Str += *argPtr;
2321 break;
2322 }
2323 argPtr++;
2324 }
2325}
2326
2327
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002328void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2329 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2330 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2331 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2332 if (!proto)
2333 return;
2334 QualType Type = proto->getResultType();
2335 std::string FdStr = Type.getAsString();
2336 FdStr += " ";
2337 FdStr += FD->getNameAsCString();
2338 FdStr += "(";
2339 unsigned numArgs = proto->getNumArgs();
2340 for (unsigned i = 0; i < numArgs; i++) {
2341 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002342 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002343 if (i+1 < numArgs)
2344 FdStr += ", ";
2345 }
2346 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002347 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002348 CurFunctionDeclToDeclareForBlock = 0;
2349}
2350
Steve Naroffc0a123c2008-03-11 17:37:02 +00002351// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002352void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002353 if (SuperContructorFunctionDecl)
2354 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002355 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002356 llvm::SmallVector<QualType, 16> ArgTys;
2357 QualType argT = Context->getObjCIdType();
2358 assert(!argT.isNull() && "Can't find 'id' type");
2359 ArgTys.push_back(argT);
2360 ArgTys.push_back(argT);
2361 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2362 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002363 false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002364 false, false, 0, 0,
2365 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002366 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002367 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002368 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002369 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002370}
2371
Steve Naroff09b266e2007-10-30 23:14:51 +00002372// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002373void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002374 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2375 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002376 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002377 assert(!argT.isNull() && "Can't find 'id' type");
2378 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002379 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002380 assert(!argT.isNull() && "Can't find 'SEL' type");
2381 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002382 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002383 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002384 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002385 false, false, 0, 0,
2386 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002387 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002388 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002389 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002390 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002391}
2392
Steve Naroff874e2322007-11-15 10:28:18 +00002393// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002394void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002395 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2396 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002397 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002398 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002399 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002400 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2401 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2402 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002404 assert(!argT.isNull() && "Can't find 'SEL' type");
2405 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002406 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002407 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002408 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002409 false, false, 0, 0,
2410 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002411 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002412 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002413 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002414 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002415}
2416
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002417// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002418void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2420 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002427 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002428 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002429 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002430 false, false, 0, 0,
2431 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002432 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002433 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002434 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002435 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002436}
2437
Mike Stump1eb44332009-09-09 15:08:12 +00002438// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002439// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002440void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002441 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002442 &Context->Idents.get("objc_msgSendSuper_stret");
2443 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002444 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002445 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002446 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002447 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2448 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2449 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002450 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002451 assert(!argT.isNull() && "Can't find 'SEL' type");
2452 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002453 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002454 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002455 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002456 false, false, 0, 0,
2457 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002458 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002459 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002460 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002461 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002462}
2463
Steve Naroff1284db82008-05-08 22:02:18 +00002464// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002465void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002466 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2467 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002468 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002469 assert(!argT.isNull() && "Can't find 'id' type");
2470 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002471 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002472 assert(!argT.isNull() && "Can't find 'SEL' type");
2473 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002474 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002475 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002476 true /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002477 false, false, 0, 0,
2478 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002479 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002480 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002481 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002482 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002483}
2484
Steve Naroff09b266e2007-10-30 23:14:51 +00002485// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002486void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002487 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2488 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002489 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002490 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002491 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002492 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002493 false, false, 0, 0,
2494 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002495 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002496 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002497 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002498 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002499}
2500
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002501// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2502void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2503 IdentifierInfo *getSuperClassIdent =
2504 &Context->Idents.get("class_getSuperclass");
2505 llvm::SmallVector<QualType, 16> ArgTys;
2506 ArgTys.push_back(Context->getObjCClassType());
2507 QualType getClassType = Context->getFunctionType(Context->getObjCClassType(),
2508 &ArgTys[0], ArgTys.size(),
2509 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002510 false, false, 0, 0,
2511 FunctionType::ExtInfo());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002512 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2513 SourceLocation(),
2514 getSuperClassIdent, getClassType, 0,
2515 FunctionDecl::Extern, false);
2516}
2517
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002518// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002519void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002520 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2521 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002522 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002524 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002525 false /*isVariadic*/, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002526 false, false, 0, 0,
2527 FunctionType::ExtInfo());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002528 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002529 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002530 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002531 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002532}
2533
Steve Naroffb29b4272008-04-14 22:03:09 +00002534Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002535 QualType strType = getConstantStringStructType();
2536
2537 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002538
2539 std::string tmpName = InFileName;
2540 unsigned i;
2541 for (i=0; i < tmpName.length(); i++) {
2542 char c = tmpName.at(i);
2543 // replace any non alphanumeric characters with '_'.
2544 if (!isalpha(c) && (c < '0' || c > '9'))
2545 tmpName[i] = '_';
2546 }
2547 S += tmpName;
2548 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002549 S += utostr(NumObjCStringLiterals++);
2550
Steve Naroffba92b2e2008-03-27 22:29:16 +00002551 Preamble += "static __NSConstantStringImpl " + S;
2552 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2553 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002554 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002555 std::string prettyBufS;
2556 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002557 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2558 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002559 Preamble += prettyBuf.str();
2560 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002561 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002562
2563 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002564 &Context->Idents.get(S), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002565 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002566 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2567 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002568 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002569 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002570 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002571 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2572 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002573 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002574 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002575 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002576}
2577
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002578bool RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002579 // check if we are sending a message to 'super'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002580 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return false;
2581 return isa<ObjCSuperExpr>(recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002582}
2583
2584// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002585QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002586 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002587 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002588 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002589 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002590 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002591
Steve Naroff874e2322007-11-15 10:28:18 +00002592 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002593 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002594 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002595 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002596
Steve Naroff874e2322007-11-15 10:28:18 +00002597 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002598 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002599 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2600 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002601 FieldTypes[i], 0,
2602 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002603 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002604 }
Mike Stump1eb44332009-09-09 15:08:12 +00002605
Douglas Gregor838db382010-02-11 01:19:42 +00002606 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002607 }
2608 return Context->getTagDeclType(SuperStructDecl);
2609}
2610
Steve Naroffb29b4272008-04-14 22:03:09 +00002611QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002612 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002613 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002614 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002615 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002616 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002617
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002618 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002619 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002620 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002621 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002622 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002623 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002624 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002625 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002626
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002627 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002628 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002629 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2630 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002631 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002632 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002633 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002634 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002635 }
2636
Douglas Gregor838db382010-02-11 01:19:42 +00002637 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002638 }
2639 return Context->getTagDeclType(ConstantStringDecl);
2640}
2641
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002642Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2643 SourceLocation StartLoc,
2644 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002645 if (!SelGetUidFunctionDecl)
2646 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002647 if (!MsgSendFunctionDecl)
2648 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002649 if (!MsgSendSuperFunctionDecl)
2650 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002651 if (!MsgSendStretFunctionDecl)
2652 SynthMsgSendStretFunctionDecl();
2653 if (!MsgSendSuperStretFunctionDecl)
2654 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002655 if (!MsgSendFpretFunctionDecl)
2656 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002657 if (!GetClassFunctionDecl)
2658 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002659 if (!GetSuperClassFunctionDecl)
2660 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002661 if (!GetMetaClassFunctionDecl)
2662 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Steve Naroff874e2322007-11-15 10:28:18 +00002664 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002665 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2666 // May need to use objc_msgSend_stret() as well.
2667 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002668 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2669 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002670 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002671 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002672 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002673 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002674 }
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Steve Naroff934f2762007-10-24 22:48:43 +00002676 // Synthesize a call to objc_msgSend().
2677 llvm::SmallVector<Expr*, 8> MsgExprs;
2678 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Steve Naroff934f2762007-10-24 22:48:43 +00002680 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2681 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002682 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2683 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002684 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002685 MsgSendFlavor = MsgSendSuperFunctionDecl;
2686 if (MsgSendStretFlavor)
2687 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2688 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002690 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002691
2692 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002693
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002694 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002695 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002696 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2697 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002698 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002699 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002700 SourceLocation()))
2701 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002702
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002703 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002704 llvm::SmallVector<Expr*, 8> ClsExprs;
2705 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002706 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002707 ClassDecl->getIdentifier()->getNameStart(),
2708 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbare013d682009-10-18 20:26:12 +00002709 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002710 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002711 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002712 ClsExprs.size(),
2713 StartLoc,
2714 EndLoc);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002715 // (Class)objc_getClass("CurrentClass")
2716 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2717 Context->getObjCClassType(),
2718 CastExpr::CK_Unknown, Cls);
2719 ClsExprs.clear();
2720 ClsExprs.push_back(ArgExpr);
2721 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2722 &ClsExprs[0], ClsExprs.size(),
2723 StartLoc, EndLoc);
2724
2725 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002726 // To turn off a warning, type-cast to 'id'
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002727 InitExprs.push_back( // set 'super class', using class_getSuperclass().
John McCall9d125032010-01-15 18:39:57 +00002728 NoTypeInfoCStyleCastExpr(Context,
2729 Context->getObjCIdType(),
2730 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002731 // struct objc_super
2732 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002733 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002734
Steve Naroff23f41272008-03-11 18:14:26 +00002735 if (LangOpts.Microsoft) {
2736 SynthSuperContructorFunctionDecl();
2737 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002738 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002739 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002740 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002741 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002742 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002743 // The code for super is a little tricky to prevent collision with
2744 // the structure definition in the header. The rewriter has it's own
2745 // internal definition (__rw_objc_super) that is uses. This is why
2746 // we need the cast below. For example:
2747 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2748 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002749 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002750 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002751 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002752 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2753 Context->getPointerType(superType),
2754 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002755 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002756 // (struct objc_super) { <exprs from above> }
Ted Kremenek709210f2010-04-13 23:39:13 +00002757 InitListExpr *ILE =
2758 new (Context) InitListExpr(*Context, SourceLocation(),
2759 &InitExprs[0], InitExprs.size(),
2760 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002761 TypeSourceInfo *superTInfo
2762 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002763 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2764 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002765 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002766 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002767 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002768 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002769 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002770 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002771 } else {
2772 llvm::SmallVector<Expr*, 8> ClsExprs;
2773 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002774 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002775 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002776 clsName->getLength(),
2777 false, argType,
2778 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002779 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002780 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002781 ClsExprs.size(),
2782 StartLoc, EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002783 MsgExprs.push_back(Cls);
2784 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002785 } else { // instance message.
2786 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002787
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002788 if (isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002789 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002790 if (MsgSendStretFlavor)
2791 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002792 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002793 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Steve Naroff874e2322007-11-15 10:28:18 +00002794 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002796 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002797 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2798 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002799 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002800 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002801 SourceLocation()))
2802 ); // set the 'receiver'.
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002803
2804 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Steve Naroff874e2322007-11-15 10:28:18 +00002805 llvm::SmallVector<Expr*, 8> ClsExprs;
2806 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002807 ClsExprs.push_back(StringLiteral::Create(*Context,
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002808 ClassDecl->getIdentifier()->getNameStart(),
2809 ClassDecl->getIdentifier()->getLength(),
Daniel Dunbare013d682009-10-18 20:26:12 +00002810 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002811 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002812 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002813 ClsExprs.size(),
2814 StartLoc, EndLoc);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002815 // (Class)objc_getClass("CurrentClass")
2816 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2817 Context->getObjCClassType(),
2818 CastExpr::CK_Unknown, Cls);
2819 ClsExprs.clear();
2820 ClsExprs.push_back(ArgExpr);
2821 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2822 &ClsExprs[0], ClsExprs.size(),
2823 StartLoc, EndLoc);
2824
2825 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Fariborz Jahanian71274312007-12-05 17:29:46 +00002826 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002827 InitExprs.push_back(
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002828 // set 'super class', using class_getSuperclass().
John McCall9d125032010-01-15 18:39:57 +00002829 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2830 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002831 // struct objc_super
2832 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002833 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Steve Naroffc0a123c2008-03-11 17:37:02 +00002835 if (LangOpts.Microsoft) {
2836 SynthSuperContructorFunctionDecl();
2837 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002838 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002839 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002840 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002841 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002842 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002843 // The code for super is a little tricky to prevent collision with
2844 // the structure definition in the header. The rewriter has it's own
2845 // internal definition (__rw_objc_super) that is uses. This is why
2846 // we need the cast below. For example:
2847 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2848 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002849 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002850 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002851 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002852 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2853 Context->getPointerType(superType),
2854 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002855 } else {
2856 // (struct objc_super) { <exprs from above> }
Ted Kremenek709210f2010-04-13 23:39:13 +00002857 InitListExpr *ILE =
2858 new (Context) InitListExpr(*Context, SourceLocation(),
2859 &InitExprs[0], InitExprs.size(),
2860 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002861 TypeSourceInfo *superTInfo
2862 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002863 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2864 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002865 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002866 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002867 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002868 // Remove all type-casts because it may contain objc-style types; e.g.
2869 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002870 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002871 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002872 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2873 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002874 MsgExprs.push_back(recExpr);
2875 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002876 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002877 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002878 llvm::SmallVector<Expr*, 8> SelExprs;
2879 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002880 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002881 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002882 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002883 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002884 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002885 &SelExprs[0], SelExprs.size(),
2886 StartLoc,
2887 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002888 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Steve Naroff934f2762007-10-24 22:48:43 +00002890 // Now push any user supplied arguments.
2891 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002892 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002893 // Make all implicit casts explicit...ICE comes in handy:-)
2894 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2895 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002896 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002897 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002898 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002899 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2900 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002901 }
2902 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002903 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002904 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002905 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002906 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002907 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2908 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002909 }
Mike Stump1eb44332009-09-09 15:08:12 +00002910 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002911 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002912 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2913 // out the argument in the original expression (since we aren't deleting
2914 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2915 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002916 }
Steve Naroffab972d32007-11-04 22:37:50 +00002917 // Generate the funky cast.
2918 CastExpr *cast;
2919 llvm::SmallVector<QualType, 8> ArgTypes;
2920 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002921
Steve Naroffab972d32007-11-04 22:37:50 +00002922 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002923 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2924 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2925 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002926 ArgTypes.push_back(Context->getObjCIdType());
2927 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002928 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002929 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002930 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2931 E = OMD->param_end(); PI != E; ++PI) {
2932 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002933 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002934 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002935 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002936 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002937 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002938 t = Context->getPointerType(BPT->getPointeeType());
2939 }
Steve Naroff352336b2007-11-05 14:36:37 +00002940 ArgTypes.push_back(t);
2941 }
Chris Lattner89951a82009-02-20 18:43:26 +00002942 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2943 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002944 if (isTopLevelBlockPointerType(returnType)) {
2945 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2946 returnType = Context->getPointerType(BPT->getPointeeType());
2947 }
Steve Naroffab972d32007-11-04 22:37:50 +00002948 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002949 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002950 }
2951 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002952 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Steve Naroffab972d32007-11-04 22:37:50 +00002954 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002955 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002956 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002957
Mike Stump1eb44332009-09-09 15:08:12 +00002958 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002959 // If we don't do this cast, we get the following bizarre warning/note:
2960 // xx.m:13: warning: function called through a non-compatible type
2961 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002962 cast = NoTypeInfoCStyleCastExpr(Context,
2963 Context->getPointerType(Context->VoidTy),
2964 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002965
Steve Naroffab972d32007-11-04 22:37:50 +00002966 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002967 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002968 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002969 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002970 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00002971 false, false, 0, 0,
2972 FunctionType::ExtInfo());
Steve Naroffab972d32007-11-04 22:37:50 +00002973 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002974 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2975 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002976
2977 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002978 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002979
John McCall183700f2009-09-21 23:43:11 +00002980 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002981 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002982 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002983 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002984 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002985 if (MsgSendStretFlavor) {
2986 // We have the method which returns a struct/union. Must also generate
2987 // call to objc_msgSend_stret and hang both varieties on a conditional
2988 // expression which dictate which one to envoke depending on size of
2989 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002991 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002992 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002993 SourceLocation());
2994 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002995 cast = NoTypeInfoCStyleCastExpr(Context,
2996 Context->getPointerType(Context->VoidTy),
2997 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002998 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002999 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00003000 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00003001 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00003002 false, false, 0, 0,
3003 FunctionType::ExtInfo());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003004 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00003005 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
3006 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003007
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003008 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003009 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003010
John McCall183700f2009-09-21 23:43:11 +00003011 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003012 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003013 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00003014 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003015
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003016 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00003017 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00003018 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00003019 Context->getSizeType(),
3020 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003021 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3022 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3023 // For X86 it is more complicated and some kind of target specific routine
3024 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003025 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003026 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00003027 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003028 Context->IntTy,
3029 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003030 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
3031 BinaryOperator::LE,
3032 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003033 SourceLocation());
3034 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003035 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003036 new (Context) ConditionalOperator(lessThanExpr,
3037 SourceLocation(), CE,
3038 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003039 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003040 }
Mike Stump1eb44332009-09-09 15:08:12 +00003041 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003042 return ReplacingStmt;
3043}
3044
Steve Naroffb29b4272008-04-14 22:03:09 +00003045Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003046 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3047 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003048
Steve Naroff934f2762007-10-24 22:48:43 +00003049 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003050 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003051
3052 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003053 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003054}
3055
Steve Naroff621edce2009-04-29 16:37:50 +00003056// typedef struct objc_object Protocol;
3057QualType RewriteObjC::getProtocolType() {
3058 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003059 TypeSourceInfo *TInfo
3060 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003061 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003062 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003063 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003064 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003065 }
3066 return Context->getTypeDeclType(ProtocolTypeDecl);
3067}
3068
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003069/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003070/// a synthesized/forward data reference (to the protocol's metadata).
3071/// The forward references (and metadata) are generated in
3072/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003073Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003074 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3075 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003076 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00003077 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00003078 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
3079 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
3080 Context->getPointerType(DRE->getType()),
3081 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003082 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3083 CastExpr::CK_Unknown,
3084 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003085 ReplaceStmt(Exp, castExpr);
3086 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00003087 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003088 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003089
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003090}
3091
Mike Stump1eb44332009-09-09 15:08:12 +00003092bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003093 const char *endBuf) {
3094 while (startBuf < endBuf) {
3095 if (*startBuf == '#') {
3096 // Skip whitespace.
3097 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3098 ;
3099 if (!strncmp(startBuf, "if", strlen("if")) ||
3100 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3101 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3102 !strncmp(startBuf, "define", strlen("define")) ||
3103 !strncmp(startBuf, "undef", strlen("undef")) ||
3104 !strncmp(startBuf, "else", strlen("else")) ||
3105 !strncmp(startBuf, "elif", strlen("elif")) ||
3106 !strncmp(startBuf, "endif", strlen("endif")) ||
3107 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3108 !strncmp(startBuf, "include", strlen("include")) ||
3109 !strncmp(startBuf, "import", strlen("import")) ||
3110 !strncmp(startBuf, "include_next", strlen("include_next")))
3111 return true;
3112 }
3113 startBuf++;
3114 }
3115 return false;
3116}
3117
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003118/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003119/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003120void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003121 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003122 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003123 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003124 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003125 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003126 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003127 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003129 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003130 SourceLocation LocStart = CDecl->getLocStart();
3131 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Steve Narofffea763e82007-11-14 19:25:57 +00003133 const char *startBuf = SM->getCharacterData(LocStart);
3134 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003136 // If no ivars and no root or if its root, directly or indirectly,
3137 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003138 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3139 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003140 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003141 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003142 return;
3143 }
Mike Stump1eb44332009-09-09 15:08:12 +00003144
3145 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003146 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003147 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003148 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003149 if (LangOpts.Microsoft)
3150 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003151
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003152 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003153 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003154 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003155 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003156 // If the buffer contains preprocessor directives, we do more fine-grained
3157 // rewrites. This is intended to fix code that looks like (which occurs in
3158 // NSURL.h, for example):
3159 //
3160 // #ifdef XYZ
3161 // @interface Foo : NSObject
3162 // #else
3163 // @interface FooBar : NSObject
3164 // #endif
3165 // {
3166 // int i;
3167 // }
3168 // @end
3169 //
3170 // This clause is segregated to avoid breaking the common case.
3171 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003172 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003173 CDecl->getClassLoc();
3174 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003175 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003176
Chris Lattnercafeb352009-02-20 18:18:36 +00003177 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003178 // advance to the end of the referenced protocols.
3179 while (endHeader < cursor && *endHeader != '>') endHeader++;
3180 endHeader++;
3181 }
3182 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003183 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003184 } else {
3185 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003186 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003187 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003188 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003189 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003190 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003191 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003192 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003193 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Steve Narofffea763e82007-11-14 19:25:57 +00003195 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003196 SourceLocation OnePastCurly =
3197 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003198 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003199 }
3200 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003201
Steve Narofffea763e82007-11-14 19:25:57 +00003202 // Now comment out any visibility specifiers.
3203 while (cursor < endBuf) {
3204 if (*cursor == '@') {
3205 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003206 // Skip whitespace.
3207 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3208 /*scan*/;
3209
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003210 // FIXME: presence of @public, etc. inside comment results in
3211 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003212 if (!strncmp(cursor, "public", strlen("public")) ||
3213 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003214 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003215 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003216 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003217 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003218 // FIXME: If there are cases where '<' is used in ivar declaration part
3219 // of user code, then scan the ivar list and use needToScanForQualifiers
3220 // for type checking.
3221 else if (*cursor == '<') {
3222 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003223 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003224 cursor = strchr(cursor, '>');
3225 cursor++;
3226 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003227 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003228 } else if (*cursor == '^') { // rewrite block specifier.
3229 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003230 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003231 }
Steve Narofffea763e82007-11-14 19:25:57 +00003232 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003233 }
Steve Narofffea763e82007-11-14 19:25:57 +00003234 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003235 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003236 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003237 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003238 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003239 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003240 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003241 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003242 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003243 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003244 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003245 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003246 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003247 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003248}
3249
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003250// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003251/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003252template<typename MethodIterator>
3253void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3254 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003255 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003256 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003257 const char *ClassName,
3258 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003259 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003261 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003262 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003263 SEL _cmd;
3264 char *method_types;
3265 void *_imp;
3266 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003267 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003268 Result += "\nstruct _objc_method {\n";
3269 Result += "\tSEL _cmd;\n";
3270 Result += "\tchar *method_types;\n";
3271 Result += "\tvoid *_imp;\n";
3272 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003274 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003275 }
Mike Stump1eb44332009-09-09 15:08:12 +00003276
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003277 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Steve Naroff946a6932008-03-11 00:12:29 +00003279 /* struct {
3280 struct _objc_method_list *next_method;
3281 int method_count;
3282 struct _objc_method method_list[];
3283 }
3284 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003285 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003286 Result += "\nstatic struct {\n";
3287 Result += "\tstruct _objc_method_list *next_method;\n";
3288 Result += "\tint method_count;\n";
3289 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003290 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003291 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003292 Result += prefix;
3293 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3294 Result += "_METHODS_";
3295 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003296 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003297 Result += IsInstanceMethod ? "inst" : "cls";
3298 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003299 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003300
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003301 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003302 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003303 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003304 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003305 Result += "\", \"";
3306 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003307 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003308 Result += MethodInternalNames[*MethodBegin];
3309 Result += "}\n";
3310 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3311 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003312 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003313 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003314 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003315 Result += "\", \"";
3316 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003317 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003318 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003319 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003320 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003321 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003322}
3323
Steve Naroff621edce2009-04-29 16:37:50 +00003324/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003325void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003326RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3327 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003328 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003329
3330 // Output struct protocol_methods holder of method selector and type.
3331 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3332 /* struct protocol_methods {
3333 SEL _cmd;
3334 char *method_types;
3335 }
3336 */
3337 Result += "\nstruct _protocol_methods {\n";
3338 Result += "\tstruct objc_selector *_cmd;\n";
3339 Result += "\tchar *method_types;\n";
3340 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003341
Steve Naroff621edce2009-04-29 16:37:50 +00003342 objc_protocol_methods = true;
3343 }
3344 // Do not synthesize the protocol more than once.
3345 if (ObjCSynthesizedProtocols.count(PDecl))
3346 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003348 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3349 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3350 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003351 /* struct _objc_protocol_method_list {
3352 int protocol_method_count;
3353 struct protocol_methods protocols[];
3354 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003355 */
Steve Naroff621edce2009-04-29 16:37:50 +00003356 Result += "\nstatic struct {\n";
3357 Result += "\tint protocol_method_count;\n";
3358 Result += "\tstruct _protocol_methods protocol_methods[";
3359 Result += utostr(NumMethods);
3360 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3361 Result += PDecl->getNameAsString();
3362 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3363 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003364
Steve Naroff621edce2009-04-29 16:37:50 +00003365 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003366 for (ObjCProtocolDecl::instmeth_iterator
3367 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003368 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003369 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003370 Result += "\t ,{{(struct objc_selector *)\"";
3371 else
3372 Result += "\t ,{(struct objc_selector *)\"";
3373 Result += (*I)->getSelector().getAsString().c_str();
3374 std::string MethodTypeString;
3375 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3376 Result += "\", \"";
3377 Result += MethodTypeString;
3378 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003379 }
Steve Naroff621edce2009-04-29 16:37:50 +00003380 Result += "\t }\n};\n";
3381 }
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Steve Naroff621edce2009-04-29 16:37:50 +00003383 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003384 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3385 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003386 if (NumMethods > 0) {
3387 /* struct _objc_protocol_method_list {
3388 int protocol_method_count;
3389 struct protocol_methods protocols[];
3390 }
3391 */
3392 Result += "\nstatic struct {\n";
3393 Result += "\tint protocol_method_count;\n";
3394 Result += "\tstruct _protocol_methods protocol_methods[";
3395 Result += utostr(NumMethods);
3396 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3397 Result += PDecl->getNameAsString();
3398 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3399 "{\n\t";
3400 Result += utostr(NumMethods);
3401 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003402
Steve Naroff621edce2009-04-29 16:37:50 +00003403 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003404 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003405 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003406 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003407 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003408 Result += "\t ,{{(struct objc_selector *)\"";
3409 else
3410 Result += "\t ,{(struct objc_selector *)\"";
3411 Result += (*I)->getSelector().getAsString().c_str();
3412 std::string MethodTypeString;
3413 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3414 Result += "\", \"";
3415 Result += MethodTypeString;
3416 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003417 }
Steve Naroff621edce2009-04-29 16:37:50 +00003418 Result += "\t }\n};\n";
3419 }
3420
3421 // Output:
3422 /* struct _objc_protocol {
3423 // Objective-C 1.0 extensions
3424 struct _objc_protocol_extension *isa;
3425 char *protocol_name;
3426 struct _objc_protocol **protocol_list;
3427 struct _objc_protocol_method_list *instance_methods;
3428 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003429 };
Steve Naroff621edce2009-04-29 16:37:50 +00003430 */
3431 static bool objc_protocol = false;
3432 if (!objc_protocol) {
3433 Result += "\nstruct _objc_protocol {\n";
3434 Result += "\tstruct _objc_protocol_extension *isa;\n";
3435 Result += "\tchar *protocol_name;\n";
3436 Result += "\tstruct _objc_protocol **protocol_list;\n";
3437 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3438 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003439 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003440
Steve Naroff621edce2009-04-29 16:37:50 +00003441 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003442 }
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Steve Naroff621edce2009-04-29 16:37:50 +00003444 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3445 Result += PDecl->getNameAsString();
3446 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3447 "{\n\t0, \"";
3448 Result += PDecl->getNameAsString();
3449 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003450 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003451 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3452 Result += PDecl->getNameAsString();
3453 Result += ", ";
3454 }
3455 else
3456 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003457 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003458 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3459 Result += PDecl->getNameAsString();
3460 Result += "\n";
3461 }
3462 else
3463 Result += "0\n";
3464 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003465
Steve Naroff621edce2009-04-29 16:37:50 +00003466 // Mark this protocol as having been generated.
3467 if (!ObjCSynthesizedProtocols.insert(PDecl))
3468 assert(false && "protocol already synthesized");
3469
3470}
3471
3472void RewriteObjC::
3473RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3474 const char *prefix, const char *ClassName,
3475 std::string &Result) {
3476 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Steve Naroff621edce2009-04-29 16:37:50 +00003478 for (unsigned i = 0; i != Protocols.size(); i++)
3479 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3480
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003481 // Output the top lovel protocol meta-data for the class.
3482 /* struct _objc_protocol_list {
3483 struct _objc_protocol_list *next;
3484 int protocol_count;
3485 struct _objc_protocol *class_protocols[];
3486 }
3487 */
3488 Result += "\nstatic struct {\n";
3489 Result += "\tstruct _objc_protocol_list *next;\n";
3490 Result += "\tint protocol_count;\n";
3491 Result += "\tstruct _objc_protocol *class_protocols[";
3492 Result += utostr(Protocols.size());
3493 Result += "];\n} _OBJC_";
3494 Result += prefix;
3495 Result += "_PROTOCOLS_";
3496 Result += ClassName;
3497 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3498 "{\n\t0, ";
3499 Result += utostr(Protocols.size());
3500 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003501
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003502 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003503 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003504 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003505
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003506 for (unsigned i = 1; i != Protocols.size(); i++) {
3507 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003508 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003509 Result += "\n";
3510 }
3511 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003512}
3513
Steve Naroff621edce2009-04-29 16:37:50 +00003514
Mike Stump1eb44332009-09-09 15:08:12 +00003515/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003516/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003517void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003518 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003519 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003520 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003521 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003522 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003523 CDecl = CDecl->getNextClassCategory())
3524 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3525 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003526
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003527 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003528 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003529 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003530
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003531 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003532 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003533 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003534
3535 // If any of our property implementations have associated getters or
3536 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003537 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3538 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003539 Prop != PropEnd; ++Prop) {
3540 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3541 continue;
3542 if (!(*Prop)->getPropertyIvarDecl())
3543 continue;
3544 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3545 if (!PD)
3546 continue;
3547 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3548 InstanceMethods.push_back(Getter);
3549 if (PD->isReadOnly())
3550 continue;
3551 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3552 InstanceMethods.push_back(Setter);
3553 }
3554 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003555 true, "CATEGORY_", FullCategoryName.c_str(),
3556 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003557
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003558 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003559 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003560 false, "CATEGORY_", FullCategoryName.c_str(),
3561 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003563 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003564 // Null CDecl is case of a category implementation with no category interface
3565 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003566 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3567 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003568 /* struct _objc_category {
3569 char *category_name;
3570 char *class_name;
3571 struct _objc_method_list *instance_methods;
3572 struct _objc_method_list *class_methods;
3573 struct _objc_protocol_list *protocols;
3574 // Objective-C 1.0 extensions
3575 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003576 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003577 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003578 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003579 */
Mike Stump1eb44332009-09-09 15:08:12 +00003580
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003581 static bool objc_category = false;
3582 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003583 Result += "\nstruct _objc_category {\n";
3584 Result += "\tchar *category_name;\n";
3585 Result += "\tchar *class_name;\n";
3586 Result += "\tstruct _objc_method_list *instance_methods;\n";
3587 Result += "\tstruct _objc_method_list *class_methods;\n";
3588 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003589 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003590 Result += "\tstruct _objc_property_list *instance_properties;\n";
3591 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003592 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003593 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003594 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3595 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003596 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003598 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003599 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003600 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003602 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += "\t, (struct _objc_method_list *)"
3604 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3605 Result += FullCategoryName;
3606 Result += "\n";
3607 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003608 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003609 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003610 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003611 Result += "\t, (struct _objc_method_list *)"
3612 "&_OBJC_CATEGORY_CLASS_METHODS_";
3613 Result += FullCategoryName;
3614 Result += "\n";
3615 }
3616 else
3617 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Chris Lattnercafeb352009-02-20 18:18:36 +00003619 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003620 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003621 Result += FullCategoryName;
3622 Result += "\n";
3623 }
3624 else
3625 Result += "\t, 0\n";
3626 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003627}
3628
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003629/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3630/// ivar offset.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003631void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCContainerDecl *IDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00003632 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003633 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003634 if (ivar->isBitField()) {
3635 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3636 // place all bitfields at offset 0.
3637 Result += "0";
3638 } else {
3639 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003640 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003641 if (LangOpts.Microsoft)
3642 Result += "_IMPL";
3643 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003644 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003645 Result += ")";
3646 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003647}
3648
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003649//===----------------------------------------------------------------------===//
3650// Meta Data Emission
3651//===----------------------------------------------------------------------===//
3652
Steve Naroffb29b4272008-04-14 22:03:09 +00003653void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003654 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003655 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003656
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003657 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003658 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003659 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003660 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003661 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003662 }
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Chris Lattnerbe6df082007-12-12 07:56:42 +00003664 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003665 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003666 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003667 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003668 if (NumIvars > 0) {
3669 static bool objc_ivar = false;
3670 if (!objc_ivar) {
3671 /* struct _objc_ivar {
3672 char *ivar_name;
3673 char *ivar_type;
3674 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003675 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003676 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003677 Result += "\nstruct _objc_ivar {\n";
3678 Result += "\tchar *ivar_name;\n";
3679 Result += "\tchar *ivar_type;\n";
3680 Result += "\tint ivar_offset;\n";
3681 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003683 objc_ivar = true;
3684 }
3685
Steve Naroff946a6932008-03-11 00:12:29 +00003686 /* struct {
3687 int ivar_count;
3688 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003689 };
Steve Naroff946a6932008-03-11 00:12:29 +00003690 */
Mike Stump1eb44332009-09-09 15:08:12 +00003691 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003692 Result += "\tint ivar_count;\n";
3693 Result += "\tstruct _objc_ivar ivar_list[";
3694 Result += utostr(NumIvars);
3695 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003696 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003697 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003698 "{\n\t";
3699 Result += utostr(NumIvars);
3700 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003701
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003702 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003703 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003704 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003705 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003706 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003707 IV != IVEnd; ++IV)
3708 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003709 IVI = IDecl->ivar_begin();
3710 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003711 } else {
3712 IVI = CDecl->ivar_begin();
3713 IVE = CDecl->ivar_end();
3714 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003715 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003716 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003717 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003718 std::string TmpString, StrEncoding;
3719 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3720 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003721 Result += StrEncoding;
3722 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003723 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003724 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003725 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003726 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003727 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003728 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003729 std::string TmpString, StrEncoding;
3730 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3731 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003732 Result += StrEncoding;
3733 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003734 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003735 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003736 }
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003738 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003739 }
Mike Stump1eb44332009-09-09 15:08:12 +00003740
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003741 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003742 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003743 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003744
3745 // If any of our property implementations have associated getters or
3746 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003747 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3748 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003749 Prop != PropEnd; ++Prop) {
3750 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3751 continue;
3752 if (!(*Prop)->getPropertyIvarDecl())
3753 continue;
3754 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3755 if (!PD)
3756 continue;
3757 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3758 InstanceMethods.push_back(Getter);
3759 if (PD->isReadOnly())
3760 continue;
3761 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3762 InstanceMethods.push_back(Setter);
3763 }
3764 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003765 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003767 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003768 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003769 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003770
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003772 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3773 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003775 // Declaration of class/meta-class metadata
3776 /* struct _objc_class {
3777 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003778 const char *super_class_name;
3779 char *name;
3780 long version;
3781 long info;
3782 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003783 struct _objc_ivar_list *ivars;
3784 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003785 struct objc_cache *cache;
3786 struct objc_protocol_list *protocols;
3787 const char *ivar_layout;
3788 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003789 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003790 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003791 static bool objc_class = false;
3792 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003793 Result += "\nstruct _objc_class {\n";
3794 Result += "\tstruct _objc_class *isa;\n";
3795 Result += "\tconst char *super_class_name;\n";
3796 Result += "\tchar *name;\n";
3797 Result += "\tlong version;\n";
3798 Result += "\tlong info;\n";
3799 Result += "\tlong instance_size;\n";
3800 Result += "\tstruct _objc_ivar_list *ivars;\n";
3801 Result += "\tstruct _objc_method_list *methods;\n";
3802 Result += "\tstruct objc_cache *cache;\n";
3803 Result += "\tstruct _objc_protocol_list *protocols;\n";
3804 Result += "\tconst char *ivar_layout;\n";
3805 Result += "\tstruct _objc_class_ext *ext;\n";
3806 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003807 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003808 }
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003810 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003811 ObjCInterfaceDecl *RootClass = 0;
3812 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003813 while (SuperClass) {
3814 RootClass = SuperClass;
3815 SuperClass = SuperClass->getSuperClass();
3816 }
3817 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003818
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003819 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003820 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003821 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003822 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003823 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003824 Result += "\"";
3825
3826 if (SuperClass) {
3827 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003828 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003829 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003830 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003831 Result += "\"";
3832 }
3833 else {
3834 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003835 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003836 Result += "\"";
3837 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003838 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003839 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003840 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003841 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003842 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003843 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003844 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003845 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003846 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003847 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003848 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003849 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003850 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003851 Result += ",0,0\n";
3852 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003853 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003854 Result += "\t,0,0,0,0\n";
3855 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003857 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003858 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003859 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003860 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003861 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003862 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003863 if (SuperClass) {
3864 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003865 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003866 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003867 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003868 Result += "\"";
3869 }
3870 else {
3871 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003872 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003873 Result += "\"";
3874 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003875 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003876 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003877 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003878 Result += ",0";
3879 else {
3880 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003881 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003882 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003883 if (LangOpts.Microsoft)
3884 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003885 Result += ")";
3886 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003887 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003888 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003889 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003890 Result += "\n\t";
3891 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003892 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003893 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003894 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003895 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003896 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003897 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003898 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003899 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003900 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003901 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003902 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003903 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003904 Result += ", 0,0\n";
3905 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003906 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003907 Result += ",0,0,0\n";
3908 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003909}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003910
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003911/// RewriteImplementations - This routine rewrites all method implementations
3912/// and emits meta-data.
3913
Steve Narofface66252008-11-13 20:07:04 +00003914void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003915 int ClsDefCount = ClassImplementation.size();
3916 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003917
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003918 // Rewrite implemented methods
3919 for (int i = 0; i < ClsDefCount; i++)
3920 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003922 for (int i = 0; i < CatDefCount; i++)
3923 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003924}
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Steve Narofface66252008-11-13 20:07:04 +00003926void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3927 int ClsDefCount = ClassImplementation.size();
3928 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00003929
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003930 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003931 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003932 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003934 // For each implemented category, write out all its meta data.
3935 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003936 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003937
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003938 // Write objc_symtab metadata
3939 /*
3940 struct _objc_symtab
3941 {
3942 long sel_ref_cnt;
3943 SEL *refs;
3944 short cls_def_cnt;
3945 short cat_def_cnt;
3946 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003947 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003948 */
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003950 Result += "\nstruct _objc_symtab {\n";
3951 Result += "\tlong sel_ref_cnt;\n";
3952 Result += "\tSEL *refs;\n";
3953 Result += "\tshort cls_def_cnt;\n";
3954 Result += "\tshort cat_def_cnt;\n";
3955 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3956 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003958 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003959 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003960 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003961 + ", " + utostr(CatDefCount) + "\n";
3962 for (int i = 0; i < ClsDefCount; i++) {
3963 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003964 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003965 Result += "\n";
3966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003968 for (int i = 0; i < CatDefCount; i++) {
3969 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003970 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003971 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003972 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003973 Result += "\n";
3974 }
Mike Stump1eb44332009-09-09 15:08:12 +00003975
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003976 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003977
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003978 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003979
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003980 /*
3981 struct _objc_module {
3982 long version;
3983 long size;
3984 const char *name;
3985 struct _objc_symtab *symtab;
3986 }
3987 */
Mike Stump1eb44332009-09-09 15:08:12 +00003988
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003989 Result += "\nstruct _objc_module {\n";
3990 Result += "\tlong version;\n";
3991 Result += "\tlong size;\n";
3992 Result += "\tconst char *name;\n";
3993 Result += "\tstruct _objc_symtab *symtab;\n";
3994 Result += "};\n\n";
3995 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003996 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003997 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003998 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003999 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004000
4001 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004002 if (ProtocolExprDecls.size()) {
4003 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4004 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004005 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004006 E = ProtocolExprDecls.end(); I != E; ++I) {
4007 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4008 Result += (*I)->getNameAsString();
4009 Result += " = &_OBJC_PROTOCOL_";
4010 Result += (*I)->getNameAsString();
4011 Result += ";\n";
4012 }
4013 Result += "#pragma data_seg(pop)\n\n";
4014 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004015 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004016 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004017 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4018 Result += "&_OBJC_MODULES;\n";
4019 Result += "#pragma data_seg(pop)\n\n";
4020 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004021}
Chris Lattner311ff022007-10-16 22:36:42 +00004022
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004023void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4024 const std::string &Name,
4025 ValueDecl *VD) {
4026 assert(BlockByRefDeclNo.count(VD) &&
4027 "RewriteByRefString: ByRef decl missing");
4028 ResultStr += "struct __Block_byref_" + Name +
4029 "_" + utostr(BlockByRefDeclNo[VD]) ;
4030}
4031
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004032static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4033 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4034 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4035 return false;
4036}
4037
Steve Naroff54055232008-10-27 17:20:55 +00004038std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4039 const char *funcName,
4040 std::string Tag) {
4041 const FunctionType *AFT = CE->getFunctionType();
4042 QualType RT = AFT->getResultType();
4043 std::string StructRef = "struct " + Tag;
4044 std::string S = "static " + RT.getAsString() + " __" +
4045 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004046
Steve Naroff54055232008-10-27 17:20:55 +00004047 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Douglas Gregor72564e72009-02-26 23:50:07 +00004049 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004050 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004051 // block (to reference imported block decl refs).
4052 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004053 } else if (BD->param_empty()) {
4054 S += "(" + StructRef + " *__cself)";
4055 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004056 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004057 assert(FT && "SynthesizeBlockFunc: No function proto");
4058 S += '(';
4059 // first add the implicit argument.
4060 S += StructRef + " *__cself, ";
4061 std::string ParamStr;
4062 for (BlockDecl::param_iterator AI = BD->param_begin(),
4063 E = BD->param_end(); AI != E; ++AI) {
4064 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004065 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004066 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004067 S += ParamStr;
4068 }
4069 if (FT->isVariadic()) {
4070 if (!BD->param_empty()) S += ", ";
4071 S += "...";
4072 }
4073 S += ')';
4074 }
4075 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004076
Steve Naroff54055232008-10-27 17:20:55 +00004077 // Create local declarations to avoid rewriting all closure decl ref exprs.
4078 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004079 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004080 E = BlockByRefDecls.end(); I != E; ++I) {
4081 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004082 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004083 std::string TypeString;
4084 RewriteByRefString(TypeString, Name, (*I));
4085 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004086 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004087 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004088 }
Steve Naroff54055232008-10-27 17:20:55 +00004089 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004090 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004091 E = BlockByCopyDecls.end(); I != E; ++I) {
4092 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004093 // Handle nested closure invocation. For example:
4094 //
4095 // void (^myImportedClosure)(void);
4096 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004097 //
Steve Naroff54055232008-10-27 17:20:55 +00004098 // void (^anotherClosure)(void);
4099 // anotherClosure = ^(void) {
4100 // myImportedClosure(); // import and invoke the closure
4101 // };
4102 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004103 if (isTopLevelBlockPointerType((*I)->getType())) {
4104 RewriteBlockPointerTypeVariable(S, (*I));
4105 S += " = (";
4106 RewriteBlockPointerType(S, (*I)->getType());
4107 S += ")";
4108 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4109 }
4110 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004111 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004112 QualType QT = (*I)->getType();
4113 if (HasLocalVariableExternalStorage(*I))
4114 QT = Context->getPointerType(QT);
4115 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004116 S += Name + " = __cself->" +
4117 (*I)->getNameAsString() + "; // bound by copy\n";
4118 }
Steve Naroff54055232008-10-27 17:20:55 +00004119 }
4120 std::string RewrittenStr = RewrittenBlockExprs[CE];
4121 const char *cstr = RewrittenStr.c_str();
4122 while (*cstr++ != '{') ;
4123 S += cstr;
4124 S += "\n";
4125 return S;
4126}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004127
Steve Naroff54055232008-10-27 17:20:55 +00004128std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4129 const char *funcName,
4130 std::string Tag) {
4131 std::string StructRef = "struct " + Tag;
4132 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004133
Steve Naroff54055232008-10-27 17:20:55 +00004134 S += funcName;
4135 S += "_block_copy_" + utostr(i);
4136 S += "(" + StructRef;
4137 S += "*dst, " + StructRef;
4138 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004139 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004140 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004141 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004142 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004143 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004144 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004145 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004146 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004147 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004148 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004149 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004150 S += "}\n";
4151
Steve Naroff54055232008-10-27 17:20:55 +00004152 S += "\nstatic void __";
4153 S += funcName;
4154 S += "_block_dispose_" + utostr(i);
4155 S += "(" + StructRef;
4156 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004157 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004158 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004159 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004160 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004161 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004162 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004163 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004164 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004167 return S;
4168}
4169
Steve Naroff01aec112009-12-06 21:14:13 +00004170std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4171 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004172 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004173 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Steve Naroff54055232008-10-27 17:20:55 +00004175 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004176 S += " struct " + Desc;
4177 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Steve Naroff01aec112009-12-06 21:14:13 +00004179 Constructor += "(void *fp, "; // Invoke function pointer.
4180 Constructor += "struct " + Desc; // Descriptor pointer.
4181 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Steve Naroff54055232008-10-27 17:20:55 +00004183 if (BlockDeclRefs.size()) {
4184 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004185 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004186 E = BlockByCopyDecls.end(); I != E; ++I) {
4187 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004188 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004189 std::string ArgName = "_" + FieldName;
4190 // Handle nested closure invocation. For example:
4191 //
4192 // void (^myImportedBlock)(void);
4193 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004194 //
Steve Naroff54055232008-10-27 17:20:55 +00004195 // void (^anotherBlock)(void);
4196 // anotherBlock = ^(void) {
4197 // myImportedBlock(); // import and invoke the closure
4198 // };
4199 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004200 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004201 S += "struct __block_impl *";
4202 Constructor += ", void *" + ArgName;
4203 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004204 QualType QT = (*I)->getType();
4205 if (HasLocalVariableExternalStorage(*I))
4206 QT = Context->getPointerType(QT);
4207 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4208 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004209 Constructor += ", " + ArgName;
4210 }
4211 S += FieldName + ";\n";
4212 }
4213 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004214 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004215 E = BlockByRefDecls.end(); I != E; ++I) {
4216 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004217 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004218 std::string ArgName = "_" + FieldName;
4219 // Handle nested closure invocation. For example:
4220 //
4221 // void (^myImportedBlock)(void);
4222 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004223 //
Steve Naroff54055232008-10-27 17:20:55 +00004224 // void (^anotherBlock)(void);
4225 // anotherBlock = ^(void) {
4226 // myImportedBlock(); // import and invoke the closure
4227 // };
4228 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004229 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004230 S += "struct __block_impl *";
4231 Constructor += ", void *" + ArgName;
4232 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004233 std::string TypeString;
4234 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004235 TypeString += " *";
4236 FieldName = TypeString + FieldName;
4237 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004238 Constructor += ", " + ArgName;
4239 }
4240 S += FieldName + "; // by ref\n";
4241 }
4242 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004243 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004244 if (GlobalVarDecl)
4245 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4246 else
4247 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004248 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004249
Steve Naroff01aec112009-12-06 21:14:13 +00004250 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004251
Steve Naroff54055232008-10-27 17:20:55 +00004252 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004253 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004254 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004255 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004256 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004257 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004258 Constructor += Name + " = (struct __block_impl *)_";
4259 else
4260 Constructor += Name + " = _";
4261 Constructor += Name + ";\n";
4262 }
4263 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004264 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004265 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004266 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004267 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004268 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004269 Constructor += Name + " = (struct __block_impl *)_";
4270 else
4271 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004272 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004273 }
4274 } else {
4275 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004276 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004277 if (GlobalVarDecl)
4278 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4279 else
4280 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004281 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4282 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004283 }
4284 Constructor += " ";
4285 Constructor += "}\n";
4286 S += Constructor;
4287 S += "};\n";
4288 return S;
4289}
4290
Steve Naroff01aec112009-12-06 21:14:13 +00004291std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4292 std::string ImplTag, int i,
4293 const char *FunName,
4294 unsigned hasCopy) {
4295 std::string S = "\nstatic struct " + DescTag;
4296
4297 S += " {\n unsigned long reserved;\n";
4298 S += " unsigned long Block_size;\n";
4299 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004300 S += " void (*copy)(struct ";
4301 S += ImplTag; S += "*, struct ";
4302 S += ImplTag; S += "*);\n";
4303
4304 S += " void (*dispose)(struct ";
4305 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004306 }
4307 S += "} ";
4308
4309 S += DescTag + "_DATA = { 0, sizeof(struct ";
4310 S += ImplTag + ")";
4311 if (hasCopy) {
4312 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4313 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4314 }
4315 S += "};\n";
4316 return S;
4317}
4318
Steve Naroff54055232008-10-27 17:20:55 +00004319void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004320 const char *FunName) {
4321 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004322 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004323 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004324 bool RewriteSC = (GlobalVarDecl &&
4325 !Blocks.empty() &&
4326 GlobalVarDecl->getStorageClass() == VarDecl::Static &&
4327 GlobalVarDecl->getType().getCVRQualifiers());
4328 if (RewriteSC) {
4329 std::string SC(" void __");
4330 SC += GlobalVarDecl->getNameAsString();
4331 SC += "() {}";
4332 InsertText(FunLocStart, SC);
4333 }
4334
Steve Naroff54055232008-10-27 17:20:55 +00004335 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004336 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4337 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004338 // Need to copy-in the inner copied-in variables not actually used in this
4339 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004340 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4341 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4342 ValueDecl *VD = Exp->getDecl();
4343 BlockDeclRefs.push_back(Exp);
4344 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4345 BlockByCopyDeclsPtrSet.insert(VD);
4346 BlockByCopyDecls.push_back(VD);
4347 }
4348 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4349 BlockByRefDeclsPtrSet.insert(VD);
4350 BlockByRefDecls.push_back(VD);
4351 }
4352 }
Steve Naroff54055232008-10-27 17:20:55 +00004353
Steve Naroff01aec112009-12-06 21:14:13 +00004354 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4355 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004356
Steve Naroff01aec112009-12-06 21:14:13 +00004357 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004358
Benjamin Kramerd999b372010-02-14 14:14:16 +00004359 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004360
Steve Naroff01aec112009-12-06 21:14:13 +00004361 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Benjamin Kramerd999b372010-02-14 14:14:16 +00004363 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004364
4365 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004366 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004367 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004368 }
Steve Naroff01aec112009-12-06 21:14:13 +00004369 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4370 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004371 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004372
Steve Naroff54055232008-10-27 17:20:55 +00004373 BlockDeclRefs.clear();
4374 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004375 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004376 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004377 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004378 ImportedBlockDecls.clear();
4379 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004380 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004381 // Must insert any 'const/volatile/static here. Since it has been
4382 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004383 std::string SC;
4384 if (GlobalVarDecl->getStorageClass() == VarDecl::Static)
4385 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004386 if (GlobalVarDecl->getType().isConstQualified())
4387 SC += "const ";
4388 if (GlobalVarDecl->getType().isVolatileQualified())
4389 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004390 if (GlobalVarDecl->getType().isRestrictQualified())
4391 SC += "restrict ";
4392 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004393 }
4394
Steve Naroff54055232008-10-27 17:20:55 +00004395 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004396 InnerDeclRefsCount.clear();
4397 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004398 RewrittenBlockExprs.clear();
4399}
4400
4401void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4402 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004403 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Steve Naroff54055232008-10-27 17:20:55 +00004405 SynthesizeBlockLiterals(FunLocStart, FuncName);
4406}
4407
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004408static void BuildUniqueMethodName(std::string &Name,
4409 ObjCMethodDecl *MD) {
4410 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4411 Name = IFace->getNameAsCString();
4412 Name += "__" + MD->getSelector().getAsString();
4413 // Convert colons to underscores.
4414 std::string::size_type loc = 0;
4415 while ((loc = Name.find(":", loc)) != std::string::npos)
4416 Name.replace(loc, 1, "_");
4417}
4418
Steve Naroff54055232008-10-27 17:20:55 +00004419void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004420 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4421 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004422 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004423 std::string FuncName;
4424 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004425 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4426}
4427
4428void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4429 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4430 CI != E; ++CI)
4431 if (*CI) {
4432 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4433 GetBlockDeclRefExprs(CBE->getBody());
4434 else
4435 GetBlockDeclRefExprs(*CI);
4436 }
4437 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004438 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004439 // FIXME: Handle enums.
4440 if (!isa<FunctionDecl>(CDRE->getDecl()))
4441 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004442 }
4443 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4444 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4445 BlockDeclRefExpr *BDRE =
4446 new (Context)BlockDeclRefExpr(DRE->getDecl(), DRE->getType(),
4447 DRE->getLocation(), false);
4448 BlockDeclRefs.push_back(BDRE);
4449 }
4450
Steve Naroff54055232008-10-27 17:20:55 +00004451 return;
4452}
4453
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004454void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4455 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004456 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004457 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4458 CI != E; ++CI)
4459 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004460 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4461 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004462 GetInnerBlockDeclRefExprs(CBE->getBody(),
4463 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004464 InnerContexts);
4465 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004466 else
4467 GetInnerBlockDeclRefExprs(*CI,
4468 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004469 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004470
4471 }
4472 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004473 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004474 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004475 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004476 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004477 }
4478 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4479 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4480 if (Var->isFunctionOrMethodVarDecl())
4481 ImportedLocalExternalDecls.insert(Var);
4482 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004483
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004484 return;
4485}
4486
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004487Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004488 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004489 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004491 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004492 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004493 } else if (const BlockDeclRefExpr *CDRE =
4494 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004495 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004496 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004497 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004498 }
4499 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4500 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4501 }
4502 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4503 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4504 else if (const ConditionalOperator *CEXPR =
4505 dyn_cast<ConditionalOperator>(BlockExp)) {
4506 Expr *LHSExp = CEXPR->getLHS();
4507 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4508 Expr *RHSExp = CEXPR->getRHS();
4509 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4510 Expr *CONDExp = CEXPR->getCond();
4511 ConditionalOperator *CondExpr =
4512 new (Context) ConditionalOperator(CONDExp,
4513 SourceLocation(), cast<Expr>(LHSStmt),
4514 SourceLocation(), cast<Expr>(RHSStmt),
4515 Exp->getType());
4516 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004517 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4518 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004519 } else {
4520 assert(1 && "RewriteBlockClass: Bad type");
4521 }
4522 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004523 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004524 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004525 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004526 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004527
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004528 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4529 SourceLocation(),
4530 &Context->Idents.get("__block_impl"));
4531 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004532
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004533 // Generate a funky cast.
4534 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004536 // Push the block argument type.
4537 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004538 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004539 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004540 E = FTP->arg_type_end(); I && (I != E); ++I) {
4541 QualType t = *I;
4542 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004543 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004544 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004545 t = Context->getPointerType(BPT->getPointeeType());
4546 }
4547 ArgTypes.push_back(t);
4548 }
Steve Naroff54055232008-10-27 17:20:55 +00004549 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004550 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004551 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004552 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4553 false, false, 0, 0,
Rafael Espindola264ba482010-03-30 20:24:48 +00004554 FunctionType::ExtInfo());
Mike Stump1eb44332009-09-09 15:08:12 +00004555
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004556 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004557
John McCall9d125032010-01-15 18:39:57 +00004558 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4559 CastExpr::CK_Unknown,
4560 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004561 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004562 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4563 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004564 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Douglas Gregor44b43212008-12-11 16:49:14 +00004566 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004567 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004568 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004569 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4570 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004571
John McCall9d125032010-01-15 18:39:57 +00004572 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4573 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004574 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004575
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004576 llvm::SmallVector<Expr*, 8> BlkExprs;
4577 // Add the implicit argument.
4578 BlkExprs.push_back(BlkCast);
4579 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004580 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004581 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004582 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004583 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004584 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4585 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004586 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004587 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004588}
4589
4590void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004591 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004592 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004593}
4594
Steve Naroff621edce2009-04-29 16:37:50 +00004595// We need to return the rewritten expression to handle cases where the
4596// BlockDeclRefExpr is embedded in another expression being rewritten.
4597// For example:
4598//
4599// int main() {
4600// __block Foo *f;
4601// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004602//
Steve Naroff621edce2009-04-29 16:37:50 +00004603// void (^myblock)() = ^() {
4604// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4605// i = 77;
4606// };
4607//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004608Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004609 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004610 // for each DeclRefExp where BYREFVAR is name of the variable.
4611 ValueDecl *VD;
4612 bool isArrow = true;
4613 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4614 VD = BDRE->getDecl();
4615 else {
4616 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4617 isArrow = false;
4618 }
4619
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004620 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4621 &Context->Idents.get("__forwarding"),
4622 Context->VoidPtrTy, 0,
4623 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004624 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4625 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004626 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004627
4628 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004629 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4630 &Context->Idents.get(Name),
4631 Context->VoidPtrTy, 0,
4632 /*BitWidth=*/0, /*Mutable=*/true);
4633 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004634 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004635
4636
4637
Steve Naroffdf8570d2009-02-02 17:19:26 +00004638 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004639 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4640 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004641 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004642 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004643}
4644
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004645// Rewrites the imported local variable V with external storage
4646// (static, extern, etc.) as *V
4647//
4648Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4649 ValueDecl *VD = DRE->getDecl();
4650 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4651 if (!ImportedLocalExternalDecls.count(Var))
4652 return DRE;
4653 Expr *Exp = new (Context) UnaryOperator(DRE, UnaryOperator::Deref,
4654 DRE->getType(), DRE->getLocation());
4655 // Need parens to enforce precedence.
4656 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4657 Exp);
4658 ReplaceStmt(DRE, PE);
4659 return PE;
4660}
4661
Steve Naroffb2f9e512008-11-03 23:29:32 +00004662void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4663 SourceLocation LocStart = CE->getLParenLoc();
4664 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004665
4666 // Need to avoid trying to rewrite synthesized casts.
4667 if (LocStart.isInvalid())
4668 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004669 // Need to avoid trying to rewrite casts contained in macros.
4670 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4671 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004672
Steve Naroff54055232008-10-27 17:20:55 +00004673 const char *startBuf = SM->getCharacterData(LocStart);
4674 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004675 QualType QT = CE->getType();
4676 const Type* TypePtr = QT->getAs<Type>();
4677 if (isa<TypeOfExprType>(TypePtr)) {
4678 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4679 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4680 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004681 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004682 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004683 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004684 return;
4685 }
Steve Naroff54055232008-10-27 17:20:55 +00004686 // advance the location to startArgList.
4687 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Steve Naroff54055232008-10-27 17:20:55 +00004689 while (*argPtr++ && (argPtr < endBuf)) {
4690 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004691 case '^':
4692 // Replace the '^' with '*'.
4693 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004694 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004695 break;
Steve Naroff54055232008-10-27 17:20:55 +00004696 }
4697 }
4698 return;
4699}
4700
4701void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4702 SourceLocation DeclLoc = FD->getLocation();
4703 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004704
Steve Naroff54055232008-10-27 17:20:55 +00004705 // We have 1 or more arguments that have closure pointers.
4706 const char *startBuf = SM->getCharacterData(DeclLoc);
4707 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004708
Steve Naroff54055232008-10-27 17:20:55 +00004709 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004710
Steve Naroff54055232008-10-27 17:20:55 +00004711 parenCount++;
4712 // advance the location to startArgList.
4713 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4714 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Steve Naroff54055232008-10-27 17:20:55 +00004716 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Steve Naroff54055232008-10-27 17:20:55 +00004718 while (*argPtr++ && parenCount) {
4719 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004720 case '^':
4721 // Replace the '^' with '*'.
4722 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004723 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004724 break;
4725 case '(':
4726 parenCount++;
4727 break;
4728 case ')':
4729 parenCount--;
4730 break;
Steve Naroff54055232008-10-27 17:20:55 +00004731 }
4732 }
4733 return;
4734}
4735
4736bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004737 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004738 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004739 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004740 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004741 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004742 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004743 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004744 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004745 }
4746 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004747 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004748 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004749 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004750 return true;
4751 }
4752 return false;
4753}
4754
Ted Kremenek8189cde2009-02-07 01:47:29 +00004755void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4756 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004757 const char *argPtr = strchr(Name, '(');
4758 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Naroff54055232008-10-27 17:20:55 +00004760 LParen = argPtr; // output the start.
4761 argPtr++; // skip past the left paren.
4762 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004763
Steve Naroff54055232008-10-27 17:20:55 +00004764 while (*argPtr && parenCount) {
4765 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004766 case '(': parenCount++; break;
4767 case ')': parenCount--; break;
4768 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004769 }
4770 if (parenCount) argPtr++;
4771 }
4772 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4773 RParen = argPtr; // output the end
4774}
4775
4776void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4777 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4778 RewriteBlockPointerFunctionArgs(FD);
4779 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004780 }
Steve Naroff54055232008-10-27 17:20:55 +00004781 // Handle Variables and Typedefs.
4782 SourceLocation DeclLoc = ND->getLocation();
4783 QualType DeclT;
4784 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4785 DeclT = VD->getType();
4786 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4787 DeclT = TDD->getUnderlyingType();
4788 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4789 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004790 else
Steve Naroff54055232008-10-27 17:20:55 +00004791 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004792
Steve Naroff54055232008-10-27 17:20:55 +00004793 const char *startBuf = SM->getCharacterData(DeclLoc);
4794 const char *endBuf = startBuf;
4795 // scan backward (from the decl location) for the end of the previous decl.
4796 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4797 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Steve Naroff54055232008-10-27 17:20:55 +00004799 // *startBuf != '^' if we are dealing with a pointer to function that
4800 // may take block argument types (which will be handled below).
4801 if (*startBuf == '^') {
4802 // Replace the '^' with '*', computing a negative offset.
4803 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004804 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004805 }
4806 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4807 // Replace the '^' with '*' for arguments.
4808 DeclLoc = ND->getLocation();
4809 startBuf = SM->getCharacterData(DeclLoc);
4810 const char *argListBegin, *argListEnd;
4811 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4812 while (argListBegin < argListEnd) {
4813 if (*argListBegin == '^') {
4814 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004815 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004816 }
4817 argListBegin++;
4818 }
4819 }
4820 return;
4821}
4822
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004823
4824/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4825/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4826/// struct Block_byref_id_object *src) {
4827/// _Block_object_assign (&_dest->object, _src->object,
4828/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4829/// [|BLOCK_FIELD_IS_WEAK]) // object
4830/// _Block_object_assign(&_dest->object, _src->object,
4831/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4832/// [|BLOCK_FIELD_IS_WEAK]) // block
4833/// }
4834/// And:
4835/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4836/// _Block_object_dispose(_src->object,
4837/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4838/// [|BLOCK_FIELD_IS_WEAK]) // object
4839/// _Block_object_dispose(_src->object,
4840/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4841/// [|BLOCK_FIELD_IS_WEAK]) // block
4842/// }
4843
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004844std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4845 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004846 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004847 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004848 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004849 CopyDestroyCache.insert(flag);
4850 S = "static void __Block_byref_id_object_copy_";
4851 S += utostr(flag);
4852 S += "(void *dst, void *src) {\n";
4853
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004854 // offset into the object pointer is computed as:
4855 // void * + void* + int + int + void* + void *
4856 unsigned IntSize =
4857 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4858 unsigned VoidPtrSize =
4859 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4860
4861 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4862 S += " _Block_object_assign((char*)dst + ";
4863 S += utostr(offset);
4864 S += ", *(void * *) ((char*)src + ";
4865 S += utostr(offset);
4866 S += "), ";
4867 S += utostr(flag);
4868 S += ");\n}\n";
4869
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004870 S += "static void __Block_byref_id_object_dispose_";
4871 S += utostr(flag);
4872 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004873 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4874 S += utostr(offset);
4875 S += "), ";
4876 S += utostr(flag);
4877 S += ");\n}\n";
4878 return S;
4879}
4880
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004881/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4882/// the declaration into:
4883/// struct __Block_byref_ND {
4884/// void *__isa; // NULL for everything except __weak pointers
4885/// struct __Block_byref_ND *__forwarding;
4886/// int32_t __flags;
4887/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004888/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4889/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004890/// typex ND;
4891/// };
4892///
4893/// It then replaces declaration of ND variable with:
4894/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4895/// __size=sizeof(struct __Block_byref_ND),
4896/// ND=initializer-if-any};
4897///
4898///
4899void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004900 // Insert declaration for the function in which block literal is
4901 // used.
4902 if (CurFunctionDeclToDeclareForBlock)
4903 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004904 int flag = 0;
4905 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004906 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004907 if (DeclLoc.isInvalid())
4908 // If type location is missing, it is because of missing type (a warning).
4909 // Use variable's location which is good for this case.
4910 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004911 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004912 SourceLocation X = ND->getLocEnd();
4913 X = SM->getInstantiationLoc(X);
4914 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004915 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004916 std::string ByrefType;
4917 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004918 ByrefType += " {\n";
4919 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004920 RewriteByRefString(ByrefType, Name, ND);
4921 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004922 ByrefType += " int __flags;\n";
4923 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004924 // Add void *__Block_byref_id_object_copy;
4925 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004926 QualType Ty = ND->getType();
4927 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4928 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004929 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4930 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004931 }
4932
4933 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004934 ByrefType += " " + Name + ";\n";
4935 ByrefType += "};\n";
4936 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004937 SourceLocation FunLocStart;
4938 if (CurFunctionDef)
4939 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4940 else {
4941 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4942 FunLocStart = CurMethodDef->getLocStart();
4943 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004944 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004945 if (Ty.isObjCGCWeak()) {
4946 flag |= BLOCK_FIELD_IS_WEAK;
4947 isa = 1;
4948 }
4949
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004950 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004951 flag = BLOCK_BYREF_CALLER;
4952 QualType Ty = ND->getType();
4953 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4954 if (Ty->isBlockPointerType())
4955 flag |= BLOCK_FIELD_IS_BLOCK;
4956 else
4957 flag |= BLOCK_FIELD_IS_OBJECT;
4958 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004959 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004960 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004961 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004962
4963 // struct __Block_byref_ND ND =
4964 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4965 // initializer-if-any};
4966 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004967 unsigned flags = 0;
4968 if (HasCopyAndDispose)
4969 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004970 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004971 ByrefType.clear();
4972 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004973 std::string ForwardingCastType("(");
4974 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004975 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004976 ByrefType += " " + Name + " = {(void*)";
4977 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004978 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004979 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004980 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004981 ByrefType += "sizeof(";
4982 RewriteByRefString(ByrefType, Name, ND);
4983 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004984 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004985 ByrefType += ", __Block_byref_id_object_copy_";
4986 ByrefType += utostr(flag);
4987 ByrefType += ", __Block_byref_id_object_dispose_";
4988 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004989 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004990 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004991 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004992 }
4993 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004994 SourceLocation startLoc;
4995 Expr *E = ND->getInit();
4996 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4997 startLoc = ECE->getLParenLoc();
4998 else
4999 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00005000 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005001 endBuf = SM->getCharacterData(startLoc);
5002
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005003 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005004 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005005 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005006 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005007 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005008 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005009 ByrefType += "sizeof(";
5010 RewriteByRefString(ByrefType, Name, ND);
5011 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005012 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005013 ByrefType += "__Block_byref_id_object_copy_";
5014 ByrefType += utostr(flag);
5015 ByrefType += ", __Block_byref_id_object_dispose_";
5016 ByrefType += utostr(flag);
5017 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005018 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005019 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005020
5021 // Complete the newly synthesized compound expression by inserting a right
5022 // curly brace before the end of the declaration.
5023 // FIXME: This approach avoids rewriting the initializer expression. It
5024 // also assumes there is only one declarator. For example, the following
5025 // isn't currently supported by this routine (in general):
5026 //
5027 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5028 //
5029 const char *startBuf = SM->getCharacterData(startLoc);
5030 const char *semiBuf = strchr(startBuf, ';');
5031 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5032 SourceLocation semiLoc =
5033 startLoc.getFileLocWithOffset(semiBuf-startBuf);
5034
Benjamin Kramerd999b372010-02-14 14:14:16 +00005035 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005036 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005037 return;
5038}
5039
Mike Stump1eb44332009-09-09 15:08:12 +00005040void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005041 // Add initializers for any closure decl refs.
5042 GetBlockDeclRefExprs(Exp->getBody());
5043 if (BlockDeclRefs.size()) {
5044 // Unique all "by copy" declarations.
5045 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005046 if (!BlockDeclRefs[i]->isByRef()) {
5047 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5048 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5049 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5050 }
5051 }
Steve Naroff54055232008-10-27 17:20:55 +00005052 // Unique all "by ref" declarations.
5053 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5054 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005055 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5056 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5057 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5058 }
Steve Naroff54055232008-10-27 17:20:55 +00005059 }
5060 // Find any imported blocks...they will need special attention.
5061 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005062 if (BlockDeclRefs[i]->isByRef() ||
5063 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005064 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005065 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005066 }
5067}
5068
Steve Narofffa15fd92008-10-28 20:29:00 +00005069FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
5070 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005071 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00005072 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00005073 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00005074 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005075}
5076
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005077Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
5078 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005079 Blocks.push_back(Exp);
5080
5081 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005082
5083 // Add inner imported variables now used in current block.
5084 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005085 if (!InnerBlockDeclRefs.empty()) {
5086 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5087 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5088 ValueDecl *VD = Exp->getDecl();
5089 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005090 // We need to save the copied-in variables in nested
5091 // blocks because it is needed at the end for some of the API generations.
5092 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005093 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5094 BlockDeclRefs.push_back(Exp);
5095 BlockByCopyDeclsPtrSet.insert(VD);
5096 BlockByCopyDecls.push_back(VD);
5097 }
5098 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5099 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5100 BlockDeclRefs.push_back(Exp);
5101 BlockByRefDeclsPtrSet.insert(VD);
5102 BlockByRefDecls.push_back(VD);
5103 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005104 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005105 // Find any imported blocks...they will need special attention.
5106 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5107 if (InnerBlockDeclRefs[i]->isByRef() ||
5108 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5109 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5110 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005111 }
5112 InnerDeclRefsCount.push_back(countOfInnerDecls);
5113
Steve Narofffa15fd92008-10-28 20:29:00 +00005114 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005115
Steve Narofffa15fd92008-10-28 20:29:00 +00005116 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005117 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005118 else if (CurMethodDef)
5119 BuildUniqueMethodName(FuncName, CurMethodDef);
5120 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005121 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005122
Steve Narofffa15fd92008-10-28 20:29:00 +00005123 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005124
Steve Narofffa15fd92008-10-28 20:29:00 +00005125 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5126 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005127
Steve Narofffa15fd92008-10-28 20:29:00 +00005128 // Get a pointer to the function type so we can cast appropriately.
5129 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
5130
5131 FunctionDecl *FD;
5132 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005133
Steve Narofffa15fd92008-10-28 20:29:00 +00005134 // Simulate a contructor call...
5135 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005136 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005137
Steve Narofffa15fd92008-10-28 20:29:00 +00005138 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005139
Steve Narofffdc03722008-10-29 21:23:59 +00005140 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00005141 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005142 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
5143 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005144 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5145 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005146 InitExprs.push_back(castExpr);
5147
Steve Naroff01aec112009-12-06 21:14:13 +00005148 // Initialize the block descriptor.
5149 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005150
Steve Naroff01aec112009-12-06 21:14:13 +00005151 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
5152 &Context->Idents.get(DescData.c_str()),
5153 Context->VoidPtrTy, 0,
5154 VarDecl::Static);
5155 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
5156 new (Context) DeclRefExpr(NewVD,
5157 Context->VoidPtrTy, SourceLocation()),
5158 UnaryOperator::AddrOf,
5159 Context->getPointerType(Context->VoidPtrTy),
5160 SourceLocation());
5161 InitExprs.push_back(DescRefExpr);
5162
Steve Narofffa15fd92008-10-28 20:29:00 +00005163 // Add initializers for any closure decl refs.
5164 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005165 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005166 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005167 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005168 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005169 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005170 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00005171 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005172 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005173 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005174 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005175 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005176 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5177 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005178 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00005179 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005180 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005181 if (HasLocalVariableExternalStorage(*I)) {
5182 QualType QT = (*I)->getType();
5183 QT = Context->getPointerType(QT);
5184 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf, QT,
5185 SourceLocation());
5186 }
5187
Steve Narofffa15fd92008-10-28 20:29:00 +00005188 }
Mike Stump1eb44332009-09-09 15:08:12 +00005189 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005190 }
5191 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005192 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005193 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005194 ValueDecl *ND = (*I);
5195 std::string Name(ND->getNameAsString());
5196 std::string RecName;
5197 RewriteByRefString(RecName, Name, ND);
5198 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5199 + sizeof("struct"));
5200 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5201 SourceLocation(), II);
5202 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5203 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5204
Chris Lattner8ec03f52008-11-24 03:54:41 +00005205 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005206 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5207 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005208 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005209 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005210 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005211 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005212 }
5213 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005214 if (ImportedBlockDecls.size()) {
5215 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5216 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005217 unsigned IntSize =
5218 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005219 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5220 Context->IntTy, SourceLocation());
5221 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005222 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005223 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5224 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005225 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005226 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005227 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005228 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5229 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005230 BlockDeclRefs.clear();
5231 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005232 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005233 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005234 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005235 ImportedBlockDecls.clear();
5236 return NewRep;
5237}
5238
5239//===----------------------------------------------------------------------===//
5240// Function Body / Expression rewriting
5241//===----------------------------------------------------------------------===//
5242
Steve Naroffc77a6362008-12-04 16:24:46 +00005243// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5244// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5245// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5246// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5247// Since the rewriter isn't capable of rewriting rewritten code, it's important
5248// we get this right.
5249void RewriteObjC::CollectPropertySetters(Stmt *S) {
5250 // Perform a bottom up traversal of all children.
5251 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5252 CI != E; ++CI)
5253 if (*CI)
5254 CollectPropertySetters(*CI);
5255
5256 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5257 if (BinOp->isAssignmentOp()) {
5258 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5259 PropSetters[PRE] = BinOp;
5260 }
5261 }
5262}
5263
Steve Narofffa15fd92008-10-28 20:29:00 +00005264Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005265 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005266 isa<DoStmt>(S) || isa<ForStmt>(S))
5267 Stmts.push_back(S);
5268 else if (isa<ObjCForCollectionStmt>(S)) {
5269 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005270 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005271 }
Mike Stump1eb44332009-09-09 15:08:12 +00005272
Steve Narofffa15fd92008-10-28 20:29:00 +00005273 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Steve Narofffa15fd92008-10-28 20:29:00 +00005275 // Perform a bottom up rewrite of all children.
5276 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5277 CI != E; ++CI)
5278 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005279 Stmt *newStmt;
5280 Stmt *S = (*CI);
5281 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5282 Expr *OldBase = IvarRefExpr->getBase();
5283 bool replaced = false;
5284 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5285 if (replaced) {
5286 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5287 ReplaceStmt(OldBase, IRE->getBase());
5288 else
5289 ReplaceStmt(S, newStmt);
5290 }
5291 }
5292 else
5293 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005294 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005295 *CI = newStmt;
5296 }
Mike Stump1eb44332009-09-09 15:08:12 +00005297
Steve Narofffa15fd92008-10-28 20:29:00 +00005298 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005299 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005300 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5301 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005302 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005303 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005304 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005305 // Rewrite the block body in place.
5306 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005307 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005308 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005309 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005310 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005311
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005312 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5313
Steve Narofffa15fd92008-10-28 20:29:00 +00005314 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005315 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005316 return blockTranscribed;
5317 }
5318 // Handle specific things.
5319 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5320 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005321
Steve Naroffc77a6362008-12-04 16:24:46 +00005322 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5323 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5324 if (BinOp) {
5325 // Because the rewriter doesn't allow us to rewrite rewritten code,
5326 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005327 DisableReplaceStmt = true;
5328 // Save the source range. Even if we disable the replacement, the
5329 // rewritten node will have been inserted into the tree. If the synthesized
5330 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005331 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005332 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5333 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005334 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005335 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005336 //
5337 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5338 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5339 // to see the original expression). Consider this example:
5340 //
5341 // Foo *obj1, *obj2;
5342 //
5343 // obj1.i = [obj2 rrrr];
5344 //
5345 // 'BinOp' for the previous expression looks like:
5346 //
5347 // (BinaryOperator 0x231ccf0 'int' '='
5348 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5349 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5350 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5351 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5352 //
5353 // 'newStmt' represents the rewritten message expression. For example:
5354 //
5355 // (CallExpr 0x231d300 'id':'struct objc_object *'
5356 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5357 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5358 // (CStyleCastExpr 0x231d220 'void *'
5359 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5360 //
5361 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5362 // can be used as the setter argument. ReplaceStmt() will still 'see'
5363 // the original RHS (since we haven't altered BinOp).
5364 //
Mike Stump1eb44332009-09-09 15:08:12 +00005365 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005366 // node. As a result, we now leak the original AST nodes.
5367 //
Steve Naroffb619d952008-12-09 12:56:34 +00005368 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005369 } else {
5370 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005371 }
5372 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005373 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5374 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005375
Steve Narofffa15fd92008-10-28 20:29:00 +00005376 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5377 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005378
Steve Narofffa15fd92008-10-28 20:29:00 +00005379 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005380#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005381 // Before we rewrite it, put the original message expression in a comment.
5382 SourceLocation startLoc = MessExpr->getLocStart();
5383 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Steve Narofffa15fd92008-10-28 20:29:00 +00005385 const char *startBuf = SM->getCharacterData(startLoc);
5386 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Steve Narofffa15fd92008-10-28 20:29:00 +00005388 std::string messString;
5389 messString += "// ";
5390 messString.append(startBuf, endBuf-startBuf+1);
5391 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005392
5393 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005394 // InsertText(clang::SourceLocation, char const*, unsigned int).
5395 // InsertText(startLoc, messString.c_str(), messString.size());
5396 // Tried this, but it didn't work either...
5397 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005398#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005399 return RewriteMessageExpr(MessExpr);
5400 }
Mike Stump1eb44332009-09-09 15:08:12 +00005401
Steve Narofffa15fd92008-10-28 20:29:00 +00005402 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5403 return RewriteObjCTryStmt(StmtTry);
5404
5405 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5406 return RewriteObjCSynchronizedStmt(StmtTry);
5407
5408 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5409 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005410
Steve Narofffa15fd92008-10-28 20:29:00 +00005411 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5412 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005413
5414 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005415 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005416 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005417 OrigStmtRange.getEnd());
5418 if (BreakStmt *StmtBreakStmt =
5419 dyn_cast<BreakStmt>(S))
5420 return RewriteBreakStmt(StmtBreakStmt);
5421 if (ContinueStmt *StmtContinueStmt =
5422 dyn_cast<ContinueStmt>(S))
5423 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005424
5425 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 // and cast exprs.
5427 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5428 // FIXME: What we're doing here is modifying the type-specifier that
5429 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005430 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005431 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5432 // the context of an ObjCForCollectionStmt. For example:
5433 // NSArray *someArray;
5434 // for (id <FooProtocol> index in someArray) ;
5435 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5436 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005437 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005438 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Steve Narofffa15fd92008-10-28 20:29:00 +00005440 // Blocks rewrite rules.
5441 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5442 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005443 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005444 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005445 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005446 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005447 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005449 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005450 if (VD->hasAttr<BlocksAttr>()) {
5451 static unsigned uniqueByrefDeclCount = 0;
5452 assert(!BlockByRefDeclNo.count(ND) &&
5453 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5454 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005455 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005456 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005457 else
5458 RewriteTypeOfDecl(VD);
5459 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005460 }
5461 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005462 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005464 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5466 }
5467 }
5468 }
Mike Stump1eb44332009-09-09 15:08:12 +00005469
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5471 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005472
5473 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005474 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5475 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005476 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5477 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005478 && "Statement stack mismatch");
5479 Stmts.pop_back();
5480 }
5481 // Handle blocks rewriting.
5482 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5483 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005484 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005485 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005486 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5487 ValueDecl *VD = DRE->getDecl();
5488 if (VD->hasAttr<BlocksAttr>())
5489 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005490 if (HasLocalVariableExternalStorage(VD))
5491 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005492 }
5493
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005495 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005496 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005497 ReplaceStmt(S, BlockCall);
5498 return BlockCall;
5499 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005500 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005501 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005502 RewriteCastExpr(CE);
5503 }
5504#if 0
5505 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005506 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005507 // Get the new text.
5508 std::string SStr;
5509 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005510 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005511 const std::string &Str = Buf.str();
5512
5513 printf("CAST = %s\n", &Str[0]);
5514 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5515 delete S;
5516 return Replacement;
5517 }
5518#endif
5519 // Return this stmt unmodified.
5520 return S;
5521}
5522
Steve Naroff3d7e7862009-12-05 15:55:59 +00005523void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5524 for (RecordDecl::field_iterator i = RD->field_begin(),
5525 e = RD->field_end(); i != e; ++i) {
5526 FieldDecl *FD = *i;
5527 if (isTopLevelBlockPointerType(FD->getType()))
5528 RewriteBlockPointerDecl(FD);
5529 if (FD->getType()->isObjCQualifiedIdType() ||
5530 FD->getType()->isObjCQualifiedInterfaceType())
5531 RewriteObjCQualifiedInterfaceTypes(FD);
5532 }
5533}
5534
Steve Narofffa15fd92008-10-28 20:29:00 +00005535/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5536/// main file of the input.
5537void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005539 if (FD->isOverloadedOperator())
5540 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005541
Steve Narofffa15fd92008-10-28 20:29:00 +00005542 // Since function prototypes don't have ParmDecl's, we check the function
5543 // prototype. This enables us to rewrite function declarations and
5544 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005545 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005546
Sebastian Redld3a413d2009-04-26 20:35:05 +00005547 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005548 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005549 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005550 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005551 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005552 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005553 Body =
5554 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5555 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005556 CurrentBody = 0;
5557 if (PropParentMap) {
5558 delete PropParentMap;
5559 PropParentMap = 0;
5560 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005561 // This synthesizes and inserts the block "impl" struct, invoke function,
5562 // and any copy/dispose helper functions.
5563 InsertBlockLiteralsWithinFunction(FD);
5564 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005565 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005566 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005567 return;
5568 }
5569 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005570 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005571 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005572 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005573 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005574 Body =
5575 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5576 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005577 CurrentBody = 0;
5578 if (PropParentMap) {
5579 delete PropParentMap;
5580 PropParentMap = 0;
5581 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005582 InsertBlockLiteralsWithinMethod(MD);
5583 CurMethodDef = 0;
5584 }
5585 }
5586 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5587 ClassImplementation.push_back(CI);
5588 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5589 CategoryImplementation.push_back(CI);
5590 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5591 RewriteForwardClassDecl(CD);
5592 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5593 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005594 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005595 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005596 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005597 CheckFunctionPointerDecl(VD->getType(), VD);
5598 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005599 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 RewriteCastExpr(CE);
5601 }
5602 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005603 } else if (VD->getType()->isRecordType()) {
5604 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5605 if (RD->isDefinition())
5606 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005607 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005608 if (VD->getInit()) {
5609 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005610 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005611 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005612 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005613 CurrentBody = 0;
5614 if (PropParentMap) {
5615 delete PropParentMap;
5616 PropParentMap = 0;
5617 }
Mike Stump1eb44332009-09-09 15:08:12 +00005618 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005619 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005620 GlobalVarDecl = 0;
5621
5622 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005623 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005624 RewriteCastExpr(CE);
5625 }
5626 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005627 return;
5628 }
5629 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005630 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005631 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005632 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005633 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5634 return;
5635 }
5636 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005637 if (RD->isDefinition())
5638 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005639 return;
5640 }
5641 // Nothing yet.
5642}
5643
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005644void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005645 if (Diags.hasErrorOccurred())
5646 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Steve Narofffa15fd92008-10-28 20:29:00 +00005648 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005649
Steve Naroff621edce2009-04-29 16:37:50 +00005650 // Here's a great place to add any extra declarations that may be needed.
5651 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005652 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005653 E = ProtocolExprDecls.end(); I != E; ++I)
5654 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5655
Benjamin Kramerd999b372010-02-14 14:14:16 +00005656 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005657 if (ClassImplementation.size() || CategoryImplementation.size())
5658 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005659
Steve Narofffa15fd92008-10-28 20:29:00 +00005660 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5661 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005662 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005663 Rewrite.getRewriteBufferFor(MainFileID)) {
5664 //printf("Changed:\n");
5665 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5666 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005667 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005668 }
Steve Narofface66252008-11-13 20:07:04 +00005669
Steve Naroff621edce2009-04-29 16:37:50 +00005670 if (ClassImplementation.size() || CategoryImplementation.size() ||
5671 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005672 // Rewrite Objective-c meta data*
5673 std::string ResultStr;
5674 SynthesizeMetaDataIntoBuffer(ResultStr);
5675 // Emit metadata.
5676 *OutFile << ResultStr;
5677 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005678 OutFile->flush();
5679}