blob: 350d6b20094d61cf361fcc6495fd39866275e962 [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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123 llvm::SmallVector<int, 32> InnerDeclRefsCount;
124 llvm::SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
125
Steve Naroff54055232008-10-27 17:20:55 +0000126 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
127 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Steve Naroff54055232008-10-27 17:20:55 +0000129 // Block related declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132 llvm::SmallVector<ValueDecl *, 8> BlockByRefDecls;
133 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000134 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136
137 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
138
Steve Naroffc77a6362008-12-04 16:24:46 +0000139 // This maps a property to it's assignment statement.
140 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000141 // This maps a property to it's synthesied message expression.
142 // This allows us to rewrite chained getters (e.g. o.a.b.c).
143 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Steve Naroff4c3580e2008-12-04 23:50:32 +0000145 // This maps an original source AST to it's rewritten form. This allows
146 // us to avoid rewriting the same node twice (which is very uncommon).
147 // This is needed to support some of the exotic property rewriting.
148 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000149
Steve Naroff54055232008-10-27 17:20:55 +0000150 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000151 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000152 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000153
Steve Naroffb619d952008-12-09 12:56:34 +0000154 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000156 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000157 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000158 virtual void Initialize(ASTContext &context);
159
Chris Lattnerf04da132007-10-24 17:06:59 +0000160 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000161 virtual void HandleTopLevelDecl(DeclGroupRef D) {
162 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
163 HandleTopLevelSingleDecl(*I);
164 }
165 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000166 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000167 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000168 Diagnostic &D, const LangOptions &LOpts,
169 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000170
171 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000173 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000174
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000175 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000176 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000177
Steve Naroff4c3580e2008-12-04 23:50:32 +0000178 if (ReplacingStmt)
179 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000180
Steve Naroffb619d952008-12-09 12:56:34 +0000181 if (DisableReplaceStmt)
182 return; // Used when rewriting the assignment of a property setter.
183
Steve Naroff4c3580e2008-12-04 23:50:32 +0000184 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000185 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000186 ReplacedNodes[Old] = New;
187 return;
188 }
189 if (SilenceRewriteMacroWarning)
190 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000191 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
192 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000193 }
Steve Naroffb619d952008-12-09 12:56:34 +0000194
195 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
196 // Measaure the old text.
197 int Size = Rewrite.getRangeSize(SrcRange);
198 if (Size == -1) {
199 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
200 << Old->getSourceRange();
201 return;
202 }
203 // Get the new text.
204 std::string SStr;
205 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000206 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000207 const std::string &Str = S.str();
208
209 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000210 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000211 ReplacedNodes[Old] = New;
212 return;
213 }
214 if (SilenceRewriteMacroWarning)
215 return;
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 }
219
Benjamin Kramerd999b372010-02-14 14:14:16 +0000220 void InsertText(SourceLocation Loc, llvm::StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000221 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000222 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000223 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000224 SilenceRewriteMacroWarning)
225 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000227 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattneraadaf782008-01-31 19:51:04 +0000230 void RemoveText(SourceLocation Loc, unsigned StrLen) {
231 // If removal succeeded or warning disabled return with no warning.
232 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
233 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Chris Lattneraadaf782008-01-31 19:51:04 +0000235 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
236 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000237
Chris Lattneraadaf782008-01-31 19:51:04 +0000238 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Benjamin Kramerd999b372010-02-14 14:14:16 +0000239 llvm::StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000240 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000241 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 SilenceRewriteMacroWarning)
243 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattneraadaf782008-01-31 19:51:04 +0000245 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
246 }
Mike Stump1eb44332009-09-09 15:08:12 +0000247
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000249 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000250 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000251 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000252 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000253 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
254 ObjCImplementationDecl *IMD,
255 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000256 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000257 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000259 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
260 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000261 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
262 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
263 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
264 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000265 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000266 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000267 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000269 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000270 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000271 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000272 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000273 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000274 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000275 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Chris Lattnerf04da132007-10-24 17:06:59 +0000277 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000278 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000279 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Steve Naroff8599e7a2008-12-08 16:43:47 +0000281 Stmt *CurrentBody;
282 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Chris Lattnere64b7772007-10-24 16:57:36 +0000284 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000285 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
286 bool &replaced);
287 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000288 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000289 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000290 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000291 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000292 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000293 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000294 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000295 void WarnAboutReturnGotoStmts(Stmt *S);
296 void HasReturnStmts(Stmt *S, bool &hasReturns);
297 void RewriteTryReturnStmts(Stmt *S);
298 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000299 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000300 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000301 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
302 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
303 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000304 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
305 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000306 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000307 Expr **args, unsigned nargs,
308 SourceLocation StartLoc=SourceLocation(),
309 SourceLocation EndLoc=SourceLocation());
310 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
311 SourceLocation StartLoc=SourceLocation(),
312 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000315 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Steve Naroff09b266e2007-10-30 23:14:51 +0000317 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000318 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000319 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000320 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000321 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000322 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000323 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000324 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000325 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Chris Lattnerf04da132007-10-24 17:06:59 +0000327 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000328 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000329 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000331 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000332 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Douglas Gregor653f1b12009-04-23 01:02:12 +0000334 template<typename MethodIterator>
335 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
336 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000337 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000338 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000339 const char *ClassName,
340 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Steve Naroff621edce2009-04-29 16:37:50 +0000342 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
343 const char *prefix,
344 const char *ClassName,
345 std::string &Result);
346 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000347 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000348 const char *ClassName,
349 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000350 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000351 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000352 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
353 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000354 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000355 void RewriteImplementations();
356 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Steve Naroff54055232008-10-27 17:20:55 +0000358 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000359 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000360 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Steve Naroff54055232008-10-27 17:20:55 +0000362 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
363 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000364
365 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000366 void RewriteBlockCall(CallExpr *Exp);
367 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000368 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000369 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000370 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
373 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000374 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000376 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000377 std::string SynthesizeBlockImpl(BlockExpr *CE,
378 std::string Tag, std::string Desc);
379 std::string SynthesizeBlockDescriptor(std::string DescTag,
380 std::string ImplTag,
381 int i, const char *funcName,
382 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000383 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000384 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000385 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000386 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Steve Naroff54055232008-10-27 17:20:55 +0000388 void CollectBlockDeclRefInfo(BlockExpr *Exp);
389 void GetBlockCallExprs(Stmt *S);
390 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000391 void GetInnerBlockDeclRefExprs(Stmt *S,
392 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
393 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls);
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 // We avoid calling Type::isBlockPointerType(), since it operates on the
396 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000397 bool isTopLevelBlockPointerType(QualType T) {
398 return isa<BlockPointerType>(T);
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Steve Naroff54055232008-10-27 17:20:55 +0000401 // FIXME: This predicate seems like it would be useful to add to ASTContext.
402 bool isObjCType(QualType T) {
403 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Steve Naroff54055232008-10-27 17:20:55 +0000406 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Steve Naroff54055232008-10-27 17:20:55 +0000408 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
409 OCT == Context->getCanonicalType(Context->getObjCClassType()))
410 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Ted Kremenek6217b802009-07-29 21:53:49 +0000412 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000413 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000414 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000415 return true;
416 }
417 return false;
418 }
419 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000420 void GetExtentOfArgList(const char *Name, const char *&LParen,
421 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000422 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Steve Narofffa15fd92008-10-28 20:29:00 +0000424 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000425 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
426 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Steve Naroff621edce2009-04-29 16:37:50 +0000428 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000430 if (From[i] == '"')
431 To += "\\\"";
432 else
433 To += From[i];
434 }
435 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000436 };
John McCall9d125032010-01-15 18:39:57 +0000437
438 // Helper function: create a CStyleCastExpr with trivial type source info.
439 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
440 CastExpr::CastKind Kind, Expr *E) {
441 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
442 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
443 SourceLocation(), SourceLocation());
444 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000445}
446
Mike Stump1eb44332009-09-09 15:08:12 +0000447void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
448 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000449 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000450 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000451 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000452 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000453 // All the args are checked/rewritten. Don't call twice!
454 RewriteBlockPointerDecl(D);
455 break;
456 }
457 }
458}
459
460void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000461 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000462 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000463 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000464}
465
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000466static bool IsHeaderFile(const std::string &Filename) {
467 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000469 if (DotPos == std::string::npos) {
470 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000471 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000472 }
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000474 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
475 // C header: .h
476 // C++ header: .hh or .H;
477 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000478}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000479
Eli Friedman66d6f042009-05-18 22:20:00 +0000480RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000481 Diagnostic &D, const LangOptions &LOpts,
482 bool silenceMacroWarn)
483 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
484 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000485 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000486 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000487 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000488 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000489 "rewriter doesn't support user-specified control flow semantics "
490 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000491}
492
Eli Friedmanbce831b2009-05-18 22:29:17 +0000493ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
494 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000495 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000496 const LangOptions &LOpts,
497 bool SilenceRewriteMacroWarning) {
498 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000499}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000500
Steve Naroffb29b4272008-04-14 22:03:09 +0000501void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000502 Context = &context;
503 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000504 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000505 MsgSendFunctionDecl = 0;
506 MsgSendSuperFunctionDecl = 0;
507 MsgSendStretFunctionDecl = 0;
508 MsgSendSuperStretFunctionDecl = 0;
509 MsgSendFpretFunctionDecl = 0;
510 GetClassFunctionDecl = 0;
511 GetMetaClassFunctionDecl = 0;
512 SelGetUidFunctionDecl = 0;
513 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000514 ConstantStringClassReference = 0;
515 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000516 CurMethodDef = 0;
517 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000518 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000519 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000520 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000521 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000522 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000523 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000524 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000525 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000526 PropParentMap = 0;
527 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000528 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000529 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000531 // Get the ID and start/end of the main file.
532 MainFileID = SM->getMainFileID();
533 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
534 MainFileStart = MainBuf->getBufferStart();
535 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner2c78b872009-04-14 23:22:57 +0000537 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 // declaring objc_selector outside the parameter list removes a silly
540 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000542 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000543 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000544 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000545 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000546 if (LangOpts.Microsoft) {
547 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000548 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
549 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000550 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000551 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000552 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
554 Preamble += "typedef struct objc_object Protocol;\n";
555 Preamble += "#define _REWRITER_typedef_Protocol\n";
556 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000557 if (LangOpts.Microsoft) {
558 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
559 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
560 } else
561 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
562 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000565 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000566 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000567 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000568 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000569 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000570 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000571 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000572 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000573 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000574 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000575 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000576 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
577 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
578 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
579 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
580 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000581 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000582 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000583 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
584 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
585 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000586 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
587 Preamble += "struct __objcFastEnumerationState {\n\t";
588 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000589 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "unsigned long *mutationsPtr;\n\t";
591 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000592 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "#define __FASTENUMERATIONSTATE\n";
594 Preamble += "#endif\n";
595 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
596 Preamble += "struct __NSConstantStringImpl {\n";
597 Preamble += " int *isa;\n";
598 Preamble += " int flags;\n";
599 Preamble += " char *str;\n";
600 Preamble += " long length;\n";
601 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000602 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
603 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
604 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000606 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
608 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000609 // Blocks preamble.
610 Preamble += "#ifndef BLOCK_IMPL\n";
611 Preamble += "#define BLOCK_IMPL\n";
612 Preamble += "struct __block_impl {\n";
613 Preamble += " void *isa;\n";
614 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000615 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000616 Preamble += " void *FuncPtr;\n";
617 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000618 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000619 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000620 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
621 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
622 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
623 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
624 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000625 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000627 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
628 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
629 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000630 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000631 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
633 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000634 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000635 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000636 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000637 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000638 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000639 Preamble += "#define __weak\n";
640 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000641}
642
643
Chris Lattnerf04da132007-10-24 17:06:59 +0000644//===----------------------------------------------------------------------===//
645// Top Level Driver Code
646//===----------------------------------------------------------------------===//
647
Chris Lattner682bf922009-03-29 16:50:03 +0000648void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000649 if (Diags.hasErrorOccurred())
650 return;
651
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000652 // Two cases: either the decl could be in the main file, or it could be in a
653 // #included file. If the former, rewrite it now. If the later, check to see
654 // if we rewrote the #include/#import.
655 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000656 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000658 // If this is for a builtin, ignore it.
659 if (Loc.isInvalid()) return;
660
Steve Naroffebf2b562007-10-23 23:50:29 +0000661 // Look for built-in declarations that we need to refer during the rewrite.
662 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000663 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000664 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000665 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000666 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000667 ConstantStringClassReference = FVD;
668 return;
669 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000670 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000671 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000672 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000673 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000674 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000675 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000676 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000677 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000678 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000679 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
680 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000681 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
682 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000683 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000684 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000685 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000686 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000687 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000688 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000689}
690
Chris Lattnerf04da132007-10-24 17:06:59 +0000691//===----------------------------------------------------------------------===//
692// Syntactic (non-AST) Rewriting Code
693//===----------------------------------------------------------------------===//
694
Steve Naroffb29b4272008-04-14 22:03:09 +0000695void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000696 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000697 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
698 const char *MainBufStart = MainBuf.first;
699 const char *MainBufEnd = MainBuf.second;
700 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000702 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000703 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
704 if (*BufPtr == '#') {
705 if (++BufPtr == MainBufEnd)
706 return;
707 while (*BufPtr == ' ' || *BufPtr == '\t')
708 if (++BufPtr == MainBufEnd)
709 return;
710 if (!strncmp(BufPtr, "import", ImportLen)) {
711 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000712 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000713 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000714 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000715 BufPtr += ImportLen;
716 }
717 }
718 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000719}
720
Steve Naroffb29b4272008-04-14 22:03:09 +0000721void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
723 const char *MainBufStart = MainBuf.first;
724 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 // Loop over the whole file, looking for tabs.
727 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
728 if (*BufPtr != '\t')
729 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Chris Lattnerf04da132007-10-24 17:06:59 +0000731 // Okay, we found a tab. This tab will turn into at least one character,
732 // but it depends on which 'virtual column' it is in. Compute that now.
733 unsigned VCol = 0;
734 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
735 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
736 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattnerf04da132007-10-24 17:06:59 +0000738 // Okay, now that we know the virtual column, we know how many spaces to
739 // insert. We assume 8-character tab-stops.
740 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Chris Lattnerf04da132007-10-24 17:06:59 +0000742 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000743 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
744 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattnerf04da132007-10-24 17:06:59 +0000746 // Rewrite the single tab character into a sequence of spaces.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000747 ReplaceText(TabLoc, 1, llvm::StringRef(" ", Spaces));
Chris Lattnerf04da132007-10-24 17:06:59 +0000748 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000749}
750
Steve Naroffeb0646c2008-12-02 15:48:25 +0000751static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
752 ObjCIvarDecl *OID) {
753 std::string S;
754 S = "((struct ";
755 S += ClassDecl->getIdentifier()->getName();
756 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000757 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758 return S;
759}
760
Steve Naroffa0876e82008-12-02 17:36:43 +0000761void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
762 ObjCImplementationDecl *IMD,
763 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000764 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000765 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000766 const char *startBuf = SM->getCharacterData(startLoc);
767 assert((*startBuf == '@') && "bogus @synthesize location");
768 const char *semiBuf = strchr(startBuf, ';');
769 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000770 SourceLocation onePastSemiLoc =
771 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000772
773 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
774 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Steve Naroffeb0646c2008-12-02 15:48:25 +0000776 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000777 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000778 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000781 if (!OID)
782 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000784 std::string Getr;
785 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
786 Getr += "{ ";
787 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000788 // FIXME: deal with code generation implications for various property
789 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000790 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 Getr += "return " + getIvarAccessString(ClassDecl, OID);
792 Getr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000793 InsertText(onePastSemiLoc, Getr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 if (PD->isReadOnly())
795 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000796
Steve Naroffeb0646c2008-12-02 15:48:25 +0000797 // Generate the 'setter' function.
798 std::string Setr;
799 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000800 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000801 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000802 // FIXME: deal with code generation implications for various property
803 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000804 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000805 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000806 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000807 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000808 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000809}
Chris Lattner8a12c272007-10-11 18:38:32 +0000810
Steve Naroffb29b4272008-04-14 22:03:09 +0000811void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000812 // Get the start location and compute the semi location.
813 SourceLocation startLoc = ClassDecl->getLocation();
814 const char *startBuf = SM->getCharacterData(startLoc);
815 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattnerf04da132007-10-24 17:06:59 +0000817 // Translate to typedef's that forward reference structs with the same name
818 // as the class. As a convenience, we include the original declaration
819 // as a comment.
820 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000821 typedefString += "// @class ";
822 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
823 I != E; ++I) {
824 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
825 typedefString += ForwardDecl->getNameAsString();
826 if (I+1 != E)
827 typedefString += ", ";
828 else
829 typedefString += ";\n";
830 }
831
Chris Lattner67956052009-02-20 18:04:31 +0000832 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
833 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000834 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000835 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000836 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000837 typedefString += "\n";
838 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000839 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000840 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000841 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000842 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000843 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Steve Naroff934f2762007-10-24 22:48:43 +0000846 // Replace the @class with typedefs corresponding to the classes.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000847 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000848}
849
Steve Naroffb29b4272008-04-14 22:03:09 +0000850void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000851 // When method is a synthesized one, such as a getter/setter there is
852 // nothing to rewrite.
853 if (Method->isSynthesized())
854 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000855 SourceLocation LocStart = Method->getLocStart();
856 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000857
Chris Lattner30fc9332009-02-04 01:06:56 +0000858 if (SM->getInstantiationLineNumber(LocEnd) >
859 SM->getInstantiationLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000860 InsertText(LocStart, "#if 0\n");
861 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000862 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000863 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000864 }
865}
866
Mike Stump1eb44332009-09-09 15:08:12 +0000867void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000868 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Benjamin Kramerd999b372010-02-14 14:14:16 +0000870 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000871 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000872}
873
Steve Naroffb29b4272008-04-14 22:03:09 +0000874void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000875 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Steve Naroff423cb562007-10-30 13:30:57 +0000877 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000878 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000880 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
881 E = CatDecl->prop_end(); I != E; ++I)
882 RewriteProperty(*I);
883
Mike Stump1eb44332009-09-09 15:08:12 +0000884 for (ObjCCategoryDecl::instmeth_iterator
885 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000886 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000887 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000888 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000889 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000890 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000891 RewriteMethodDeclaration(*I);
892
Steve Naroff423cb562007-10-30 13:30:57 +0000893 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000894 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000895}
896
Steve Naroffb29b4272008-04-14 22:03:09 +0000897void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000898 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Steve Naroff752d6ef2007-10-30 16:42:30 +0000900 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Steve Naroff752d6ef2007-10-30 16:42:30 +0000902 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000903 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000904
905 for (ObjCProtocolDecl::instmeth_iterator
906 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000907 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000908 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000909 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000910 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000911 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000912 RewriteMethodDeclaration(*I);
913
Steve Naroff752d6ef2007-10-30 16:42:30 +0000914 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000915 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000916 ReplaceText(LocEnd, 0, "// ");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000917
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000918 // Must comment out @optional/@required
919 const char *startBuf = SM->getCharacterData(LocStart);
920 const char *endBuf = SM->getCharacterData(LocEnd);
921 for (const char *p = startBuf; p < endBuf; p++) {
922 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000923 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000924 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000926 }
927 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +0000928 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000929 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000931 }
932 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000933}
934
Steve Naroffb29b4272008-04-14 22:03:09 +0000935void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000936 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000937 if (LocStart.isInvalid())
938 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000939 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000940 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000941}
942
Mike Stump1eb44332009-09-09 15:08:12 +0000943void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000944 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000945 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000946 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000947 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000948 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000949 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000950 else if (OMD->getResultType()->isFunctionPointerType() ||
951 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000952 // needs special handling, since pointer-to-functions have special
953 // syntax (where a decaration models use).
954 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000955 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000956 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000957 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000958 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000959 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000960 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000961 ResultStr += FPRetType->getResultType().getAsString();
962 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000963 }
964 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000965 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000966 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000968 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000969 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000971 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000972 NameStr += "_I_";
973 else
974 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000976 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000977 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000978
979 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000980 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000981 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000982 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000985 {
986 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000987 int len = selString.size();
988 for (int i = 0; i < len; i++)
989 if (selString[i] == ':')
990 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000991 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000992 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000993 // Remember this name for metadata emission
994 MethodInternalNames[OMD] = NameStr;
995 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 // Rewrite arguments
998 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001000 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001001 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001002 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001003 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001004 if (!LangOpts.Microsoft) {
1005 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
1006 ResultStr += "struct ";
1007 }
1008 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001009 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001010 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001011 }
1012 else
Steve Naroff621edce2009-04-29 16:37:50 +00001013 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001015 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001016 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001017 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001019 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001020 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1021 E = OMD->param_end(); PI != E; ++PI) {
1022 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001023 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001024 if (PDecl->getType()->isObjCQualifiedIdType()) {
1025 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001026 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001027 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001028 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001029 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001030 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001031 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001032 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1033 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001034 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001035 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001036 ResultStr += Name;
1037 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001038 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001039 if (OMD->isVariadic())
1040 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001041 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Steve Naroff76e429d2008-07-16 14:40:40 +00001043 if (FPRetType) {
1044 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Steve Naroff76e429d2008-07-16 14:40:40 +00001046 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001047 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001048 ResultStr += "(";
1049 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1050 if (i) ResultStr += ", ";
1051 std::string ParamStr = FT->getArgType(i).getAsString();
1052 ResultStr += ParamStr;
1053 }
1054 if (FT->isVariadic()) {
1055 if (FT->getNumArgs()) ResultStr += ", ";
1056 ResultStr += "...";
1057 }
1058 ResultStr += ")";
1059 } else {
1060 ResultStr += "()";
1061 }
1062 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001063}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001064void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001065 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1066 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001068 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001070 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001071 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1072 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001073 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001075 ObjCMethodDecl *OMD = *I;
1076 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001077 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001078 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001079
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 const char *startBuf = SM->getCharacterData(LocStart);
1081 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001082 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 }
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001085 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001086 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1087 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001088 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001089 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090 ObjCMethodDecl *OMD = *I;
1091 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001092 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001093 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001095 const char *startBuf = SM->getCharacterData(LocStart);
1096 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001097 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001099 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001100 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001101 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001102 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001103 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001104 }
1105
Benjamin Kramerd999b372010-02-14 14:14:16 +00001106 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107}
1108
Steve Naroffb29b4272008-04-14 22:03:09 +00001109void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001110 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001111 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001112 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001113 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001114 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001115 ResultStr += "\n";
1116 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001117 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001118 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001119 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001121 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001122 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001123 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001124 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001125 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001126
1127 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001128 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001129 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001130 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001131 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001132 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001133 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001134 for (ObjCInterfaceDecl::classmeth_iterator
1135 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001136 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001137 RewriteMethodDeclaration(*I);
1138
Steve Naroff2feac5e2007-10-30 03:43:13 +00001139 // Lastly, comment out the @end.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001140 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ");
Steve Naroffbef11852007-10-26 20:53:56 +00001141}
1142
Steve Naroffb619d952008-12-09 12:56:34 +00001143Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1144 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001145 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1146 // This allows us to reuse all the fun and games in SynthMessageExpr().
1147 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1148 ObjCMessageExpr *MsgExpr;
1149 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1150 llvm::SmallVector<Expr *, 1> ExprVec;
1151 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Steve Naroff8599e7a2008-12-08 16:43:47 +00001153 Stmt *Receiver = PropRefExpr->getBase();
1154 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1155 if (PRE && PropGetters[PRE]) {
1156 // This allows us to handle chain/nested property getters.
1157 Receiver = PropGetters[PRE];
1158 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001159 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001160 PDecl->getSetterName(), PDecl->getType(),
1161 PDecl->getSetterMethodDecl(),
1162 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001163 &ExprVec[0], 1);
1164 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Steve Naroffc77a6362008-12-04 16:24:46 +00001166 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001167 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001168 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001169 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1170 // to things that stay around.
1171 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001172 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001173}
1174
Steve Naroffc77a6362008-12-04 16:24:46 +00001175Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001176 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1177 // This allows us to reuse all the fun and games in SynthMessageExpr().
1178 ObjCMessageExpr *MsgExpr;
1179 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Steve Naroff8599e7a2008-12-08 16:43:47 +00001181 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Steve Naroff8599e7a2008-12-08 16:43:47 +00001183 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1184 if (PRE && PropGetters[PRE]) {
1185 // This allows us to handle chain/nested property getters.
1186 Receiver = PropGetters[PRE];
1187 }
Ted Kremenekeb3b3242010-02-11 22:41:21 +00001188 MsgExpr = new (Context) ObjCMessageExpr(*Context, dyn_cast<Expr>(Receiver),
Mike Stump1eb44332009-09-09 15:08:12 +00001189 PDecl->getGetterName(), PDecl->getType(),
1190 PDecl->getGetterMethodDecl(),
1191 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001192 0, 0);
1193
Steve Naroff4c3580e2008-12-04 23:50:32 +00001194 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001195
1196 if (!PropParentMap)
1197 PropParentMap = new ParentMap(CurrentBody);
1198
1199 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1200 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1201 // We stash away the ReplacingStmt since actually doing the
1202 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1203 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001204 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1205 // to things that stay around.
1206 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001207 return PropRefExpr; // return the original...
1208 } else {
1209 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001210 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001211 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1212 // to things that stay around.
1213 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001214 return ReplacingStmt;
1215 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001216}
1217
Mike Stump1eb44332009-09-09 15:08:12 +00001218Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001219 SourceLocation OrigStart,
1220 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001222 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001223 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001224 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001225 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001226 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001227 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001228 // lookup which class implements the instance variable.
1229 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001230 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001231 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001232 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Steve Narofff0757612008-05-08 17:52:16 +00001234 // Synthesize an explicit cast to gain access to the ivar.
1235 std::string RecName = clsDeclared->getIdentifier()->getName();
1236 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001238 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001239 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001240 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1241 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001242 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1243 CastExpr::CK_Unknown,
1244 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001245 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001246 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1247 IV->getBase()->getLocEnd(),
1248 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001249 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001250 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001251 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001252 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1253 IV->getLocation(),
1254 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001255 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001256 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001257 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001258 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001259 // Cannot delete IV->getBase(), since PE points to it.
1260 // Replace the old base with the cast. This is important when doing
1261 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001262 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001263 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001264 }
Steve Naroff84472a82008-04-18 21:55:08 +00001265 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001266 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Steve Naroff9f525972008-05-06 23:20:07 +00001268 // Explicit ivar refs need to have a cast inserted.
1269 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001270 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001271 ObjCInterfaceType *iFaceDecl =
1272 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001273 // lookup which class implements the instance variable.
1274 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001275 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001276 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001277 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Steve Naroff9f525972008-05-06 23:20:07 +00001279 // Synthesize an explicit cast to gain access to the ivar.
1280 std::string RecName = clsDeclared->getIdentifier()->getName();
1281 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001282 IdentifierInfo *II = &Context->Idents.get(RecName);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001283 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001284 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001285 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1286 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001287 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1288 CastExpr::CK_Unknown,
1289 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001290 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001291 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001292 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001293 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001294 // Cannot delete IV->getBase(), since PE points to it.
1295 // Replace the old base with the cast. This is important when doing
1296 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001297 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001298 return IV;
1299 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001300 }
Steve Naroff84472a82008-04-18 21:55:08 +00001301 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001302}
1303
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001304Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1305 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1306 CI != E; ++CI) {
1307 if (*CI) {
1308 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1309 if (newStmt)
1310 *CI = newStmt;
1311 }
1312 }
1313 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1314 SourceRange OrigStmtRange = S->getSourceRange();
1315 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1316 replaced);
1317 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001318 }
1319 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1320 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1321 return newStmt;
1322 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001323 return S;
1324}
1325
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001326/// SynthCountByEnumWithState - To print:
1327/// ((unsigned int (*)
1328/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001329/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001330/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001331/// "countByEnumeratingWithState:objects:count:"),
1332/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001333/// (id *)items, (unsigned int)16)
1334///
Steve Naroffb29b4272008-04-14 22:03:09 +00001335void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001336 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1337 "id *, unsigned int))(void *)objc_msgSend)";
1338 buf += "\n\t\t";
1339 buf += "((id)l_collection,\n\t\t";
1340 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1341 buf += "\n\t\t";
1342 buf += "&enumState, "
1343 "(id *)items, (unsigned int)16)";
1344}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001345
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001346/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1347/// statement to exit to its outer synthesized loop.
1348///
Steve Naroffb29b4272008-04-14 22:03:09 +00001349Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001350 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1351 return S;
1352 // replace break with goto __break_label
1353 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001355 SourceLocation startLoc = S->getLocStart();
1356 buf = "goto __break_label_";
1357 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001358 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001359
1360 return 0;
1361}
1362
1363/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1364/// statement to continue with its inner synthesized loop.
1365///
Steve Naroffb29b4272008-04-14 22:03:09 +00001366Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001367 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1368 return S;
1369 // replace continue with goto __continue_label
1370 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001372 SourceLocation startLoc = S->getLocStart();
1373 buf = "goto __continue_label_";
1374 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001375 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001377 return 0;
1378}
1379
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001380/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001381/// It rewrites:
1382/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001384/// Into:
1385/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001386/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001387/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001388/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001390/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001391/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001392/// if (limit) {
1393/// unsigned long startMutations = *enumState.mutationsPtr;
1394/// do {
1395/// unsigned long counter = 0;
1396/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001397/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001398/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001399/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001400/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001401/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001402/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001403/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001404/// objects:items count:16]);
1405/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001406/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001407/// }
1408/// else
1409/// elem = nil;
1410/// }
1411///
Steve Naroffb29b4272008-04-14 22:03:09 +00001412Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001413 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001414 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001415 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001416 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001417 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001418 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001420 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001421 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001423 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001424 std::string buf;
1425 buf = "\n{\n\t";
1426 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1427 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001428 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001429 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001430 if (ElementType->isObjCQualifiedIdType() ||
1431 ElementType->isObjCQualifiedInterfaceType())
1432 // Simply use 'id' for all qualified types.
1433 elementTypeAsString = "id";
1434 else
1435 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001436 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001437 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001438 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001439 buf += elementName;
1440 buf += ";\n\t";
1441 }
Chris Lattner06767512008-04-08 05:52:18 +00001442 else {
1443 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001444 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001445 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1446 if (VD->getType()->isObjCQualifiedIdType() ||
1447 VD->getType()->isObjCQualifiedInterfaceType())
1448 // Simply use 'id' for all qualified types.
1449 elementTypeAsString = "id";
1450 else
1451 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001452 }
Mike Stump1eb44332009-09-09 15:08:12 +00001453
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454 // struct __objcFastEnumerationState enumState = { 0 };
1455 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1456 // id items[16];
1457 buf += "id items[16];\n\t";
1458 // id l_collection = (id)
1459 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001460 // Find start location of 'collection' the hard way!
1461 const char *startCollectionBuf = startBuf;
1462 startCollectionBuf += 3; // skip 'for'
1463 startCollectionBuf = strchr(startCollectionBuf, '(');
1464 startCollectionBuf++; // skip '('
1465 // find 'in' and skip it.
1466 while (*startCollectionBuf != ' ' ||
1467 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1468 (*(startCollectionBuf+3) != ' ' &&
1469 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1470 startCollectionBuf++;
1471 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001472
1473 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001474 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001475 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001476 SourceLocation rightParenLoc = S->getRParenLoc();
1477 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1478 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1482 // objects:items count:16];
1483 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001484 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001485 // ((unsigned int (*)
1486 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001487 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001488 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001489 // "countByEnumeratingWithState:objects:count:"),
1490 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001491 // (id *)items, (unsigned int)16);
1492 buf += "unsigned long limit =\n\t\t";
1493 SynthCountByEnumWithState(buf);
1494 buf += ";\n\t";
1495 /// if (limit) {
1496 /// unsigned long startMutations = *enumState.mutationsPtr;
1497 /// do {
1498 /// unsigned long counter = 0;
1499 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001500 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001501 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001502 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001503 buf += "if (limit) {\n\t";
1504 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1505 buf += "do {\n\t\t";
1506 buf += "unsigned long counter = 0;\n\t\t";
1507 buf += "do {\n\t\t\t";
1508 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1509 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1510 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001511 buf += " = (";
1512 buf += elementTypeAsString;
1513 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001515 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001517 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001518 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001519 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001520 /// objects:items count:16]);
1521 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001522 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 /// }
1524 /// else
1525 /// elem = nil;
1526 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001527 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001528 buf = ";\n\t";
1529 buf += "__continue_label_";
1530 buf += utostr(ObjCBcLabelNo.back());
1531 buf += ": ;";
1532 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001533 buf += "} while (counter < limit);\n\t";
1534 buf += "} while (limit = ";
1535 SynthCountByEnumWithState(buf);
1536 buf += ");\n\t";
1537 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001538 buf += " = ((";
1539 buf += elementTypeAsString;
1540 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001541 buf += "__break_label_";
1542 buf += utostr(ObjCBcLabelNo.back());
1543 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001544 buf += "}\n\t";
1545 buf += "else\n\t\t";
1546 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001547 buf += " = ((";
1548 buf += elementTypeAsString;
1549 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001550 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001552 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001553 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001554 if (isa<CompoundStmt>(S->getBody())) {
1555 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001556 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001557 } else {
1558 /* Need to treat single statements specially. For example:
1559 *
1560 * for (A *a in b) if (stuff()) break;
1561 * for (A *a in b) xxxyy;
1562 *
1563 * The following code simply scans ahead to the semi to find the actual end.
1564 */
1565 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1566 const char *semiBuf = strchr(stmtBuf, ';');
1567 assert(semiBuf && "Can't find ';'");
1568 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001569 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001570 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001571 Stmts.pop_back();
1572 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001573 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001574}
1575
Mike Stump1eb44332009-09-09 15:08:12 +00001576/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001577/// This routine rewrites @synchronized(expr) stmt;
1578/// into:
1579/// objc_sync_enter(expr);
1580/// @try stmt @finally { objc_sync_exit(expr); }
1581///
Steve Naroffb29b4272008-04-14 22:03:09 +00001582Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001583 // Get the start location and compute the semi location.
1584 SourceLocation startLoc = S->getLocStart();
1585 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001586
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001587 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001588
1589 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001590 buf = "objc_sync_enter((id)";
1591 const char *lparenBuf = startBuf;
1592 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001593 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001594 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1595 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001596 // been rewritten! (which implies the SourceLocation's are invalid).
1597 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001598 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001599 while (*endBuf != ')') endBuf--;
1600 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001601 buf = ");\n";
1602 // declare a new scope with two variables, _stack and _rethrow.
1603 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1604 buf += "int buf[18/*32-bit i386*/];\n";
1605 buf += "char *pointers[4];} _stack;\n";
1606 buf += "id volatile _rethrow = 0;\n";
1607 buf += "objc_exception_try_enter(&_stack);\n";
1608 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001609 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001610 startLoc = S->getSynchBody()->getLocEnd();
1611 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Steve Naroffc7089f12008-08-19 13:04:19 +00001613 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001614 SourceLocation lastCurlyLoc = startLoc;
1615 buf = "}\nelse {\n";
1616 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001617 buf += "}\n";
1618 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001619 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001620
1621 std::string syncBuf;
1622 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001623 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1624 CastExpr::CK_Unknown,
1625 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001626 std::string syncExprBufS;
1627 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001628 syncExpr->printPretty(syncExprBuf, *Context, 0,
1629 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001630 syncBuf += syncExprBuf.str();
1631 syncBuf += ");";
1632
1633 buf += syncBuf;
1634 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001635 buf += "}\n";
1636 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Benjamin Kramerd999b372010-02-14 14:14:16 +00001638 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001639
1640 bool hasReturns = false;
1641 HasReturnStmts(S->getSynchBody(), hasReturns);
1642 if (hasReturns)
1643 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1644
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001645 return 0;
1646}
1647
Steve Naroffb85e77a2009-12-05 21:43:12 +00001648void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1649{
Steve Naroff8c565152008-12-05 17:03:39 +00001650 // Perform a bottom up traversal of all children.
1651 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1652 CI != E; ++CI)
1653 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001654 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001655
Steve Naroffb85e77a2009-12-05 21:43:12 +00001656 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001657 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001658 TryFinallyContainsReturnDiag);
1659 }
1660 return;
1661}
1662
Steve Naroffb85e77a2009-12-05 21:43:12 +00001663void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1664{
1665 // Perform a bottom up traversal of all children.
1666 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1667 CI != E; ++CI)
1668 if (*CI)
1669 HasReturnStmts(*CI, hasReturns);
1670
1671 if (isa<ReturnStmt>(S))
1672 hasReturns = true;
1673 return;
1674}
1675
1676void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1677 // Perform a bottom up traversal of all children.
1678 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1679 CI != E; ++CI)
1680 if (*CI) {
1681 RewriteTryReturnStmts(*CI);
1682 }
1683 if (isa<ReturnStmt>(S)) {
1684 SourceLocation startLoc = S->getLocStart();
1685 const char *startBuf = SM->getCharacterData(startLoc);
1686
1687 const char *semiBuf = strchr(startBuf, ';');
1688 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1689 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1690
1691 std::string buf;
1692 buf = "{ objc_exception_try_exit(&_stack); return";
1693
Benjamin Kramerd999b372010-02-14 14:14:16 +00001694 ReplaceText(startLoc, 6, buf);
1695 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001696 }
1697 return;
1698}
1699
1700void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1701 // Perform a bottom up traversal of all children.
1702 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1703 CI != E; ++CI)
1704 if (*CI) {
1705 RewriteSyncReturnStmts(*CI, syncExitBuf);
1706 }
1707 if (isa<ReturnStmt>(S)) {
1708 SourceLocation startLoc = S->getLocStart();
1709 const char *startBuf = SM->getCharacterData(startLoc);
1710
1711 const char *semiBuf = strchr(startBuf, ';');
1712 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1713 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1714
1715 std::string buf;
1716 buf = "{ objc_exception_try_exit(&_stack);";
1717 buf += syncExitBuf;
1718 buf += " return";
1719
Benjamin Kramerd999b372010-02-14 14:14:16 +00001720 ReplaceText(startLoc, 6, buf);
1721 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001722 }
1723 return;
1724}
1725
Steve Naroffb29b4272008-04-14 22:03:09 +00001726Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001727 // Get the start location and compute the semi location.
1728 SourceLocation startLoc = S->getLocStart();
1729 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Steve Naroff75730982007-11-07 04:08:17 +00001731 assert((*startBuf == '@') && "bogus @try location");
1732
1733 std::string buf;
1734 // declare a new scope with two variables, _stack and _rethrow.
1735 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1736 buf += "int buf[18/*32-bit i386*/];\n";
1737 buf += "char *pointers[4];} _stack;\n";
1738 buf += "id volatile _rethrow = 0;\n";
1739 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001740 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001741
Benjamin Kramerd999b372010-02-14 14:14:16 +00001742 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Steve Naroff75730982007-11-07 04:08:17 +00001744 startLoc = S->getTryBody()->getLocEnd();
1745 startBuf = SM->getCharacterData(startLoc);
1746
1747 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001748
Steve Naroff75730982007-11-07 04:08:17 +00001749 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001750 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1751 if (catchList) {
1752 startLoc = startLoc.getFileLocWithOffset(1);
1753 buf = " /* @catch begin */ else {\n";
1754 buf += " id _caught = objc_exception_extract(&_stack);\n";
1755 buf += " objc_exception_try_enter (&_stack);\n";
1756 buf += " if (_setjmp(_stack.buf))\n";
1757 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1758 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001759
Benjamin Kramerd999b372010-02-14 14:14:16 +00001760 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001761 } else { /* no catch list */
1762 buf = "}\nelse {\n";
1763 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1764 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001765 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001766 }
Steve Naroff75730982007-11-07 04:08:17 +00001767 bool sawIdTypedCatch = false;
1768 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001769 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001770 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001771
Mike Stump1eb44332009-09-09 15:08:12 +00001772 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001773 buf = "if ("; // we are generating code for the first catch clause
1774 else
1775 buf = "else if (";
1776 startLoc = catchList->getLocStart();
1777 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Steve Naroff75730982007-11-07 04:08:17 +00001779 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Steve Naroff75730982007-11-07 04:08:17 +00001781 const char *lParenLoc = strchr(startBuf, '(');
1782
Steve Naroffbe4b3332008-02-01 22:08:12 +00001783 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001784 // Now rewrite the body...
1785 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001786 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1787 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001788 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1789 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001790 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Steve Naroffe12e6922008-02-01 20:02:07 +00001792 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001793 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001794 } else if (catchDecl) {
1795 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001796 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001797 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001798 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001799 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001800 } else if (t->isObjCObjectPointerType()) {
1801 QualType InterfaceTy = t->getPointeeType();
1802 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1803 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001804 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001805 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001806 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001807 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001809 }
1810 }
1811 // Now rewrite the body...
1812 lastCatchBody = catchList->getCatchBody();
1813 SourceLocation rParenLoc = catchList->getRParenLoc();
1814 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1815 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1816 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1817 assert((*rParenBuf == ')') && "bogus @catch paren location");
1818 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Mike Stump1eb44332009-09-09 15:08:12 +00001820 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001821 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001822 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001823 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001824 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001825 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001826 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001827 catchList = catchList->getNextCatchStmt();
1828 }
1829 // Complete the catch list...
1830 if (lastCatchBody) {
1831 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001832 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1833 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff378f47a2008-09-11 15:29:03 +00001835 // Insert the last (implicit) else clause *before* the right curly brace.
1836 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1837 buf = "} /* last catch end */\n";
1838 buf += "else {\n";
1839 buf += " _rethrow = _caught;\n";
1840 buf += " objc_exception_try_exit(&_stack);\n";
1841 buf += "} } /* @catch end */\n";
1842 if (!S->getFinallyStmt())
1843 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001844 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Steve Naroff75730982007-11-07 04:08:17 +00001846 // Set lastCurlyLoc
1847 lastCurlyLoc = lastCatchBody->getLocEnd();
1848 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001849 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001850 startLoc = finalStmt->getLocStart();
1851 startBuf = SM->getCharacterData(startLoc);
1852 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Benjamin Kramerd999b372010-02-14 14:14:16 +00001854 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Steve Naroff75730982007-11-07 04:08:17 +00001856 Stmt *body = finalStmt->getFinallyBody();
1857 SourceLocation startLoc = body->getLocStart();
1858 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001859 assert(*SM->getCharacterData(startLoc) == '{' &&
1860 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001861 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001862 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001863
Steve Naroff75730982007-11-07 04:08:17 +00001864 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001865 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00001866 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001867 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Steve Naroff75730982007-11-07 04:08:17 +00001869 // Set lastCurlyLoc
1870 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Steve Naroff8c565152008-12-05 17:03:39 +00001872 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001873 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001874 } else { /* no finally clause - make sure we synthesize an implicit one */
1875 buf = "{ /* implicit finally clause */\n";
1876 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1877 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1878 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001879 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001880
1881 // Now check for any return/continue/go statements within the @try.
1882 // The implicit finally clause won't called if the @try contains any
1883 // jump statements.
1884 bool hasReturns = false;
1885 HasReturnStmts(S->getTryBody(), hasReturns);
1886 if (hasReturns)
1887 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001888 }
1889 // Now emit the final closing curly brace...
1890 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001891 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001892 return 0;
1893}
1894
Steve Naroffb29b4272008-04-14 22:03:09 +00001895Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001896 return 0;
1897}
1898
Steve Naroffb29b4272008-04-14 22:03:09 +00001899Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001900 return 0;
1901}
1902
Mike Stump1eb44332009-09-09 15:08:12 +00001903// This can't be done with ReplaceStmt(S, ThrowExpr), since
1904// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001905// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001906Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001907 // Get the start location and compute the semi location.
1908 SourceLocation startLoc = S->getLocStart();
1909 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Steve Naroff2bd03922007-11-07 15:32:26 +00001911 assert((*startBuf == '@') && "bogus @throw location");
1912
1913 std::string buf;
1914 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001915 if (S->getThrowExpr())
1916 buf = "objc_exception_throw(";
1917 else // add an implicit argument
1918 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001920 // handle "@ throw" correctly.
1921 const char *wBuf = strchr(startBuf, 'w');
1922 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001923 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001924
Steve Naroff2bd03922007-11-07 15:32:26 +00001925 const char *semiBuf = strchr(startBuf, ';');
1926 assert((*semiBuf == ';') && "@throw: can't find ';'");
1927 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001928 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001929 return 0;
1930}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001931
Steve Naroffb29b4272008-04-14 22:03:09 +00001932Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001933 // Create a new string expression.
1934 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001935 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001936 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001937 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1938 StrEncoding.length(), false,StrType,
1939 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001940 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001941
Chris Lattner07506182007-11-30 22:53:43 +00001942 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001943 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001944 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001945}
1946
Steve Naroffb29b4272008-04-14 22:03:09 +00001947Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001948 if (!SelGetUidFunctionDecl)
1949 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001950 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1951 // Create a call to sel_registerName("selName").
1952 llvm::SmallVector<Expr*, 8> SelExprs;
1953 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001954 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001955 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001956 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001957 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001958 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1959 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001960 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001961 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001962 return SelExp;
1963}
1964
Steve Naroffb29b4272008-04-14 22:03:09 +00001965CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00001966 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1967 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001968 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001969 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Steve Naroffebf2b562007-10-23 23:50:29 +00001971 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001972 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Steve Naroffebf2b562007-10-23 23:50:29 +00001974 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001975 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001976 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001977 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001978 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001979 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001980
John McCall183700f2009-09-21 23:43:11 +00001981 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00001983 CallExpr *Exp =
1984 new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1985 EndLoc);
1986 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00001987}
1988
Steve Naroffd5255f52007-11-01 13:24:47 +00001989static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1990 const char *&startRef, const char *&endRef) {
1991 while (startBuf < endBuf) {
1992 if (*startBuf == '<')
1993 startRef = startBuf; // mark the start.
1994 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001995 if (startRef && *startRef == '<') {
1996 endRef = startBuf; // mark the end.
1997 return true;
1998 }
1999 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002000 }
2001 startBuf++;
2002 }
2003 return false;
2004}
2005
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002006static void scanToNextArgument(const char *&argRef) {
2007 int angle = 0;
2008 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2009 if (*argRef == '<')
2010 angle++;
2011 else if (*argRef == '>')
2012 angle--;
2013 argRef++;
2014 }
2015 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2016}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002017
Steve Naroffb29b4272008-04-14 22:03:09 +00002018bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002019 if (T->isObjCQualifiedIdType())
2020 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002021 if (const PointerType *PT = T->getAs<PointerType>()) {
2022 if (PT->getPointeeType()->isObjCQualifiedIdType())
2023 return true;
2024 }
2025 if (T->isObjCObjectPointerType()) {
2026 T = T->getPointeeType();
2027 return T->isObjCQualifiedInterfaceType();
2028 }
2029 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002030}
2031
Steve Naroff4f95b752008-07-29 18:15:38 +00002032void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2033 QualType Type = E->getType();
2034 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002035 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Steve Naroffcda658e2008-11-19 21:15:47 +00002037 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2038 Loc = ECE->getLParenLoc();
2039 EndLoc = ECE->getRParenLoc();
2040 } else {
2041 Loc = E->getLocStart();
2042 EndLoc = E->getLocEnd();
2043 }
2044 // This will defend against trying to rewrite synthesized expressions.
2045 if (Loc.isInvalid() || EndLoc.isInvalid())
2046 return;
2047
Steve Naroff4f95b752008-07-29 18:15:38 +00002048 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002049 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002050 const char *startRef = 0, *endRef = 0;
2051 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2052 // Get the locations of the startRef, endRef.
2053 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2054 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2055 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002056 InsertText(LessLoc, "/*");
2057 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002058 }
2059 }
2060}
2061
Steve Naroffb29b4272008-04-14 22:03:09 +00002062void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002063 SourceLocation Loc;
2064 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002065 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002066 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2067 Loc = VD->getLocation();
2068 Type = VD->getType();
2069 }
2070 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2071 Loc = FD->getLocation();
2072 // Check for ObjC 'id' and class types that have been adorned with protocol
2073 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002074 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002075 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002076 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002077 if (!proto)
2078 return;
2079 Type = proto->getResultType();
2080 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002081 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2082 Loc = FD->getLocation();
2083 Type = FD->getType();
2084 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002085 else
2086 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002088 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002089 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002090
Steve Naroffd5255f52007-11-01 13:24:47 +00002091 const char *endBuf = SM->getCharacterData(Loc);
2092 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002093 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002094 startBuf--; // scan backward (from the decl location) for return type.
2095 const char *startRef = 0, *endRef = 0;
2096 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2097 // Get the locations of the startRef, endRef.
2098 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2099 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2100 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002101 InsertText(LessLoc, "/*");
2102 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002103 }
2104 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002105 if (!proto)
2106 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002107 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002108 const char *startBuf = SM->getCharacterData(Loc);
2109 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002110 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2111 if (needToScanForQualifiers(proto->getArgType(i))) {
2112 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Steve Naroffd5255f52007-11-01 13:24:47 +00002114 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002115 // scan forward (from the decl location) for argument types.
2116 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002117 const char *startRef = 0, *endRef = 0;
2118 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2119 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002120 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002121 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002122 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002123 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002124 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002125 InsertText(LessLoc, "/*");
2126 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002127 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002128 startBuf = ++endBuf;
2129 }
2130 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002131 // If the function name is derived from a macro expansion, then the
2132 // argument buffer will not follow the name. Need to speak with Chris.
2133 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002134 startBuf++; // scan forward (from the decl location) for argument types.
2135 startBuf++;
2136 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002137 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002138}
2139
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002140void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2141 QualType QT = ND->getType();
2142 const Type* TypePtr = QT->getAs<Type>();
2143 if (!isa<TypeOfExprType>(TypePtr))
2144 return;
2145 while (isa<TypeOfExprType>(TypePtr)) {
2146 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2147 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2148 TypePtr = QT->getAs<Type>();
2149 }
2150 // FIXME. This will not work for multiple declarators; as in:
2151 // __typeof__(a) b,c,d;
2152 std::string TypeAsString(QT.getAsString());
2153 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2154 const char *startBuf = SM->getCharacterData(DeclLoc);
2155 if (ND->getInit()) {
2156 std::string Name(ND->getNameAsString());
2157 TypeAsString += " " + Name + " = ";
2158 Expr *E = ND->getInit();
2159 SourceLocation startLoc;
2160 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2161 startLoc = ECE->getLParenLoc();
2162 else
2163 startLoc = E->getLocStart();
2164 startLoc = SM->getInstantiationLoc(startLoc);
2165 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002166 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002167 }
2168 else {
2169 SourceLocation X = ND->getLocEnd();
2170 X = SM->getInstantiationLoc(X);
2171 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002172 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002173 }
2174}
2175
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002176// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002177void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002178 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2179 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002180 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002181 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002182 &ArgTys[0], ArgTys.size(),
2183 false /*isVariadic*/, 0,
2184 false, false, 0, 0, false,
2185 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002186 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002187 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002188 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002189 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002190}
2191
Steve Naroffb29b4272008-04-14 22:03:09 +00002192void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002193 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002194 if (FD->getIdentifier() &&
2195 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002196 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002197 return;
2198 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002199 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002200}
2201
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002202static void RewriteBlockPointerType(std::string& Str, QualType Type) {
2203 std::string TypeString(Type.getAsString());
2204 const char *argPtr = TypeString.c_str();
2205 if (!strchr(argPtr, '^')) {
2206 Str += TypeString;
2207 return;
2208 }
2209 while (*argPtr) {
2210 Str += (*argPtr == '^' ? '*' : *argPtr);
2211 argPtr++;
2212 }
2213}
2214
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002215// FIXME. Consolidate this routine with RewriteBlockPointerType.
2216static void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD) {
2217 QualType Type = VD->getType();
2218 std::string TypeString(Type.getAsString());
2219 const char *argPtr = TypeString.c_str();
2220 int paren = 0;
2221 while (*argPtr) {
2222 switch (*argPtr) {
2223 case '(':
2224 Str += *argPtr;
2225 paren++;
2226 break;
2227 case ')':
2228 Str += *argPtr;
2229 paren--;
2230 break;
2231 case '^':
2232 Str += '*';
2233 if (paren == 1)
2234 Str += VD->getNameAsString();
2235 break;
2236 default:
2237 Str += *argPtr;
2238 break;
2239 }
2240 argPtr++;
2241 }
2242}
2243
2244
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002245void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2246 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2247 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2248 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2249 if (!proto)
2250 return;
2251 QualType Type = proto->getResultType();
2252 std::string FdStr = Type.getAsString();
2253 FdStr += " ";
2254 FdStr += FD->getNameAsCString();
2255 FdStr += "(";
2256 unsigned numArgs = proto->getNumArgs();
2257 for (unsigned i = 0; i < numArgs; i++) {
2258 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002259 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002260 if (i+1 < numArgs)
2261 FdStr += ", ";
2262 }
2263 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002264 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002265 CurFunctionDeclToDeclareForBlock = 0;
2266}
2267
Steve Naroffc0a123c2008-03-11 17:37:02 +00002268// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002269void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002270 if (SuperContructorFunctionDecl)
2271 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002272 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002273 llvm::SmallVector<QualType, 16> ArgTys;
2274 QualType argT = Context->getObjCIdType();
2275 assert(!argT.isNull() && "Can't find 'id' type");
2276 ArgTys.push_back(argT);
2277 ArgTys.push_back(argT);
2278 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2279 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002280 false, 0,
2281 false, false, 0, 0, false,
2282 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002283 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002284 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002285 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002286 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002287}
2288
Steve Naroff09b266e2007-10-30 23:14:51 +00002289// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002290void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002291 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2292 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002293 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002294 assert(!argT.isNull() && "Can't find 'id' type");
2295 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002296 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002297 assert(!argT.isNull() && "Can't find 'SEL' type");
2298 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002299 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002300 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002301 true /*isVariadic*/, 0,
2302 false, false, 0, 0, false,
2303 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002304 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002305 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002306 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002307 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002308}
2309
Steve Naroff874e2322007-11-15 10:28:18 +00002310// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002311void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002312 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2313 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002314 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002315 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002316 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002317 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2318 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2319 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002320 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002321 assert(!argT.isNull() && "Can't find 'SEL' type");
2322 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002323 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002324 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002325 true /*isVariadic*/, 0,
2326 false, false, 0, 0, false,
2327 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002328 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002329 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002330 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002331 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002332}
2333
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002334// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002335void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002336 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2337 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002338 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002339 assert(!argT.isNull() && "Can't find 'id' type");
2340 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002341 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002342 assert(!argT.isNull() && "Can't find 'SEL' type");
2343 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002344 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002345 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002346 true /*isVariadic*/, 0,
2347 false, false, 0, 0, false,
2348 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002349 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002350 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002351 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002352 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002353}
2354
Mike Stump1eb44332009-09-09 15:08:12 +00002355// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002356// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002357void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002358 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002359 &Context->Idents.get("objc_msgSendSuper_stret");
2360 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002361 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002362 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002363 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002364 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2365 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2366 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002367 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002368 assert(!argT.isNull() && "Can't find 'SEL' type");
2369 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002370 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002371 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002372 true /*isVariadic*/, 0,
2373 false, false, 0, 0, false,
2374 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002375 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002376 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002377 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002378 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002379}
2380
Steve Naroff1284db82008-05-08 22:02:18 +00002381// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002382void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002383 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2384 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002385 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002386 assert(!argT.isNull() && "Can't find 'id' type");
2387 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002388 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002389 assert(!argT.isNull() && "Can't find 'SEL' type");
2390 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002391 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002392 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002393 true /*isVariadic*/, 0,
2394 false, false, 0, 0, false,
2395 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002396 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002397 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002398 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002399 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002400}
2401
Steve Naroff09b266e2007-10-30 23:14:51 +00002402// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002403void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002404 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2405 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002406 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002407 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002408 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002409 false /*isVariadic*/, 0,
2410 false, false, 0, 0, false,
2411 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002412 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002413 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002414 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002415 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002416}
2417
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002418// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002419void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002420 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2421 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002422 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002423 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002424 &ArgTys[0], ArgTys.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002425 false /*isVariadic*/, 0,
2426 false, false, 0, 0, false,
2427 CC_Default);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002428 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002429 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002430 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002431 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002432}
2433
Steve Naroffb29b4272008-04-14 22:03:09 +00002434Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002435 QualType strType = getConstantStringStructType();
2436
2437 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002438
2439 std::string tmpName = InFileName;
2440 unsigned i;
2441 for (i=0; i < tmpName.length(); i++) {
2442 char c = tmpName.at(i);
2443 // replace any non alphanumeric characters with '_'.
2444 if (!isalpha(c) && (c < '0' || c > '9'))
2445 tmpName[i] = '_';
2446 }
2447 S += tmpName;
2448 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002449 S += utostr(NumObjCStringLiterals++);
2450
Steve Naroffba92b2e2008-03-27 22:29:16 +00002451 Preamble += "static __NSConstantStringImpl " + S;
2452 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2453 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002454 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002455 std::string prettyBufS;
2456 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002457 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2458 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002459 Preamble += prettyBuf.str();
2460 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002461 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002462
2463 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Benjamin Kramerd999b372010-02-14 14:14:16 +00002464 &Context->Idents.get(S), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002465 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002466 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2467 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002468 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002469 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002470 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002471 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2472 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002473 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002474 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002475 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002476}
2477
Steve Naroffb29b4272008-04-14 22:03:09 +00002478ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002479 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002480 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002482 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002483 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002484 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002485 assert(OPT);
2486 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002487 return IT->getDecl();
2488 }
2489 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002490}
2491
2492// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002493QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002494 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002495 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002496 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002497 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002498 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002499
Steve Naroff874e2322007-11-15 10:28:18 +00002500 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002501 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002502 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002503 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002504
Steve Naroff874e2322007-11-15 10:28:18 +00002505 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002506 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002507 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2508 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002509 FieldTypes[i], 0,
2510 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002511 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002512 }
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Douglas Gregor838db382010-02-11 01:19:42 +00002514 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002515 }
2516 return Context->getTagDeclType(SuperStructDecl);
2517}
2518
Steve Naroffb29b4272008-04-14 22:03:09 +00002519QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002520 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002521 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002522 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002523 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002524 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002526 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002527 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002528 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002529 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002530 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002531 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002532 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002533 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002534
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002535 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002536 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002537 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2538 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002539 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002540 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002541 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002542 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002543 }
2544
Douglas Gregor838db382010-02-11 01:19:42 +00002545 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002546 }
2547 return Context->getTagDeclType(ConstantStringDecl);
2548}
2549
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002550Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2551 SourceLocation StartLoc,
2552 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002553 if (!SelGetUidFunctionDecl)
2554 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002555 if (!MsgSendFunctionDecl)
2556 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002557 if (!MsgSendSuperFunctionDecl)
2558 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002559 if (!MsgSendStretFunctionDecl)
2560 SynthMsgSendStretFunctionDecl();
2561 if (!MsgSendSuperStretFunctionDecl)
2562 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002563 if (!MsgSendFpretFunctionDecl)
2564 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002565 if (!GetClassFunctionDecl)
2566 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002567 if (!GetMetaClassFunctionDecl)
2568 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002569
Steve Naroff874e2322007-11-15 10:28:18 +00002570 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2572 // May need to use objc_msgSend_stret() as well.
2573 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002574 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2575 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002576 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002577 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002578 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002579 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Steve Naroff934f2762007-10-24 22:48:43 +00002582 // Synthesize a call to objc_msgSend().
2583 llvm::SmallVector<Expr*, 8> MsgExprs;
2584 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Steve Naroff934f2762007-10-24 22:48:43 +00002586 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2587 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002588 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2589 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002590 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002591 MsgSendFlavor = MsgSendSuperFunctionDecl;
2592 if (MsgSendStretFlavor)
2593 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2594 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002595
2596 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002597 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002598
2599 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002601 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002602 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002603 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2604 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002605 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002606 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002607 SourceLocation()))
2608 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002609
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002610 llvm::SmallVector<Expr*, 8> ClsExprs;
2611 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002612 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002613 SuperDecl->getIdentifier()->getNameStart(),
2614 SuperDecl->getIdentifier()->getLength(),
2615 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002616 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002617 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002618 ClsExprs.size(),
2619 StartLoc,
2620 EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002621 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002622 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002623 NoTypeInfoCStyleCastExpr(Context,
2624 Context->getObjCIdType(),
2625 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002626 // struct objc_super
2627 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002628 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002629
Steve Naroff23f41272008-03-11 18:14:26 +00002630 if (LangOpts.Microsoft) {
2631 SynthSuperContructorFunctionDecl();
2632 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002633 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002634 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002635 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002636 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002637 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002638 // The code for super is a little tricky to prevent collision with
2639 // the structure definition in the header. The rewriter has it's own
2640 // internal definition (__rw_objc_super) that is uses. This is why
2641 // we need the cast below. For example:
2642 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2643 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002644 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002645 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002646 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002647 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2648 Context->getPointerType(superType),
2649 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002650 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002651 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002652 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2653 &InitExprs[0], InitExprs.size(),
2654 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002655 TypeSourceInfo *superTInfo
2656 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002657 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2658 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002659 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002660 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002661 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002662 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002663 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002664 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002665 } else {
2666 llvm::SmallVector<Expr*, 8> ClsExprs;
2667 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002668 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002669 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002670 clsName->getLength(),
2671 false, argType,
2672 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002673 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002674 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002675 ClsExprs.size(),
2676 StartLoc, EndLoc);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002677 MsgExprs.push_back(Cls);
2678 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002679 } else { // instance message.
2680 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002681
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002682 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002683 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002684 if (MsgSendStretFlavor)
2685 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002686 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Steve Naroff874e2322007-11-15 10:28:18 +00002688 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002689
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002690 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002691 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2692 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002693 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002694 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002695 SourceLocation()))
2696 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Steve Naroff874e2322007-11-15 10:28:18 +00002698 llvm::SmallVector<Expr*, 8> ClsExprs;
2699 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002700 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002701 SuperDecl->getIdentifier()->getNameStart(),
2702 SuperDecl->getIdentifier()->getLength(),
2703 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002704 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002705 &ClsExprs[0],
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002706 ClsExprs.size(),
2707 StartLoc, EndLoc);
Fariborz Jahanian71274312007-12-05 17:29:46 +00002708 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002709 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002710 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002711 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2712 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002713 // struct objc_super
2714 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002715 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002716
Steve Naroffc0a123c2008-03-11 17:37:02 +00002717 if (LangOpts.Microsoft) {
2718 SynthSuperContructorFunctionDecl();
2719 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002720 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002721 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002722 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002723 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002724 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002725 // The code for super is a little tricky to prevent collision with
2726 // the structure definition in the header. The rewriter has it's own
2727 // internal definition (__rw_objc_super) that is uses. This is why
2728 // we need the cast below. For example:
2729 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2730 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002731 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002732 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002733 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002734 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2735 Context->getPointerType(superType),
2736 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002737 } else {
2738 // (struct objc_super) { <exprs from above> }
Ted Kremenekba7bc552010-02-19 01:50:18 +00002739 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2740 &InitExprs[0], InitExprs.size(),
2741 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002742 TypeSourceInfo *superTInfo
2743 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002744 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2745 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002746 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002747 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002748 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002749 // Remove all type-casts because it may contain objc-style types; e.g.
2750 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002751 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002752 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002753 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2754 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002755 MsgExprs.push_back(recExpr);
2756 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002757 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002758 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002759 llvm::SmallVector<Expr*, 8> SelExprs;
2760 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002761 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002762 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002763 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002764 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002765 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002766 &SelExprs[0], SelExprs.size(),
2767 StartLoc,
2768 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002769 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Steve Naroff934f2762007-10-24 22:48:43 +00002771 // Now push any user supplied arguments.
2772 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002773 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002774 // Make all implicit casts explicit...ICE comes in handy:-)
2775 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2776 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002777 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002778 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002779 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002780 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2781 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002782 }
2783 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002784 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002785 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002786 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002787 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002788 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2789 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002790 }
Mike Stump1eb44332009-09-09 15:08:12 +00002791 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002792 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002793 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2794 // out the argument in the original expression (since we aren't deleting
2795 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2796 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002797 }
Steve Naroffab972d32007-11-04 22:37:50 +00002798 // Generate the funky cast.
2799 CastExpr *cast;
2800 llvm::SmallVector<QualType, 8> ArgTypes;
2801 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002802
Steve Naroffab972d32007-11-04 22:37:50 +00002803 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002804 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2805 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2806 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002807 ArgTypes.push_back(Context->getObjCIdType());
2808 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002809 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002810 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002811 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2812 E = OMD->param_end(); PI != E; ++PI) {
2813 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002814 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002815 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002816 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002817 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002818 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002819 t = Context->getPointerType(BPT->getPointeeType());
2820 }
Steve Naroff352336b2007-11-05 14:36:37 +00002821 ArgTypes.push_back(t);
2822 }
Chris Lattner89951a82009-02-20 18:43:26 +00002823 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2824 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian86aa9fd2010-02-24 01:25:40 +00002825 if (isTopLevelBlockPointerType(returnType)) {
2826 const BlockPointerType *BPT = returnType->getAs<BlockPointerType>();
2827 returnType = Context->getPointerType(BPT->getPointeeType());
2828 }
Steve Naroffab972d32007-11-04 22:37:50 +00002829 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002830 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002831 }
2832 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002833 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002834
Steve Naroffab972d32007-11-04 22:37:50 +00002835 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002836 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002837 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002838
Mike Stump1eb44332009-09-09 15:08:12 +00002839 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002840 // If we don't do this cast, we get the following bizarre warning/note:
2841 // xx.m:13: warning: function called through a non-compatible type
2842 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002843 cast = NoTypeInfoCStyleCastExpr(Context,
2844 Context->getPointerType(Context->VoidTy),
2845 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002846
Steve Naroffab972d32007-11-04 22:37:50 +00002847 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002848 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002849 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002850 // If we don't have a method decl, force a variadic cast.
Douglas Gregorce056bc2010-02-21 22:15:06 +00002851 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0,
2852 false, false, 0, 0, false,
2853 CC_Default);
Steve Naroffab972d32007-11-04 22:37:50 +00002854 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002855 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2856 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002857
2858 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002859 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002860
John McCall183700f2009-09-21 23:43:11 +00002861 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002862 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002863 MsgExprs.size(),
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002864 FT->getResultType(), EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002865 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002866 if (MsgSendStretFlavor) {
2867 // We have the method which returns a struct/union. Must also generate
2868 // call to objc_msgSend_stret and hang both varieties on a conditional
2869 // expression which dictate which one to envoke depending on size of
2870 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002872 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002873 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002874 SourceLocation());
2875 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002876 cast = NoTypeInfoCStyleCastExpr(Context,
2877 Context->getPointerType(Context->VoidTy),
2878 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002879 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002880 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002881 &ArgTypes[0], ArgTypes.size(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00002882 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0,
2883 false, false, 0, 0, false,
2884 CC_Default);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002885 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002886 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2887 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002889 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002890 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002891
John McCall183700f2009-09-21 23:43:11 +00002892 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002893 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002894 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002895 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002896
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002897 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002898 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002899 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002900 Context->getSizeType(),
2901 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002902 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2903 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2904 // For X86 it is more complicated and some kind of target specific routine
2905 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002906 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002907 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002908 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002909 Context->IntTy,
2910 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002911 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2912 BinaryOperator::LE,
2913 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002914 SourceLocation());
2915 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002916 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002917 new (Context) ConditionalOperator(lessThanExpr,
2918 SourceLocation(), CE,
2919 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002920 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002921 }
Mike Stump1eb44332009-09-09 15:08:12 +00002922 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002923 return ReplacingStmt;
2924}
2925
Steve Naroffb29b4272008-04-14 22:03:09 +00002926Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002927 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2928 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00002929
Steve Naroff934f2762007-10-24 22:48:43 +00002930 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002931 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002932
2933 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002934 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002935}
2936
Steve Naroff621edce2009-04-29 16:37:50 +00002937// typedef struct objc_object Protocol;
2938QualType RewriteObjC::getProtocolType() {
2939 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002940 TypeSourceInfo *TInfo
2941 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002942 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002943 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002944 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002945 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002946 }
2947 return Context->getTypeDeclType(ProtocolTypeDecl);
2948}
2949
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002950/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002951/// a synthesized/forward data reference (to the protocol's metadata).
2952/// The forward references (and metadata) are generated in
2953/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002954Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002955 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2956 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002957 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002958 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002959 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2960 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2961 Context->getPointerType(DRE->getType()),
2962 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002963 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2964 CastExpr::CK_Unknown,
2965 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002966 ReplaceStmt(Exp, castExpr);
2967 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002968 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002969 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002971}
2972
Mike Stump1eb44332009-09-09 15:08:12 +00002973bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002974 const char *endBuf) {
2975 while (startBuf < endBuf) {
2976 if (*startBuf == '#') {
2977 // Skip whitespace.
2978 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2979 ;
2980 if (!strncmp(startBuf, "if", strlen("if")) ||
2981 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2982 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2983 !strncmp(startBuf, "define", strlen("define")) ||
2984 !strncmp(startBuf, "undef", strlen("undef")) ||
2985 !strncmp(startBuf, "else", strlen("else")) ||
2986 !strncmp(startBuf, "elif", strlen("elif")) ||
2987 !strncmp(startBuf, "endif", strlen("endif")) ||
2988 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2989 !strncmp(startBuf, "include", strlen("include")) ||
2990 !strncmp(startBuf, "import", strlen("import")) ||
2991 !strncmp(startBuf, "include_next", strlen("include_next")))
2992 return true;
2993 }
2994 startBuf++;
2995 }
2996 return false;
2997}
2998
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002999/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003000/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003001void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003002 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003003 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00003004 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003005 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003006 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003007 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003008 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003009 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003010 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003011 SourceLocation LocStart = CDecl->getLocStart();
3012 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Steve Narofffea763e82007-11-14 19:25:57 +00003014 const char *startBuf = SM->getCharacterData(LocStart);
3015 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003017 // If no ivars and no root or if its root, directly or indirectly,
3018 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003019 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3020 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003021 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003022 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003023 return;
3024 }
Mike Stump1eb44332009-09-09 15:08:12 +00003025
3026 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003027 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003028 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003029 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003030 if (LangOpts.Microsoft)
3031 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003032
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003033 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003034 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003035 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003036 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003037 // If the buffer contains preprocessor directives, we do more fine-grained
3038 // rewrites. This is intended to fix code that looks like (which occurs in
3039 // NSURL.h, for example):
3040 //
3041 // #ifdef XYZ
3042 // @interface Foo : NSObject
3043 // #else
3044 // @interface FooBar : NSObject
3045 // #endif
3046 // {
3047 // int i;
3048 // }
3049 // @end
3050 //
3051 // This clause is segregated to avoid breaking the common case.
3052 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003053 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003054 CDecl->getClassLoc();
3055 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003056 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003057
Chris Lattnercafeb352009-02-20 18:18:36 +00003058 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003059 // advance to the end of the referenced protocols.
3060 while (endHeader < cursor && *endHeader != '>') endHeader++;
3061 endHeader++;
3062 }
3063 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003064 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003065 } else {
3066 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003067 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003068 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003069 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003070 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003071 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003072 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003073 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003074 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003075
Steve Narofffea763e82007-11-14 19:25:57 +00003076 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003077 SourceLocation OnePastCurly =
3078 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003079 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003080 }
3081 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003082
Steve Narofffea763e82007-11-14 19:25:57 +00003083 // Now comment out any visibility specifiers.
3084 while (cursor < endBuf) {
3085 if (*cursor == '@') {
3086 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003087 // Skip whitespace.
3088 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3089 /*scan*/;
3090
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003091 // FIXME: presence of @public, etc. inside comment results in
3092 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003093 if (!strncmp(cursor, "public", strlen("public")) ||
3094 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003095 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003096 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003097 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003098 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003099 // FIXME: If there are cases where '<' is used in ivar declaration part
3100 // of user code, then scan the ivar list and use needToScanForQualifiers
3101 // for type checking.
3102 else if (*cursor == '<') {
3103 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003104 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003105 cursor = strchr(cursor, '>');
3106 cursor++;
3107 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003108 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003109 } else if (*cursor == '^') { // rewrite block specifier.
3110 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003111 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003112 }
Steve Narofffea763e82007-11-14 19:25:57 +00003113 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003114 }
Steve Narofffea763e82007-11-14 19:25:57 +00003115 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003116 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003117 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003118 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003119 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003120 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003121 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003122 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003123 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003124 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003125 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003126 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003127 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003128 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003129}
3130
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003131// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003132/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003133template<typename MethodIterator>
3134void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3135 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003136 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003137 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003138 const char *ClassName,
3139 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003140 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003142 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003143 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003144 SEL _cmd;
3145 char *method_types;
3146 void *_imp;
3147 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003148 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003149 Result += "\nstruct _objc_method {\n";
3150 Result += "\tSEL _cmd;\n";
3151 Result += "\tchar *method_types;\n";
3152 Result += "\tvoid *_imp;\n";
3153 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003155 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003156 }
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003158 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003159
Steve Naroff946a6932008-03-11 00:12:29 +00003160 /* struct {
3161 struct _objc_method_list *next_method;
3162 int method_count;
3163 struct _objc_method method_list[];
3164 }
3165 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003166 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003167 Result += "\nstatic struct {\n";
3168 Result += "\tstruct _objc_method_list *next_method;\n";
3169 Result += "\tint method_count;\n";
3170 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003171 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003172 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003173 Result += prefix;
3174 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3175 Result += "_METHODS_";
3176 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003177 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003178 Result += IsInstanceMethod ? "inst" : "cls";
3179 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003180 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003181
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003182 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003183 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003184 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003185 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003186 Result += "\", \"";
3187 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003188 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003189 Result += MethodInternalNames[*MethodBegin];
3190 Result += "}\n";
3191 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3192 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003193 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003194 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003195 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003196 Result += "\", \"";
3197 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003198 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003199 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003200 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003201 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003202 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003203}
3204
Steve Naroff621edce2009-04-29 16:37:50 +00003205/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003206void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003207RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3208 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003209 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003210
3211 // Output struct protocol_methods holder of method selector and type.
3212 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3213 /* struct protocol_methods {
3214 SEL _cmd;
3215 char *method_types;
3216 }
3217 */
3218 Result += "\nstruct _protocol_methods {\n";
3219 Result += "\tstruct objc_selector *_cmd;\n";
3220 Result += "\tchar *method_types;\n";
3221 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003222
Steve Naroff621edce2009-04-29 16:37:50 +00003223 objc_protocol_methods = true;
3224 }
3225 // Do not synthesize the protocol more than once.
3226 if (ObjCSynthesizedProtocols.count(PDecl))
3227 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003229 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3230 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3231 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003232 /* struct _objc_protocol_method_list {
3233 int protocol_method_count;
3234 struct protocol_methods protocols[];
3235 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003236 */
Steve Naroff621edce2009-04-29 16:37:50 +00003237 Result += "\nstatic struct {\n";
3238 Result += "\tint protocol_method_count;\n";
3239 Result += "\tstruct _protocol_methods protocol_methods[";
3240 Result += utostr(NumMethods);
3241 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3242 Result += PDecl->getNameAsString();
3243 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3244 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Steve Naroff621edce2009-04-29 16:37:50 +00003246 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003247 for (ObjCProtocolDecl::instmeth_iterator
3248 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003249 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003250 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003251 Result += "\t ,{{(struct objc_selector *)\"";
3252 else
3253 Result += "\t ,{(struct objc_selector *)\"";
3254 Result += (*I)->getSelector().getAsString().c_str();
3255 std::string MethodTypeString;
3256 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3257 Result += "\", \"";
3258 Result += MethodTypeString;
3259 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003260 }
Steve Naroff621edce2009-04-29 16:37:50 +00003261 Result += "\t }\n};\n";
3262 }
Mike Stump1eb44332009-09-09 15:08:12 +00003263
Steve Naroff621edce2009-04-29 16:37:50 +00003264 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003265 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3266 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003267 if (NumMethods > 0) {
3268 /* struct _objc_protocol_method_list {
3269 int protocol_method_count;
3270 struct protocol_methods protocols[];
3271 }
3272 */
3273 Result += "\nstatic struct {\n";
3274 Result += "\tint protocol_method_count;\n";
3275 Result += "\tstruct _protocol_methods protocol_methods[";
3276 Result += utostr(NumMethods);
3277 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3278 Result += PDecl->getNameAsString();
3279 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3280 "{\n\t";
3281 Result += utostr(NumMethods);
3282 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Steve Naroff621edce2009-04-29 16:37:50 +00003284 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003285 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003286 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003287 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003288 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003289 Result += "\t ,{{(struct objc_selector *)\"";
3290 else
3291 Result += "\t ,{(struct objc_selector *)\"";
3292 Result += (*I)->getSelector().getAsString().c_str();
3293 std::string MethodTypeString;
3294 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3295 Result += "\", \"";
3296 Result += MethodTypeString;
3297 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003298 }
Steve Naroff621edce2009-04-29 16:37:50 +00003299 Result += "\t }\n};\n";
3300 }
3301
3302 // Output:
3303 /* struct _objc_protocol {
3304 // Objective-C 1.0 extensions
3305 struct _objc_protocol_extension *isa;
3306 char *protocol_name;
3307 struct _objc_protocol **protocol_list;
3308 struct _objc_protocol_method_list *instance_methods;
3309 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003310 };
Steve Naroff621edce2009-04-29 16:37:50 +00003311 */
3312 static bool objc_protocol = false;
3313 if (!objc_protocol) {
3314 Result += "\nstruct _objc_protocol {\n";
3315 Result += "\tstruct _objc_protocol_extension *isa;\n";
3316 Result += "\tchar *protocol_name;\n";
3317 Result += "\tstruct _objc_protocol **protocol_list;\n";
3318 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3319 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003320 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003321
Steve Naroff621edce2009-04-29 16:37:50 +00003322 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003323 }
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Steve Naroff621edce2009-04-29 16:37:50 +00003325 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3326 Result += PDecl->getNameAsString();
3327 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3328 "{\n\t0, \"";
3329 Result += PDecl->getNameAsString();
3330 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003331 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003332 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3333 Result += PDecl->getNameAsString();
3334 Result += ", ";
3335 }
3336 else
3337 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003338 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003339 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3340 Result += PDecl->getNameAsString();
3341 Result += "\n";
3342 }
3343 else
3344 Result += "0\n";
3345 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003346
Steve Naroff621edce2009-04-29 16:37:50 +00003347 // Mark this protocol as having been generated.
3348 if (!ObjCSynthesizedProtocols.insert(PDecl))
3349 assert(false && "protocol already synthesized");
3350
3351}
3352
3353void RewriteObjC::
3354RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3355 const char *prefix, const char *ClassName,
3356 std::string &Result) {
3357 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003358
Steve Naroff621edce2009-04-29 16:37:50 +00003359 for (unsigned i = 0; i != Protocols.size(); i++)
3360 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3361
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003362 // Output the top lovel protocol meta-data for the class.
3363 /* struct _objc_protocol_list {
3364 struct _objc_protocol_list *next;
3365 int protocol_count;
3366 struct _objc_protocol *class_protocols[];
3367 }
3368 */
3369 Result += "\nstatic struct {\n";
3370 Result += "\tstruct _objc_protocol_list *next;\n";
3371 Result += "\tint protocol_count;\n";
3372 Result += "\tstruct _objc_protocol *class_protocols[";
3373 Result += utostr(Protocols.size());
3374 Result += "];\n} _OBJC_";
3375 Result += prefix;
3376 Result += "_PROTOCOLS_";
3377 Result += ClassName;
3378 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3379 "{\n\t0, ";
3380 Result += utostr(Protocols.size());
3381 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003383 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003385 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003387 for (unsigned i = 1; i != Protocols.size(); i++) {
3388 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003389 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003390 Result += "\n";
3391 }
3392 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003393}
3394
Steve Naroff621edce2009-04-29 16:37:50 +00003395
Mike Stump1eb44332009-09-09 15:08:12 +00003396/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003397/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003398void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003399 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003400 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003401 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003402 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003403 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003404 CDecl = CDecl->getNextClassCategory())
3405 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3406 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003408 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003409 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003410 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003411
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003412 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003413 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003414 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003415
3416 // If any of our property implementations have associated getters or
3417 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003418 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3419 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003420 Prop != PropEnd; ++Prop) {
3421 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3422 continue;
3423 if (!(*Prop)->getPropertyIvarDecl())
3424 continue;
3425 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3426 if (!PD)
3427 continue;
3428 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3429 InstanceMethods.push_back(Getter);
3430 if (PD->isReadOnly())
3431 continue;
3432 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3433 InstanceMethods.push_back(Setter);
3434 }
3435 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003436 true, "CATEGORY_", FullCategoryName.c_str(),
3437 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003438
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003439 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003440 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003441 false, "CATEGORY_", FullCategoryName.c_str(),
3442 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003444 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003445 // Null CDecl is case of a category implementation with no category interface
3446 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003447 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3448 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003449 /* struct _objc_category {
3450 char *category_name;
3451 char *class_name;
3452 struct _objc_method_list *instance_methods;
3453 struct _objc_method_list *class_methods;
3454 struct _objc_protocol_list *protocols;
3455 // Objective-C 1.0 extensions
3456 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003457 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003458 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003459 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003460 */
Mike Stump1eb44332009-09-09 15:08:12 +00003461
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003462 static bool objc_category = false;
3463 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003464 Result += "\nstruct _objc_category {\n";
3465 Result += "\tchar *category_name;\n";
3466 Result += "\tchar *class_name;\n";
3467 Result += "\tstruct _objc_method_list *instance_methods;\n";
3468 Result += "\tstruct _objc_method_list *class_methods;\n";
3469 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003470 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003471 Result += "\tstruct _objc_property_list *instance_properties;\n";
3472 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003473 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003474 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003475 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3476 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003477 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003478 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003479 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003480 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003481 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003482
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003483 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003484 Result += "\t, (struct _objc_method_list *)"
3485 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3486 Result += FullCategoryName;
3487 Result += "\n";
3488 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003489 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003490 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003491 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003492 Result += "\t, (struct _objc_method_list *)"
3493 "&_OBJC_CATEGORY_CLASS_METHODS_";
3494 Result += FullCategoryName;
3495 Result += "\n";
3496 }
3497 else
3498 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Chris Lattnercafeb352009-02-20 18:18:36 +00003500 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003501 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003502 Result += FullCategoryName;
3503 Result += "\n";
3504 }
3505 else
3506 Result += "\t, 0\n";
3507 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003508}
3509
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003510/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3511/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003512void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3513 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003514 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003515 if (ivar->isBitField()) {
3516 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3517 // place all bitfields at offset 0.
3518 Result += "0";
3519 } else {
3520 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003521 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003522 if (LangOpts.Microsoft)
3523 Result += "_IMPL";
3524 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003525 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003526 Result += ")";
3527 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003528}
3529
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003530//===----------------------------------------------------------------------===//
3531// Meta Data Emission
3532//===----------------------------------------------------------------------===//
3533
Steve Naroffb29b4272008-04-14 22:03:09 +00003534void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003535 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003536 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003538 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003539 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003540 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003541 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003542 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003543 }
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Chris Lattnerbe6df082007-12-12 07:56:42 +00003545 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003546 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003547 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003548 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003549 if (NumIvars > 0) {
3550 static bool objc_ivar = false;
3551 if (!objc_ivar) {
3552 /* struct _objc_ivar {
3553 char *ivar_name;
3554 char *ivar_type;
3555 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003556 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003557 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003558 Result += "\nstruct _objc_ivar {\n";
3559 Result += "\tchar *ivar_name;\n";
3560 Result += "\tchar *ivar_type;\n";
3561 Result += "\tint ivar_offset;\n";
3562 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003564 objc_ivar = true;
3565 }
3566
Steve Naroff946a6932008-03-11 00:12:29 +00003567 /* struct {
3568 int ivar_count;
3569 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003570 };
Steve Naroff946a6932008-03-11 00:12:29 +00003571 */
Mike Stump1eb44332009-09-09 15:08:12 +00003572 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003573 Result += "\tint ivar_count;\n";
3574 Result += "\tstruct _objc_ivar ivar_list[";
3575 Result += utostr(NumIvars);
3576 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003577 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003578 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003579 "{\n\t";
3580 Result += utostr(NumIvars);
3581 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003582
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003583 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003584 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003585 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003586 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003587 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003588 IV != IVEnd; ++IV)
3589 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003590 IVI = IDecl->ivar_begin();
3591 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003592 } else {
3593 IVI = CDecl->ivar_begin();
3594 IVE = CDecl->ivar_end();
3595 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003598 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003599 std::string TmpString, StrEncoding;
3600 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3601 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003602 Result += StrEncoding;
3603 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003604 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003605 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003606 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003607 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003608 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003609 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003610 std::string TmpString, StrEncoding;
3611 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3612 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003613 Result += StrEncoding;
3614 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003615 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003616 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003617 }
Mike Stump1eb44332009-09-09 15:08:12 +00003618
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003619 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003620 }
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003622 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003623 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003624 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003625
3626 // If any of our property implementations have associated getters or
3627 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003628 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3629 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003630 Prop != PropEnd; ++Prop) {
3631 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3632 continue;
3633 if (!(*Prop)->getPropertyIvarDecl())
3634 continue;
3635 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3636 if (!PD)
3637 continue;
3638 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3639 InstanceMethods.push_back(Getter);
3640 if (PD->isReadOnly())
3641 continue;
3642 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3643 InstanceMethods.push_back(Setter);
3644 }
3645 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003646 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003648 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003649 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003650 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003652 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003653 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3654 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003656 // Declaration of class/meta-class metadata
3657 /* struct _objc_class {
3658 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003659 const char *super_class_name;
3660 char *name;
3661 long version;
3662 long info;
3663 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003664 struct _objc_ivar_list *ivars;
3665 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003666 struct objc_cache *cache;
3667 struct objc_protocol_list *protocols;
3668 const char *ivar_layout;
3669 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003670 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003671 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003672 static bool objc_class = false;
3673 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003674 Result += "\nstruct _objc_class {\n";
3675 Result += "\tstruct _objc_class *isa;\n";
3676 Result += "\tconst char *super_class_name;\n";
3677 Result += "\tchar *name;\n";
3678 Result += "\tlong version;\n";
3679 Result += "\tlong info;\n";
3680 Result += "\tlong instance_size;\n";
3681 Result += "\tstruct _objc_ivar_list *ivars;\n";
3682 Result += "\tstruct _objc_method_list *methods;\n";
3683 Result += "\tstruct objc_cache *cache;\n";
3684 Result += "\tstruct _objc_protocol_list *protocols;\n";
3685 Result += "\tconst char *ivar_layout;\n";
3686 Result += "\tstruct _objc_class_ext *ext;\n";
3687 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003688 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003689 }
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003691 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003692 ObjCInterfaceDecl *RootClass = 0;
3693 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003694 while (SuperClass) {
3695 RootClass = SuperClass;
3696 SuperClass = SuperClass->getSuperClass();
3697 }
3698 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003700 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003701 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003702 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003703 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003704 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003705 Result += "\"";
3706
3707 if (SuperClass) {
3708 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003709 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003710 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003711 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003712 Result += "\"";
3713 }
3714 else {
3715 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003716 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003717 Result += "\"";
3718 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003719 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003720 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003721 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003722 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003723 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003724 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003725 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003726 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003727 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003728 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003729 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003730 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003731 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003732 Result += ",0,0\n";
3733 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003734 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003735 Result += "\t,0,0,0,0\n";
3736 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003738 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003739 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003740 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003741 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003742 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003743 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003744 if (SuperClass) {
3745 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003746 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003747 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003748 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003749 Result += "\"";
3750 }
3751 else {
3752 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003753 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003754 Result += "\"";
3755 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003756 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003757 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003758 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003759 Result += ",0";
3760 else {
3761 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003762 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003763 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003764 if (LangOpts.Microsoft)
3765 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003766 Result += ")";
3767 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003768 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003769 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003770 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003771 Result += "\n\t";
3772 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003773 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003775 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003776 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003777 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003778 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003779 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003780 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003781 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003782 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003783 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003784 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003785 Result += ", 0,0\n";
3786 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003787 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003788 Result += ",0,0,0\n";
3789 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003790}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003791
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003792/// RewriteImplementations - This routine rewrites all method implementations
3793/// and emits meta-data.
3794
Steve Narofface66252008-11-13 20:07:04 +00003795void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003796 int ClsDefCount = ClassImplementation.size();
3797 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003798
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003799 // Rewrite implemented methods
3800 for (int i = 0; i < ClsDefCount; i++)
3801 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003803 for (int i = 0; i < CatDefCount; i++)
3804 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003805}
Mike Stump1eb44332009-09-09 15:08:12 +00003806
Steve Narofface66252008-11-13 20:07:04 +00003807void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3808 int ClsDefCount = ClassImplementation.size();
3809 int CatDefCount = CategoryImplementation.size();
3810
Steve Naroff5df5b762008-05-07 21:23:49 +00003811 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003812 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003813 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003814 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003815 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003817 // For each implemented category, write out all its meta data.
3818 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003819 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003820
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003821 // Write objc_symtab metadata
3822 /*
3823 struct _objc_symtab
3824 {
3825 long sel_ref_cnt;
3826 SEL *refs;
3827 short cls_def_cnt;
3828 short cat_def_cnt;
3829 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003830 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003831 */
Mike Stump1eb44332009-09-09 15:08:12 +00003832
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003833 Result += "\nstruct _objc_symtab {\n";
3834 Result += "\tlong sel_ref_cnt;\n";
3835 Result += "\tSEL *refs;\n";
3836 Result += "\tshort cls_def_cnt;\n";
3837 Result += "\tshort cat_def_cnt;\n";
3838 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3839 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003841 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003842 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003843 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003844 + ", " + utostr(CatDefCount) + "\n";
3845 for (int i = 0; i < ClsDefCount; i++) {
3846 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003847 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003848 Result += "\n";
3849 }
Mike Stump1eb44332009-09-09 15:08:12 +00003850
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003851 for (int i = 0; i < CatDefCount; i++) {
3852 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003853 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003854 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003855 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003856 Result += "\n";
3857 }
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003859 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003860
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003861 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003862
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003863 /*
3864 struct _objc_module {
3865 long version;
3866 long size;
3867 const char *name;
3868 struct _objc_symtab *symtab;
3869 }
3870 */
Mike Stump1eb44332009-09-09 15:08:12 +00003871
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003872 Result += "\nstruct _objc_module {\n";
3873 Result += "\tlong version;\n";
3874 Result += "\tlong size;\n";
3875 Result += "\tconst char *name;\n";
3876 Result += "\tstruct _objc_symtab *symtab;\n";
3877 Result += "};\n\n";
3878 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003879 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003880 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003881 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003882 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003883
3884 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003885 if (ProtocolExprDecls.size()) {
3886 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3887 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003888 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003889 E = ProtocolExprDecls.end(); I != E; ++I) {
3890 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3891 Result += (*I)->getNameAsString();
3892 Result += " = &_OBJC_PROTOCOL_";
3893 Result += (*I)->getNameAsString();
3894 Result += ";\n";
3895 }
3896 Result += "#pragma data_seg(pop)\n\n";
3897 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003898 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003899 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003900 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3901 Result += "&_OBJC_MODULES;\n";
3902 Result += "#pragma data_seg(pop)\n\n";
3903 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003904}
Chris Lattner311ff022007-10-16 22:36:42 +00003905
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003906void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3907 const std::string &Name,
3908 ValueDecl *VD) {
3909 assert(BlockByRefDeclNo.count(VD) &&
3910 "RewriteByRefString: ByRef decl missing");
3911 ResultStr += "struct __Block_byref_" + Name +
3912 "_" + utostr(BlockByRefDeclNo[VD]) ;
3913}
3914
Steve Naroff54055232008-10-27 17:20:55 +00003915std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3916 const char *funcName,
3917 std::string Tag) {
3918 const FunctionType *AFT = CE->getFunctionType();
3919 QualType RT = AFT->getResultType();
3920 std::string StructRef = "struct " + Tag;
3921 std::string S = "static " + RT.getAsString() + " __" +
3922 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003923
Steve Naroff54055232008-10-27 17:20:55 +00003924 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Douglas Gregor72564e72009-02-26 23:50:07 +00003926 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003927 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003928 // block (to reference imported block decl refs).
3929 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003930 } else if (BD->param_empty()) {
3931 S += "(" + StructRef + " *__cself)";
3932 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003933 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003934 assert(FT && "SynthesizeBlockFunc: No function proto");
3935 S += '(';
3936 // first add the implicit argument.
3937 S += StructRef + " *__cself, ";
3938 std::string ParamStr;
3939 for (BlockDecl::param_iterator AI = BD->param_begin(),
3940 E = BD->param_end(); AI != E; ++AI) {
3941 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003942 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003943 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003944 S += ParamStr;
3945 }
3946 if (FT->isVariadic()) {
3947 if (!BD->param_empty()) S += ", ";
3948 S += "...";
3949 }
3950 S += ')';
3951 }
3952 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Steve Naroff54055232008-10-27 17:20:55 +00003954 // Create local declarations to avoid rewriting all closure decl ref exprs.
3955 // First, emit a declaration for all "by ref" decls.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003956 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003957 E = BlockByRefDecls.end(); I != E; ++I) {
3958 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003959 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003960 std::string TypeString;
3961 RewriteByRefString(TypeString, Name, (*I));
3962 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003963 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003964 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003965 }
Steve Naroff54055232008-10-27 17:20:55 +00003966 // Next, emit a declaration for all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003967 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003968 E = BlockByCopyDecls.end(); I != E; ++I) {
3969 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003970 // Handle nested closure invocation. For example:
3971 //
3972 // void (^myImportedClosure)(void);
3973 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003974 //
Steve Naroff54055232008-10-27 17:20:55 +00003975 // void (^anotherClosure)(void);
3976 // anotherClosure = ^(void) {
3977 // myImportedClosure(); // import and invoke the closure
3978 // };
3979 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003980 if (isTopLevelBlockPointerType((*I)->getType())) {
3981 RewriteBlockPointerTypeVariable(S, (*I));
3982 S += " = (";
3983 RewriteBlockPointerType(S, (*I)->getType());
3984 S += ")";
3985 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3986 }
3987 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003988 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003989 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003990 S += Name + " = __cself->" +
3991 (*I)->getNameAsString() + "; // bound by copy\n";
3992 }
Steve Naroff54055232008-10-27 17:20:55 +00003993 }
3994 std::string RewrittenStr = RewrittenBlockExprs[CE];
3995 const char *cstr = RewrittenStr.c_str();
3996 while (*cstr++ != '{') ;
3997 S += cstr;
3998 S += "\n";
3999 return S;
4000}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004001
Steve Naroff54055232008-10-27 17:20:55 +00004002std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4003 const char *funcName,
4004 std::string Tag) {
4005 std::string StructRef = "struct " + Tag;
4006 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Steve Naroff54055232008-10-27 17:20:55 +00004008 S += funcName;
4009 S += "_block_copy_" + utostr(i);
4010 S += "(" + StructRef;
4011 S += "*dst, " + StructRef;
4012 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004013 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004014 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004015 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004016 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004017 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004019 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004020 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004021 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004022 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004023 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004024 S += "}\n";
4025
Steve Naroff54055232008-10-27 17:20:55 +00004026 S += "\nstatic void __";
4027 S += funcName;
4028 S += "_block_dispose_" + utostr(i);
4029 S += "(" + StructRef;
4030 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004031 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004032 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00004033 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004034 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004035 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004036 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004037 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004038 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004039 }
Mike Stump1eb44332009-09-09 15:08:12 +00004040 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004041 return S;
4042}
4043
Steve Naroff01aec112009-12-06 21:14:13 +00004044std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4045 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004046 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004047 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Steve Naroff54055232008-10-27 17:20:55 +00004049 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004050 S += " struct " + Desc;
4051 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Steve Naroff01aec112009-12-06 21:14:13 +00004053 Constructor += "(void *fp, "; // Invoke function pointer.
4054 Constructor += "struct " + Desc; // Descriptor pointer.
4055 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Steve Naroff54055232008-10-27 17:20:55 +00004057 if (BlockDeclRefs.size()) {
4058 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004059 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004060 E = BlockByCopyDecls.end(); I != E; ++I) {
4061 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004063 std::string ArgName = "_" + FieldName;
4064 // Handle nested closure invocation. For example:
4065 //
4066 // void (^myImportedBlock)(void);
4067 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004068 //
Steve Naroff54055232008-10-27 17:20:55 +00004069 // void (^anotherBlock)(void);
4070 // anotherBlock = ^(void) {
4071 // myImportedBlock(); // import and invoke the closure
4072 // };
4073 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004074 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004075 S += "struct __block_impl *";
4076 Constructor += ", void *" + ArgName;
4077 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00004078 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
4079 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004080 Constructor += ", " + ArgName;
4081 }
4082 S += FieldName + ";\n";
4083 }
4084 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004085 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004086 E = BlockByRefDecls.end(); I != E; ++I) {
4087 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004088 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004089 std::string ArgName = "_" + FieldName;
4090 // Handle nested closure invocation. For example:
4091 //
4092 // void (^myImportedBlock)(void);
4093 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004094 //
Steve Naroff54055232008-10-27 17:20:55 +00004095 // void (^anotherBlock)(void);
4096 // anotherBlock = ^(void) {
4097 // myImportedBlock(); // import and invoke the closure
4098 // };
4099 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004100 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004101 S += "struct __block_impl *";
4102 Constructor += ", void *" + ArgName;
4103 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004104 std::string TypeString;
4105 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004106 TypeString += " *";
4107 FieldName = TypeString + FieldName;
4108 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004109 Constructor += ", " + ArgName;
4110 }
4111 S += FieldName + "; // by ref\n";
4112 }
4113 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004114 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004115 if (GlobalVarDecl)
4116 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4117 else
4118 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004119 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Steve Naroff01aec112009-12-06 21:14:13 +00004121 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004122
Steve Naroff54055232008-10-27 17:20:55 +00004123 // Initialize all "by copy" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004124 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004125 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004126 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004127 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004128 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004129 Constructor += Name + " = (struct __block_impl *)_";
4130 else
4131 Constructor += Name + " = _";
4132 Constructor += Name + ";\n";
4133 }
4134 // Initialize all "by ref" arguments.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004135 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004136 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004137 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004138 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004139 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004140 Constructor += Name + " = (struct __block_impl *)_";
4141 else
4142 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004143 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004144 }
4145 } else {
4146 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004147 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004148 if (GlobalVarDecl)
4149 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4150 else
4151 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004152 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4153 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004154 }
4155 Constructor += " ";
4156 Constructor += "}\n";
4157 S += Constructor;
4158 S += "};\n";
4159 return S;
4160}
4161
Steve Naroff01aec112009-12-06 21:14:13 +00004162std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4163 std::string ImplTag, int i,
4164 const char *FunName,
4165 unsigned hasCopy) {
4166 std::string S = "\nstatic struct " + DescTag;
4167
4168 S += " {\n unsigned long reserved;\n";
4169 S += " unsigned long Block_size;\n";
4170 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004171 S += " void (*copy)(struct ";
4172 S += ImplTag; S += "*, struct ";
4173 S += ImplTag; S += "*);\n";
4174
4175 S += " void (*dispose)(struct ";
4176 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004177 }
4178 S += "} ";
4179
4180 S += DescTag + "_DATA = { 0, sizeof(struct ";
4181 S += ImplTag + ")";
4182 if (hasCopy) {
4183 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4184 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4185 }
4186 S += "};\n";
4187 return S;
4188}
4189
Steve Naroff54055232008-10-27 17:20:55 +00004190void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004191 const char *FunName) {
4192 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004193 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004194 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004195 // Insert closures that were part of the function.
4196 for (unsigned i = 0; i < Blocks.size(); i++) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004197 // Need to copy-in the inner copied-in variables not actually used in this
4198 // block.
4199 for (int j = 0; j < InnerDeclRefsCount[i]; j++)
4200 BlockDeclRefs.push_back(InnerDeclRefs[j]);
Steve Naroff54055232008-10-27 17:20:55 +00004201 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004202 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
4203 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4204 GetInnerBlockDeclRefExprs(Blocks[i]->getBody(),
4205 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Naroff54055232008-10-27 17:20:55 +00004206
Steve Naroff01aec112009-12-06 21:14:13 +00004207 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4208 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004209
Steve Naroff01aec112009-12-06 21:14:13 +00004210 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004211
Benjamin Kramerd999b372010-02-14 14:14:16 +00004212 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004213
Steve Naroff01aec112009-12-06 21:14:13 +00004214 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004215
Benjamin Kramerd999b372010-02-14 14:14:16 +00004216 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004217
4218 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004219 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004220 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004221 }
Steve Naroff01aec112009-12-06 21:14:13 +00004222 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4223 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004224 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004225
Steve Naroff54055232008-10-27 17:20:55 +00004226 BlockDeclRefs.clear();
4227 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004228 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004229 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004230 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004231 BlockCallExprs.clear();
4232 ImportedBlockDecls.clear();
4233 }
4234 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004235 InnerDeclRefsCount.clear();
4236 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004237 RewrittenBlockExprs.clear();
4238}
4239
4240void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4241 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004242 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004243
Steve Naroff54055232008-10-27 17:20:55 +00004244 SynthesizeBlockLiterals(FunLocStart, FuncName);
4245}
4246
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004247static void BuildUniqueMethodName(std::string &Name,
4248 ObjCMethodDecl *MD) {
4249 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4250 Name = IFace->getNameAsCString();
4251 Name += "__" + MD->getSelector().getAsString();
4252 // Convert colons to underscores.
4253 std::string::size_type loc = 0;
4254 while ((loc = Name.find(":", loc)) != std::string::npos)
4255 Name.replace(loc, 1, "_");
4256}
4257
Steve Naroff54055232008-10-27 17:20:55 +00004258void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004259 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4260 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004261 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004262 std::string FuncName;
4263 BuildUniqueMethodName(FuncName, MD);
Steve Naroff54055232008-10-27 17:20:55 +00004264 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4265}
4266
4267void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4268 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4269 CI != E; ++CI)
4270 if (*CI) {
4271 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4272 GetBlockDeclRefExprs(CBE->getBody());
4273 else
4274 GetBlockDeclRefExprs(*CI);
4275 }
4276 // Handle specific things.
4277 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4278 // FIXME: Handle enums.
4279 if (!isa<FunctionDecl>(CDRE->getDecl()))
4280 BlockDeclRefs.push_back(CDRE);
4281 return;
4282}
4283
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004284void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4285 llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
4286 llvm::SmallPtrSet<ValueDecl *, 8> &InnerBlockValueDecls) {
4287 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4288 CI != E; ++CI)
4289 if (*CI) {
4290 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4291 GetInnerBlockDeclRefExprs(CBE->getBody(),
4292 InnerBlockDeclRefs,
4293 InnerBlockValueDecls);
4294 else
4295 GetInnerBlockDeclRefExprs(*CI,
4296 InnerBlockDeclRefs,
4297 InnerBlockValueDecls);
4298
4299 }
4300 // Handle specific things.
4301 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4302 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
4303 !CDRE->isByRef() &&
4304 !InnerBlockValueDecls.count(CDRE->getDecl())) {
4305 InnerBlockValueDecls.insert(CDRE->getDecl());
4306 InnerBlockDeclRefs.push_back(CDRE);
4307 }
4308 return;
4309}
4310
Steve Naroff54055232008-10-27 17:20:55 +00004311void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4312 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4313 CI != E; ++CI)
4314 if (*CI) {
4315 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4316 GetBlockCallExprs(CBE->getBody());
4317 else
4318 GetBlockCallExprs(*CI);
4319 }
Mike Stump1eb44332009-09-09 15:08:12 +00004320
Steve Naroff54055232008-10-27 17:20:55 +00004321 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4322 if (CE->getCallee()->getType()->isBlockPointerType()) {
4323 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4324 }
4325 }
4326 return;
4327}
4328
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004329Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004330 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004331 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004332
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004333 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004334 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004335 } else if (const BlockDeclRefExpr *CDRE =
4336 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004337 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004338 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004339 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004340 }
4341 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4342 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4343 }
4344 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4345 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4346 else if (const ConditionalOperator *CEXPR =
4347 dyn_cast<ConditionalOperator>(BlockExp)) {
4348 Expr *LHSExp = CEXPR->getLHS();
4349 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4350 Expr *RHSExp = CEXPR->getRHS();
4351 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4352 Expr *CONDExp = CEXPR->getCond();
4353 ConditionalOperator *CondExpr =
4354 new (Context) ConditionalOperator(CONDExp,
4355 SourceLocation(), cast<Expr>(LHSStmt),
4356 SourceLocation(), cast<Expr>(RHSStmt),
4357 Exp->getType());
4358 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004359 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4360 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004361 } else {
4362 assert(1 && "RewriteBlockClass: Bad type");
4363 }
4364 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004365 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004366 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004367 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004368 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004370 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4371 SourceLocation(),
4372 &Context->Idents.get("__block_impl"));
4373 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004374
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004375 // Generate a funky cast.
4376 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004378 // Push the block argument type.
4379 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004380 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004381 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004382 E = FTP->arg_type_end(); I && (I != E); ++I) {
4383 QualType t = *I;
4384 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004385 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004386 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004387 t = Context->getPointerType(BPT->getPointeeType());
4388 }
4389 ArgTypes.push_back(t);
4390 }
Steve Naroff54055232008-10-27 17:20:55 +00004391 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004392 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004393 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Douglas Gregorce056bc2010-02-21 22:15:06 +00004394 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0,
4395 false, false, 0, 0,
4396 false, CC_Default);
Mike Stump1eb44332009-09-09 15:08:12 +00004397
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004398 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004399
John McCall9d125032010-01-15 18:39:57 +00004400 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4401 CastExpr::CK_Unknown,
4402 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004403 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004404 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4405 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004406 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Douglas Gregor44b43212008-12-11 16:49:14 +00004408 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004409 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004410 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004411 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4412 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004413
John McCall9d125032010-01-15 18:39:57 +00004414 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4415 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004416 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004418 llvm::SmallVector<Expr*, 8> BlkExprs;
4419 // Add the implicit argument.
4420 BlkExprs.push_back(BlkCast);
4421 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004422 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004423 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004424 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004425 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004426 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4427 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004428 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004429 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004430}
4431
4432void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004433 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004434 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004435}
4436
Steve Naroff621edce2009-04-29 16:37:50 +00004437// We need to return the rewritten expression to handle cases where the
4438// BlockDeclRefExpr is embedded in another expression being rewritten.
4439// For example:
4440//
4441// int main() {
4442// __block Foo *f;
4443// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004444//
Steve Naroff621edce2009-04-29 16:37:50 +00004445// void (^myblock)() = ^() {
4446// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4447// i = 77;
4448// };
4449//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004450Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004451 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004452 // for each DeclRefExp where BYREFVAR is name of the variable.
4453 ValueDecl *VD;
4454 bool isArrow = true;
4455 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4456 VD = BDRE->getDecl();
4457 else {
4458 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4459 isArrow = false;
4460 }
4461
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004462 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4463 &Context->Idents.get("__forwarding"),
4464 Context->VoidPtrTy, 0,
4465 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004466 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4467 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004468 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004469
4470 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004471 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4472 &Context->Idents.get(Name),
4473 Context->VoidPtrTy, 0,
4474 /*BitWidth=*/0, /*Mutable=*/true);
4475 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004476 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004477
4478
4479
Steve Naroffdf8570d2009-02-02 17:19:26 +00004480 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004481 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4482 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004483 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004484 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004485}
4486
Steve Naroffb2f9e512008-11-03 23:29:32 +00004487void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4488 SourceLocation LocStart = CE->getLParenLoc();
4489 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004490
4491 // Need to avoid trying to rewrite synthesized casts.
4492 if (LocStart.isInvalid())
4493 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004494 // Need to avoid trying to rewrite casts contained in macros.
4495 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4496 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004497
Steve Naroff54055232008-10-27 17:20:55 +00004498 const char *startBuf = SM->getCharacterData(LocStart);
4499 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004500 QualType QT = CE->getType();
4501 const Type* TypePtr = QT->getAs<Type>();
4502 if (isa<TypeOfExprType>(TypePtr)) {
4503 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4504 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4505 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004506 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004507 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004508 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004509 return;
4510 }
Steve Naroff54055232008-10-27 17:20:55 +00004511 // advance the location to startArgList.
4512 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004513
Steve Naroff54055232008-10-27 17:20:55 +00004514 while (*argPtr++ && (argPtr < endBuf)) {
4515 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004516 case '^':
4517 // Replace the '^' with '*'.
4518 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004519 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004520 break;
Steve Naroff54055232008-10-27 17:20:55 +00004521 }
4522 }
4523 return;
4524}
4525
4526void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4527 SourceLocation DeclLoc = FD->getLocation();
4528 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Steve Naroff54055232008-10-27 17:20:55 +00004530 // We have 1 or more arguments that have closure pointers.
4531 const char *startBuf = SM->getCharacterData(DeclLoc);
4532 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Steve Naroff54055232008-10-27 17:20:55 +00004534 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Steve Naroff54055232008-10-27 17:20:55 +00004536 parenCount++;
4537 // advance the location to startArgList.
4538 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4539 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004540
Steve Naroff54055232008-10-27 17:20:55 +00004541 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004542
Steve Naroff54055232008-10-27 17:20:55 +00004543 while (*argPtr++ && parenCount) {
4544 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004545 case '^':
4546 // Replace the '^' with '*'.
4547 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004548 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004549 break;
4550 case '(':
4551 parenCount++;
4552 break;
4553 case ')':
4554 parenCount--;
4555 break;
Steve Naroff54055232008-10-27 17:20:55 +00004556 }
4557 }
4558 return;
4559}
4560
4561bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004562 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004563 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004564 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004565 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004566 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004567 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004568 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004569 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004570 }
4571 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004572 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004573 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004574 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004575 return true;
4576 }
4577 return false;
4578}
4579
Ted Kremenek8189cde2009-02-07 01:47:29 +00004580void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4581 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004582 const char *argPtr = strchr(Name, '(');
4583 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004584
Steve Naroff54055232008-10-27 17:20:55 +00004585 LParen = argPtr; // output the start.
4586 argPtr++; // skip past the left paren.
4587 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004588
Steve Naroff54055232008-10-27 17:20:55 +00004589 while (*argPtr && parenCount) {
4590 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004591 case '(': parenCount++; break;
4592 case ')': parenCount--; break;
4593 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004594 }
4595 if (parenCount) argPtr++;
4596 }
4597 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4598 RParen = argPtr; // output the end
4599}
4600
4601void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4602 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4603 RewriteBlockPointerFunctionArgs(FD);
4604 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004605 }
Steve Naroff54055232008-10-27 17:20:55 +00004606 // Handle Variables and Typedefs.
4607 SourceLocation DeclLoc = ND->getLocation();
4608 QualType DeclT;
4609 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4610 DeclT = VD->getType();
4611 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4612 DeclT = TDD->getUnderlyingType();
4613 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4614 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004615 else
Steve Naroff54055232008-10-27 17:20:55 +00004616 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004617
Steve Naroff54055232008-10-27 17:20:55 +00004618 const char *startBuf = SM->getCharacterData(DeclLoc);
4619 const char *endBuf = startBuf;
4620 // scan backward (from the decl location) for the end of the previous decl.
4621 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4622 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004623
Steve Naroff54055232008-10-27 17:20:55 +00004624 // *startBuf != '^' if we are dealing with a pointer to function that
4625 // may take block argument types (which will be handled below).
4626 if (*startBuf == '^') {
4627 // Replace the '^' with '*', computing a negative offset.
4628 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004629 ReplaceText(DeclLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004630 }
4631 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4632 // Replace the '^' with '*' for arguments.
4633 DeclLoc = ND->getLocation();
4634 startBuf = SM->getCharacterData(DeclLoc);
4635 const char *argListBegin, *argListEnd;
4636 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4637 while (argListBegin < argListEnd) {
4638 if (*argListBegin == '^') {
4639 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004640 ReplaceText(CaretLoc, 1, "*");
Steve Naroff54055232008-10-27 17:20:55 +00004641 }
4642 argListBegin++;
4643 }
4644 }
4645 return;
4646}
4647
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004648
4649/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4650/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4651/// struct Block_byref_id_object *src) {
4652/// _Block_object_assign (&_dest->object, _src->object,
4653/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4654/// [|BLOCK_FIELD_IS_WEAK]) // object
4655/// _Block_object_assign(&_dest->object, _src->object,
4656/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4657/// [|BLOCK_FIELD_IS_WEAK]) // block
4658/// }
4659/// And:
4660/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4661/// _Block_object_dispose(_src->object,
4662/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4663/// [|BLOCK_FIELD_IS_WEAK]) // object
4664/// _Block_object_dispose(_src->object,
4665/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4666/// [|BLOCK_FIELD_IS_WEAK]) // block
4667/// }
4668
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004669std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4670 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004671 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004672 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004673 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004674 CopyDestroyCache.insert(flag);
4675 S = "static void __Block_byref_id_object_copy_";
4676 S += utostr(flag);
4677 S += "(void *dst, void *src) {\n";
4678
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004679 // offset into the object pointer is computed as:
4680 // void * + void* + int + int + void* + void *
4681 unsigned IntSize =
4682 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4683 unsigned VoidPtrSize =
4684 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4685
4686 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4687 S += " _Block_object_assign((char*)dst + ";
4688 S += utostr(offset);
4689 S += ", *(void * *) ((char*)src + ";
4690 S += utostr(offset);
4691 S += "), ";
4692 S += utostr(flag);
4693 S += ");\n}\n";
4694
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004695 S += "static void __Block_byref_id_object_dispose_";
4696 S += utostr(flag);
4697 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004698 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4699 S += utostr(offset);
4700 S += "), ";
4701 S += utostr(flag);
4702 S += ");\n}\n";
4703 return S;
4704}
4705
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004706/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4707/// the declaration into:
4708/// struct __Block_byref_ND {
4709/// void *__isa; // NULL for everything except __weak pointers
4710/// struct __Block_byref_ND *__forwarding;
4711/// int32_t __flags;
4712/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004713/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4714/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004715/// typex ND;
4716/// };
4717///
4718/// It then replaces declaration of ND variable with:
4719/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4720/// __size=sizeof(struct __Block_byref_ND),
4721/// ND=initializer-if-any};
4722///
4723///
4724void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004725 // Insert declaration for the function in which block literal is
4726 // used.
4727 if (CurFunctionDeclToDeclareForBlock)
4728 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004729 int flag = 0;
4730 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004731 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4732 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004733 SourceLocation X = ND->getLocEnd();
4734 X = SM->getInstantiationLoc(X);
4735 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004736 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004737 std::string ByrefType;
4738 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004739 ByrefType += " {\n";
4740 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004741 RewriteByRefString(ByrefType, Name, ND);
4742 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004743 ByrefType += " int __flags;\n";
4744 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004745 // Add void *__Block_byref_id_object_copy;
4746 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004747 QualType Ty = ND->getType();
4748 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4749 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004750 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4751 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004752 }
4753
4754 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004755 ByrefType += " " + Name + ";\n";
4756 ByrefType += "};\n";
4757 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004758 SourceLocation FunLocStart;
4759 if (CurFunctionDef)
4760 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4761 else {
4762 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4763 FunLocStart = CurMethodDef->getLocStart();
4764 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004765 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004766 if (Ty.isObjCGCWeak()) {
4767 flag |= BLOCK_FIELD_IS_WEAK;
4768 isa = 1;
4769 }
4770
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004771 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004772 flag = BLOCK_BYREF_CALLER;
4773 QualType Ty = ND->getType();
4774 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4775 if (Ty->isBlockPointerType())
4776 flag |= BLOCK_FIELD_IS_BLOCK;
4777 else
4778 flag |= BLOCK_FIELD_IS_OBJECT;
4779 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004780 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004781 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004782 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004783
4784 // struct __Block_byref_ND ND =
4785 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4786 // initializer-if-any};
4787 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004788 unsigned flags = 0;
4789 if (HasCopyAndDispose)
4790 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004791 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004792 ByrefType.clear();
4793 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004794 std::string ForwardingCastType("(");
4795 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004796 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004797 ByrefType += " " + Name + " = {(void*)";
4798 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004799 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004800 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004801 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004802 ByrefType += "sizeof(";
4803 RewriteByRefString(ByrefType, Name, ND);
4804 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004805 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004806 ByrefType += ", __Block_byref_id_object_copy_";
4807 ByrefType += utostr(flag);
4808 ByrefType += ", __Block_byref_id_object_dispose_";
4809 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004810 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004811 ByrefType += "};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004812 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(), ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004813 }
4814 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004815 SourceLocation startLoc;
4816 Expr *E = ND->getInit();
4817 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4818 startLoc = ECE->getLParenLoc();
4819 else
4820 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004821 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004822 endBuf = SM->getCharacterData(startLoc);
4823
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004824 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004825 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004826 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004827 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004828 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004829 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004830 ByrefType += "sizeof(";
4831 RewriteByRefString(ByrefType, Name, ND);
4832 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004833 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004834 ByrefType += "__Block_byref_id_object_copy_";
4835 ByrefType += utostr(flag);
4836 ByrefType += ", __Block_byref_id_object_dispose_";
4837 ByrefType += utostr(flag);
4838 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004839 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004840 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004841
4842 // Complete the newly synthesized compound expression by inserting a right
4843 // curly brace before the end of the declaration.
4844 // FIXME: This approach avoids rewriting the initializer expression. It
4845 // also assumes there is only one declarator. For example, the following
4846 // isn't currently supported by this routine (in general):
4847 //
4848 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4849 //
4850 const char *startBuf = SM->getCharacterData(startLoc);
4851 const char *semiBuf = strchr(startBuf, ';');
4852 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4853 SourceLocation semiLoc =
4854 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4855
Benjamin Kramerd999b372010-02-14 14:14:16 +00004856 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004857 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004858 return;
4859}
4860
Mike Stump1eb44332009-09-09 15:08:12 +00004861void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004862 // Add initializers for any closure decl refs.
4863 GetBlockDeclRefExprs(Exp->getBody());
4864 if (BlockDeclRefs.size()) {
4865 // Unique all "by copy" declarations.
4866 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004867 if (!BlockDeclRefs[i]->isByRef()) {
4868 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4869 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4870 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4871 }
4872 }
Steve Naroff54055232008-10-27 17:20:55 +00004873 // Unique all "by ref" declarations.
4874 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4875 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004876 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4877 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4878 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4879 }
Steve Naroff54055232008-10-27 17:20:55 +00004880 }
4881 // Find any imported blocks...they will need special attention.
4882 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004883 if (BlockDeclRefs[i]->isByRef() ||
4884 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4885 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004886 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004887 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4888 }
4889 }
4890}
4891
Steve Narofffa15fd92008-10-28 20:29:00 +00004892FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4893 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004894 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004895 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004896 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004897 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004898}
4899
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004900Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4901 const llvm::SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004902 Blocks.push_back(Exp);
4903
4904 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004905
4906 // Add inner imported variables now used in current block.
4907 int countOfInnerDecls = 0;
4908 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4909 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4910 ValueDecl *VD = Exp->getDecl();
4911 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4912 // We need to save the copied-in variables in nested
4913 // blocks because it is needed at the end for some of the API generations.
4914 // See SynthesizeBlockLiterals routine.
4915 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4916 BlockDeclRefs.push_back(Exp);
4917 BlockByCopyDeclsPtrSet.insert(VD);
4918 BlockByCopyDecls.push_back(VD);
4919 if (Exp->getType()->isObjCObjectPointerType() ||
4920 Exp->getType()->isBlockPointerType()) {
4921 GetBlockCallExprs(Exp);
4922 ImportedBlockDecls.insert(VD);
4923 }
4924 }
4925 }
4926 InnerDeclRefsCount.push_back(countOfInnerDecls);
4927
Steve Narofffa15fd92008-10-28 20:29:00 +00004928 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Steve Narofffa15fd92008-10-28 20:29:00 +00004930 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004931 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004932 else if (CurMethodDef)
4933 BuildUniqueMethodName(FuncName, CurMethodDef);
4934 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004935 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Steve Narofffa15fd92008-10-28 20:29:00 +00004937 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Steve Narofffa15fd92008-10-28 20:29:00 +00004939 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4940 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Steve Narofffa15fd92008-10-28 20:29:00 +00004942 // Get a pointer to the function type so we can cast appropriately.
4943 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4944
4945 FunctionDecl *FD;
4946 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 // Simulate a contructor call...
4949 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004950 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004951
Steve Narofffa15fd92008-10-28 20:29:00 +00004952 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Steve Narofffdc03722008-10-29 21:23:59 +00004954 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004955 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004956 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4957 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004958 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4959 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004960 InitExprs.push_back(castExpr);
4961
Steve Naroff01aec112009-12-06 21:14:13 +00004962 // Initialize the block descriptor.
4963 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004964
Steve Naroff01aec112009-12-06 21:14:13 +00004965 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4966 &Context->Idents.get(DescData.c_str()),
4967 Context->VoidPtrTy, 0,
4968 VarDecl::Static);
4969 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4970 new (Context) DeclRefExpr(NewVD,
4971 Context->VoidPtrTy, SourceLocation()),
4972 UnaryOperator::AddrOf,
4973 Context->getPointerType(Context->VoidPtrTy),
4974 SourceLocation());
4975 InitExprs.push_back(DescRefExpr);
4976
Steve Narofffa15fd92008-10-28 20:29:00 +00004977 // Add initializers for any closure decl refs.
4978 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004979 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004980 // Output all "by copy" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004981 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004982 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004983 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004984 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004985 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004986 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004987 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004988 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004989 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004990 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4991 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004992 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004993 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004994 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004995 }
Mike Stump1eb44332009-09-09 15:08:12 +00004996 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004997 }
4998 // Output all "by ref" declarations.
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004999 for (llvm::SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005000 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005001 ValueDecl *ND = (*I);
5002 std::string Name(ND->getNameAsString());
5003 std::string RecName;
5004 RewriteByRefString(RecName, Name, ND);
5005 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5006 + sizeof("struct"));
5007 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
5008 SourceLocation(), II);
5009 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5010 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5011
Chris Lattner8ec03f52008-11-24 03:54:41 +00005012 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005013 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
5014 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005015 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00005016 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005017 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005018 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005019 }
5020 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005021 if (ImportedBlockDecls.size()) {
5022 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5023 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005024 unsigned IntSize =
5025 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00005026 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
5027 Context->IntTy, SourceLocation());
5028 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005029 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005030 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5031 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00005032 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005033 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00005034 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005035 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
5036 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005037 BlockDeclRefs.clear();
5038 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005039 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005040 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005041 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005042 ImportedBlockDecls.clear();
5043 return NewRep;
5044}
5045
5046//===----------------------------------------------------------------------===//
5047// Function Body / Expression rewriting
5048//===----------------------------------------------------------------------===//
5049
Steve Naroffc77a6362008-12-04 16:24:46 +00005050// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5051// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5052// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5053// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5054// Since the rewriter isn't capable of rewriting rewritten code, it's important
5055// we get this right.
5056void RewriteObjC::CollectPropertySetters(Stmt *S) {
5057 // Perform a bottom up traversal of all children.
5058 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5059 CI != E; ++CI)
5060 if (*CI)
5061 CollectPropertySetters(*CI);
5062
5063 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5064 if (BinOp->isAssignmentOp()) {
5065 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
5066 PropSetters[PRE] = BinOp;
5067 }
5068 }
5069}
5070
Steve Narofffa15fd92008-10-28 20:29:00 +00005071Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005072 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005073 isa<DoStmt>(S) || isa<ForStmt>(S))
5074 Stmts.push_back(S);
5075 else if (isa<ObjCForCollectionStmt>(S)) {
5076 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005077 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005078 }
Mike Stump1eb44332009-09-09 15:08:12 +00005079
Steve Narofffa15fd92008-10-28 20:29:00 +00005080 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005081
Steve Narofffa15fd92008-10-28 20:29:00 +00005082 // Perform a bottom up rewrite of all children.
5083 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
5084 CI != E; ++CI)
5085 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005086 Stmt *newStmt;
5087 Stmt *S = (*CI);
5088 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5089 Expr *OldBase = IvarRefExpr->getBase();
5090 bool replaced = false;
5091 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
5092 if (replaced) {
5093 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5094 ReplaceStmt(OldBase, IRE->getBase());
5095 else
5096 ReplaceStmt(S, newStmt);
5097 }
5098 }
5099 else
5100 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00005101 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00005102 *CI = newStmt;
5103 }
Mike Stump1eb44332009-09-09 15:08:12 +00005104
Steve Narofffa15fd92008-10-28 20:29:00 +00005105 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005106 llvm::SmallPtrSet<ValueDecl *, 8> InnerBlockValueDecls;
5107 llvm::SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
5108 GetInnerBlockDeclRefExprs(BE->getBody(),
5109 InnerBlockDeclRefs, InnerBlockValueDecls);
Steve Narofffa15fd92008-10-28 20:29:00 +00005110 // Rewrite the block body in place.
5111 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00005112
Steve Narofffa15fd92008-10-28 20:29:00 +00005113 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00005114 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005115 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005116
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005117 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5118
Steve Narofffa15fd92008-10-28 20:29:00 +00005119 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005120 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005121 return blockTranscribed;
5122 }
5123 // Handle specific things.
5124 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5125 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005126
Steve Naroffc77a6362008-12-04 16:24:46 +00005127 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
5128 BinaryOperator *BinOp = PropSetters[PropRefExpr];
5129 if (BinOp) {
5130 // Because the rewriter doesn't allow us to rewrite rewritten code,
5131 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005132 DisableReplaceStmt = true;
5133 // Save the source range. Even if we disable the replacement, the
5134 // rewritten node will have been inserted into the tree. If the synthesized
5135 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005136 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005137 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5138 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005139 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00005140 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005141 //
5142 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5143 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5144 // to see the original expression). Consider this example:
5145 //
5146 // Foo *obj1, *obj2;
5147 //
5148 // obj1.i = [obj2 rrrr];
5149 //
5150 // 'BinOp' for the previous expression looks like:
5151 //
5152 // (BinaryOperator 0x231ccf0 'int' '='
5153 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5154 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5155 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5156 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5157 //
5158 // 'newStmt' represents the rewritten message expression. For example:
5159 //
5160 // (CallExpr 0x231d300 'id':'struct objc_object *'
5161 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5162 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5163 // (CStyleCastExpr 0x231d220 'void *'
5164 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5165 //
5166 // Note that 'newStmt' is passed to RewritePropertySetter so that it
5167 // can be used as the setter argument. ReplaceStmt() will still 'see'
5168 // the original RHS (since we haven't altered BinOp).
5169 //
Mike Stump1eb44332009-09-09 15:08:12 +00005170 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005171 // node. As a result, we now leak the original AST nodes.
5172 //
Steve Naroffb619d952008-12-09 12:56:34 +00005173 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005174 } else {
5175 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005176 }
5177 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005178 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5179 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005180
Steve Narofffa15fd92008-10-28 20:29:00 +00005181 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5182 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005183
Steve Narofffa15fd92008-10-28 20:29:00 +00005184 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005185#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005186 // Before we rewrite it, put the original message expression in a comment.
5187 SourceLocation startLoc = MessExpr->getLocStart();
5188 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Steve Narofffa15fd92008-10-28 20:29:00 +00005190 const char *startBuf = SM->getCharacterData(startLoc);
5191 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Steve Narofffa15fd92008-10-28 20:29:00 +00005193 std::string messString;
5194 messString += "// ";
5195 messString.append(startBuf, endBuf-startBuf+1);
5196 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005197
5198 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005199 // InsertText(clang::SourceLocation, char const*, unsigned int).
5200 // InsertText(startLoc, messString.c_str(), messString.size());
5201 // Tried this, but it didn't work either...
5202 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005203#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005204 return RewriteMessageExpr(MessExpr);
5205 }
Mike Stump1eb44332009-09-09 15:08:12 +00005206
Steve Narofffa15fd92008-10-28 20:29:00 +00005207 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5208 return RewriteObjCTryStmt(StmtTry);
5209
5210 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5211 return RewriteObjCSynchronizedStmt(StmtTry);
5212
5213 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5214 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005215
Steve Narofffa15fd92008-10-28 20:29:00 +00005216 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5217 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005218
5219 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005220 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005221 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005222 OrigStmtRange.getEnd());
5223 if (BreakStmt *StmtBreakStmt =
5224 dyn_cast<BreakStmt>(S))
5225 return RewriteBreakStmt(StmtBreakStmt);
5226 if (ContinueStmt *StmtContinueStmt =
5227 dyn_cast<ContinueStmt>(S))
5228 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005229
5230 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005231 // and cast exprs.
5232 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5233 // FIXME: What we're doing here is modifying the type-specifier that
5234 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005235 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005236 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5237 // the context of an ObjCForCollectionStmt. For example:
5238 // NSArray *someArray;
5239 // for (id <FooProtocol> index in someArray) ;
5240 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5241 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005242 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005243 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005244
Steve Narofffa15fd92008-10-28 20:29:00 +00005245 // Blocks rewrite rules.
5246 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5247 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005248 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005249 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005250 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005251 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005252 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005253 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005254 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005255 if (VD->hasAttr<BlocksAttr>()) {
5256 static unsigned uniqueByrefDeclCount = 0;
5257 assert(!BlockByRefDeclNo.count(ND) &&
5258 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5259 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005260 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005261 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005262 else
5263 RewriteTypeOfDecl(VD);
5264 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005265 }
5266 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005267 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005269 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005270 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5271 }
5272 }
5273 }
Mike Stump1eb44332009-09-09 15:08:12 +00005274
Steve Narofffa15fd92008-10-28 20:29:00 +00005275 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5276 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005277
5278 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005279 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5280 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005281 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5282 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005283 && "Statement stack mismatch");
5284 Stmts.pop_back();
5285 }
5286 // Handle blocks rewriting.
5287 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5288 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005289 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005290 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005291 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5292 ValueDecl *VD = DRE->getDecl();
5293 if (VD->hasAttr<BlocksAttr>())
5294 return RewriteBlockDeclRefExpr(DRE);
5295 }
5296
Steve Narofffa15fd92008-10-28 20:29:00 +00005297 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005298 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005299 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005300 ReplaceStmt(S, BlockCall);
5301 return BlockCall;
5302 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005303 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005304 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005305 RewriteCastExpr(CE);
5306 }
5307#if 0
5308 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005309 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005310 // Get the new text.
5311 std::string SStr;
5312 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005313 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005314 const std::string &Str = Buf.str();
5315
5316 printf("CAST = %s\n", &Str[0]);
5317 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5318 delete S;
5319 return Replacement;
5320 }
5321#endif
5322 // Return this stmt unmodified.
5323 return S;
5324}
5325
Steve Naroff3d7e7862009-12-05 15:55:59 +00005326void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5327 for (RecordDecl::field_iterator i = RD->field_begin(),
5328 e = RD->field_end(); i != e; ++i) {
5329 FieldDecl *FD = *i;
5330 if (isTopLevelBlockPointerType(FD->getType()))
5331 RewriteBlockPointerDecl(FD);
5332 if (FD->getType()->isObjCQualifiedIdType() ||
5333 FD->getType()->isObjCQualifiedInterfaceType())
5334 RewriteObjCQualifiedInterfaceTypes(FD);
5335 }
5336}
5337
Steve Narofffa15fd92008-10-28 20:29:00 +00005338/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5339/// main file of the input.
5340void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5341 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005342 if (FD->isOverloadedOperator())
5343 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005344
Steve Narofffa15fd92008-10-28 20:29:00 +00005345 // Since function prototypes don't have ParmDecl's, we check the function
5346 // prototype. This enables us to rewrite function declarations and
5347 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005348 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005349
Sebastian Redld3a413d2009-04-26 20:35:05 +00005350 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005351 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005352 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005353 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005354 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005355 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005356 Body =
5357 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5358 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005359 CurrentBody = 0;
5360 if (PropParentMap) {
5361 delete PropParentMap;
5362 PropParentMap = 0;
5363 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005364 // This synthesizes and inserts the block "impl" struct, invoke function,
5365 // and any copy/dispose helper functions.
5366 InsertBlockLiteralsWithinFunction(FD);
5367 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005368 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005369 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 return;
5371 }
5372 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005373 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005374 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005375 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005376 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005377 Body =
5378 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5379 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005380 CurrentBody = 0;
5381 if (PropParentMap) {
5382 delete PropParentMap;
5383 PropParentMap = 0;
5384 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005385 InsertBlockLiteralsWithinMethod(MD);
5386 CurMethodDef = 0;
5387 }
5388 }
5389 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5390 ClassImplementation.push_back(CI);
5391 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5392 CategoryImplementation.push_back(CI);
5393 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5394 RewriteForwardClassDecl(CD);
5395 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5396 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005397 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005398 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005399 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005400 CheckFunctionPointerDecl(VD->getType(), VD);
5401 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005402 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005403 RewriteCastExpr(CE);
5404 }
5405 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005406 } else if (VD->getType()->isRecordType()) {
5407 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5408 if (RD->isDefinition())
5409 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005410 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005411 if (VD->getInit()) {
5412 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005413 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005414 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005415 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005416 CurrentBody = 0;
5417 if (PropParentMap) {
5418 delete PropParentMap;
5419 PropParentMap = 0;
5420 }
Mike Stump1eb44332009-09-09 15:08:12 +00005421 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005422 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005423 GlobalVarDecl = 0;
5424
5425 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005426 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005427 RewriteCastExpr(CE);
5428 }
5429 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005430 return;
5431 }
5432 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005433 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005434 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005435 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005436 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5437 return;
5438 }
5439 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005440 if (RD->isDefinition())
5441 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005442 return;
5443 }
5444 // Nothing yet.
5445}
5446
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005447void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005448 if (Diags.hasErrorOccurred())
5449 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005450
Steve Narofffa15fd92008-10-28 20:29:00 +00005451 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005452
Steve Naroff621edce2009-04-29 16:37:50 +00005453 // Here's a great place to add any extra declarations that may be needed.
5454 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005455 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005456 E = ProtocolExprDecls.end(); I != E; ++I)
5457 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5458
Benjamin Kramerd999b372010-02-14 14:14:16 +00005459 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005460 if (ClassImplementation.size() || CategoryImplementation.size())
5461 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005462
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5464 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005465 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 Rewrite.getRewriteBufferFor(MainFileID)) {
5467 //printf("Changed:\n");
5468 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5469 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005470 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005471 }
Steve Narofface66252008-11-13 20:07:04 +00005472
Steve Naroff621edce2009-04-29 16:37:50 +00005473 if (ClassImplementation.size() || CategoryImplementation.size() ||
5474 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005475 // Rewrite Objective-c meta data*
5476 std::string ResultStr;
5477 SynthesizeMetaDataIntoBuffer(ResultStr);
5478 // Emit metadata.
5479 *OutFile << ResultStr;
5480 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005481 OutFile->flush();
5482}
5483