blob: c0ad799c5a966836a096f89ff4095245c3a72c1c [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;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroffc77a6362008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Steve Naroff4c3580e2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000144
Steve Naroff54055232008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000152 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000175
Steve Naroffb619d952008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff4c3580e2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
180 if (!Rewrite.ReplaceStmt(Old, New)) {
181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000188 }
Steve Naroffb619d952008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroffba92b2e2008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattneraadaf782008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Steve Naroff8599e7a2008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner3b2c58c2008-05-23 20:40:52 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroffc77a6362008-12-04 16:24:46 +0000282 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000283 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000284 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000285 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000286 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000287 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000288 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000289 void WarnAboutReturnGotoStmts(Stmt *S);
290 void HasReturnStmts(Stmt *S, bool &hasReturns);
291 void RewriteTryReturnStmts(Stmt *S);
292 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000293 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000294 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
296 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
297 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000298 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
299 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000300 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000301 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000302 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000303 Stmt *RewriteBreakStmt(BreakStmt *S);
304 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000305 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Steve Naroff09b266e2007-10-30 23:14:51 +0000307 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000308 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000309 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000310 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000311 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000312 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000313 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000314 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000315 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Chris Lattnerf04da132007-10-24 17:06:59 +0000317 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000318 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000319 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000321 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000322 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Douglas Gregor653f1b12009-04-23 01:02:12 +0000324 template<typename MethodIterator>
325 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
326 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000327 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000328 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000329 const char *ClassName,
330 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Steve Naroff621edce2009-04-29 16:37:50 +0000332 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
333 const char *prefix,
334 const char *ClassName,
335 std::string &Result);
336 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000337 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000338 const char *ClassName,
339 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000340 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000341 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000342 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
343 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000344 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000345 void RewriteImplementations();
346 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff54055232008-10-27 17:20:55 +0000348 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000349 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000350 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Steve Naroff54055232008-10-27 17:20:55 +0000352 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
353 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000354
355 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000356 void RewriteBlockCall(CallExpr *Exp);
357 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000358 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000359 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000360 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000361 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
363 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000364 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000367 std::string SynthesizeBlockImpl(BlockExpr *CE,
368 std::string Tag, std::string Desc);
369 std::string SynthesizeBlockDescriptor(std::string DescTag,
370 std::string ImplTag,
371 int i, const char *funcName,
372 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000373 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000374 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000375 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000376 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Steve Naroff54055232008-10-27 17:20:55 +0000378 void CollectBlockDeclRefInfo(BlockExpr *Exp);
379 void GetBlockCallExprs(Stmt *S);
380 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Steve Naroff54055232008-10-27 17:20:55 +0000382 // We avoid calling Type::isBlockPointerType(), since it operates on the
383 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000384 bool isTopLevelBlockPointerType(QualType T) {
385 return isa<BlockPointerType>(T);
386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Steve Naroff54055232008-10-27 17:20:55 +0000388 // FIXME: This predicate seems like it would be useful to add to ASTContext.
389 bool isObjCType(QualType T) {
390 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
396 OCT == Context->getCanonicalType(Context->getObjCClassType()))
397 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Ted Kremenek6217b802009-07-29 21:53:49 +0000399 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000400 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000401 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000402 return true;
403 }
404 return false;
405 }
406 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000407 void GetExtentOfArgList(const char *Name, const char *&LParen,
408 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000409 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Steve Narofffa15fd92008-10-28 20:29:00 +0000411 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000412 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Steve Naroff621edce2009-04-29 16:37:50 +0000414 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000415 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000416 if (From[i] == '"')
417 To += "\\\"";
418 else
419 To += From[i];
420 }
421 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000422 };
John McCall9d125032010-01-15 18:39:57 +0000423
424 // Helper function: create a CStyleCastExpr with trivial type source info.
425 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
426 CastExpr::CastKind Kind, Expr *E) {
427 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
428 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
429 SourceLocation(), SourceLocation());
430 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000431}
432
Mike Stump1eb44332009-09-09 15:08:12 +0000433void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
434 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000435 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000436 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000437 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000438 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000439 // All the args are checked/rewritten. Don't call twice!
440 RewriteBlockPointerDecl(D);
441 break;
442 }
443 }
444}
445
446void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000447 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000448 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000449 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000450}
451
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000452static bool IsHeaderFile(const std::string &Filename) {
453 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000455 if (DotPos == std::string::npos) {
456 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000457 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000460 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
461 // C header: .h
462 // C++ header: .hh or .H;
463 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000464}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000465
Eli Friedman66d6f042009-05-18 22:20:00 +0000466RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000467 Diagnostic &D, const LangOptions &LOpts,
468 bool silenceMacroWarn)
469 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
470 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000471 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000472 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000473 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000474 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000475 "rewriter doesn't support user-specified control flow semantics "
476 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000477}
478
Eli Friedmanbce831b2009-05-18 22:29:17 +0000479ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
480 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000481 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000482 const LangOptions &LOpts,
483 bool SilenceRewriteMacroWarning) {
484 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000485}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000486
Steve Naroffb29b4272008-04-14 22:03:09 +0000487void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000488 Context = &context;
489 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000490 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000491 MsgSendFunctionDecl = 0;
492 MsgSendSuperFunctionDecl = 0;
493 MsgSendStretFunctionDecl = 0;
494 MsgSendSuperStretFunctionDecl = 0;
495 MsgSendFpretFunctionDecl = 0;
496 GetClassFunctionDecl = 0;
497 GetMetaClassFunctionDecl = 0;
498 SelGetUidFunctionDecl = 0;
499 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000500 ConstantStringClassReference = 0;
501 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000502 CurMethodDef = 0;
503 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000504 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000505 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000506 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000507 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000508 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000509 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000510 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000511 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000512 PropParentMap = 0;
513 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000514 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000515 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000517 // Get the ID and start/end of the main file.
518 MainFileID = SM->getMainFileID();
519 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
520 MainFileStart = MainBuf->getBufferStart();
521 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner2c78b872009-04-14 23:22:57 +0000523 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000525 // declaring objc_selector outside the parameter list removes a silly
526 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000527 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000528 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000530 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000532 if (LangOpts.Microsoft) {
533 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000534 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
535 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000536 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000537 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000538 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000539 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
540 Preamble += "typedef struct objc_object Protocol;\n";
541 Preamble += "#define _REWRITER_typedef_Protocol\n";
542 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000543 if (LangOpts.Microsoft) {
544 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
545 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
546 } else
547 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
548 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000549 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000555 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
563 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000567 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000568 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000569 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
571 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000572 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
573 Preamble += "struct __objcFastEnumerationState {\n\t";
574 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000575 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000576 Preamble += "unsigned long *mutationsPtr;\n\t";
577 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000578 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 Preamble += "#define __FASTENUMERATIONSTATE\n";
580 Preamble += "#endif\n";
581 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
582 Preamble += "struct __NSConstantStringImpl {\n";
583 Preamble += " int *isa;\n";
584 Preamble += " int flags;\n";
585 Preamble += " char *str;\n";
586 Preamble += " long length;\n";
587 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000588 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
589 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
590 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000591 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000592 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
594 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000595 // Blocks preamble.
596 Preamble += "#ifndef BLOCK_IMPL\n";
597 Preamble += "#define BLOCK_IMPL\n";
598 Preamble += "struct __block_impl {\n";
599 Preamble += " void *isa;\n";
600 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000601 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000602 Preamble += " void *FuncPtr;\n";
603 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000604 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000605 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000606 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
607 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
608 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
610 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000611 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
612 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
615 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000616 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000617 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000618 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
619 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000620 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000621 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000622 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000623 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000624 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000625 Preamble += "#define __weak\n";
626 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000627}
628
629
Chris Lattnerf04da132007-10-24 17:06:59 +0000630//===----------------------------------------------------------------------===//
631// Top Level Driver Code
632//===----------------------------------------------------------------------===//
633
Chris Lattner682bf922009-03-29 16:50:03 +0000634void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000635 // Two cases: either the decl could be in the main file, or it could be in a
636 // #included file. If the former, rewrite it now. If the later, check to see
637 // if we rewrote the #include/#import.
638 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000639 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000641 // If this is for a builtin, ignore it.
642 if (Loc.isInvalid()) return;
643
Steve Naroffebf2b562007-10-23 23:50:29 +0000644 // Look for built-in declarations that we need to refer during the rewrite.
645 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000646 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000647 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000648 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000649 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000650 ConstantStringClassReference = FVD;
651 return;
652 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000653 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000654 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000656 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000658 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000659 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000660 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000661 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000662 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
663 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000664 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
665 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000666 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000667 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000668 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000669 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000670 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000671 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000672}
673
Chris Lattnerf04da132007-10-24 17:06:59 +0000674//===----------------------------------------------------------------------===//
675// Syntactic (non-AST) Rewriting Code
676//===----------------------------------------------------------------------===//
677
Steve Naroffb29b4272008-04-14 22:03:09 +0000678void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000679 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000680 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
681 const char *MainBufStart = MainBuf.first;
682 const char *MainBufEnd = MainBuf.second;
683 size_t ImportLen = strlen("import");
684 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000686 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000687 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
688 if (*BufPtr == '#') {
689 if (++BufPtr == MainBufEnd)
690 return;
691 while (*BufPtr == ' ' || *BufPtr == '\t')
692 if (++BufPtr == MainBufEnd)
693 return;
694 if (!strncmp(BufPtr, "import", ImportLen)) {
695 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000696 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000697 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000698 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000699 BufPtr += ImportLen;
700 }
701 }
702 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000703}
704
Steve Naroffb29b4272008-04-14 22:03:09 +0000705void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000706 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
707 const char *MainBufStart = MainBuf.first;
708 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattnerf04da132007-10-24 17:06:59 +0000710 // Loop over the whole file, looking for tabs.
711 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
712 if (*BufPtr != '\t')
713 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000714
Chris Lattnerf04da132007-10-24 17:06:59 +0000715 // Okay, we found a tab. This tab will turn into at least one character,
716 // but it depends on which 'virtual column' it is in. Compute that now.
717 unsigned VCol = 0;
718 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
719 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
720 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattnerf04da132007-10-24 17:06:59 +0000722 // Okay, now that we know the virtual column, we know how many spaces to
723 // insert. We assume 8-character tab-stops.
724 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
Chris Lattnerf04da132007-10-24 17:06:59 +0000726 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000727 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
728 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Chris Lattnerf04da132007-10-24 17:06:59 +0000730 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000731 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000733}
734
Steve Naroffeb0646c2008-12-02 15:48:25 +0000735static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
736 ObjCIvarDecl *OID) {
737 std::string S;
738 S = "((struct ";
739 S += ClassDecl->getIdentifier()->getName();
740 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000741 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000742 return S;
743}
744
Steve Naroffa0876e82008-12-02 17:36:43 +0000745void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
746 ObjCImplementationDecl *IMD,
747 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000748 SourceLocation startLoc = PID->getLocStart();
749 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000750 const char *startBuf = SM->getCharacterData(startLoc);
751 assert((*startBuf == '@') && "bogus @synthesize location");
752 const char *semiBuf = strchr(startBuf, ';');
753 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000754 SourceLocation onePastSemiLoc =
755 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000756
757 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
758 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Steve Naroffeb0646c2008-12-02 15:48:25 +0000760 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000761 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000765 if (!OID)
766 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000768 std::string Getr;
769 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
770 Getr += "{ ";
771 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000772 // FIXME: deal with code generation implications for various property
773 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000774 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000775 Getr += "return " + getIvarAccessString(ClassDecl, OID);
776 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000777 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000778 if (PD->isReadOnly())
779 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Steve Naroffeb0646c2008-12-02 15:48:25 +0000781 // Generate the 'setter' function.
782 std::string Setr;
783 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000785 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000786 // FIXME: deal with code generation implications for various property
787 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000788 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000789 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000790 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000792 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000793}
Chris Lattner8a12c272007-10-11 18:38:32 +0000794
Steve Naroffb29b4272008-04-14 22:03:09 +0000795void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000796 // Get the start location and compute the semi location.
797 SourceLocation startLoc = ClassDecl->getLocation();
798 const char *startBuf = SM->getCharacterData(startLoc);
799 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Chris Lattnerf04da132007-10-24 17:06:59 +0000801 // Translate to typedef's that forward reference structs with the same name
802 // as the class. As a convenience, we include the original declaration
803 // as a comment.
804 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000805 typedefString += "// @class ";
806 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
807 I != E; ++I) {
808 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
809 typedefString += ForwardDecl->getNameAsString();
810 if (I+1 != E)
811 typedefString += ", ";
812 else
813 typedefString += ";\n";
814 }
815
Chris Lattner67956052009-02-20 18:04:31 +0000816 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
817 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000818 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000819 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000820 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000821 typedefString += "\n";
822 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000823 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000824 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000825 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000826 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000827 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000828 }
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Steve Naroff934f2762007-10-24 22:48:43 +0000830 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000831 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000832 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000833}
834
Steve Naroffb29b4272008-04-14 22:03:09 +0000835void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000836 SourceLocation LocStart = Method->getLocStart();
837 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Chris Lattner30fc9332009-02-04 01:06:56 +0000839 if (SM->getInstantiationLineNumber(LocEnd) >
840 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000841 InsertText(LocStart, "#if 0\n", 6);
842 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000843 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000844 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000845 }
846}
847
Mike Stump1eb44332009-09-09 15:08:12 +0000848void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff6327e0d2009-01-11 01:06:09 +0000849 SourceLocation Loc = prop->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Steve Naroff6327e0d2009-01-11 01:06:09 +0000851 ReplaceText(Loc, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Steve Naroff6327e0d2009-01-11 01:06:09 +0000853 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000854}
855
Steve Naroffb29b4272008-04-14 22:03:09 +0000856void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000857 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Steve Naroff423cb562007-10-30 13:30:57 +0000859 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000860 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000861
862 for (ObjCCategoryDecl::instmeth_iterator
863 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000864 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000865 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000866 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000867 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000868 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000869 RewriteMethodDeclaration(*I);
870
Steve Naroff423cb562007-10-30 13:30:57 +0000871 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000872 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000873}
874
Steve Naroffb29b4272008-04-14 22:03:09 +0000875void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000876 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000877
Steve Naroff752d6ef2007-10-30 16:42:30 +0000878 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Steve Naroff752d6ef2007-10-30 16:42:30 +0000880 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000881 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
883 for (ObjCProtocolDecl::instmeth_iterator
884 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000885 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000886 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000887 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000888 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000889 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000890 RewriteMethodDeclaration(*I);
891
Steve Naroff752d6ef2007-10-30 16:42:30 +0000892 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000893 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000894 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000895
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000896 // Must comment out @optional/@required
897 const char *startBuf = SM->getCharacterData(LocStart);
898 const char *endBuf = SM->getCharacterData(LocEnd);
899 for (const char *p = startBuf; p < endBuf; p++) {
900 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
901 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000902 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000903 ReplaceText(OptionalLoc, strlen("@optional"),
904 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000906 }
907 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
908 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000909 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000910 ReplaceText(OptionalLoc, strlen("@required"),
911 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000912
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000913 }
914 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000915}
916
Steve Naroffb29b4272008-04-14 22:03:09 +0000917void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000918 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000919 if (LocStart.isInvalid())
920 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000921 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000922 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000923}
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000926 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000927 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000928 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000929 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000930 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000931 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000932 else if (OMD->getResultType()->isFunctionPointerType() ||
933 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000934 // needs special handling, since pointer-to-functions have special
935 // syntax (where a decaration models use).
936 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000937 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000938 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000939 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000940 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000941 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000942 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000943 ResultStr += FPRetType->getResultType().getAsString();
944 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000945 }
946 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000947 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000948 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000950 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000951 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000953 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000954 NameStr += "_I_";
955 else
956 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000958 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000959 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000960
961 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000962 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000963 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000964 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000967 {
968 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000969 int len = selString.size();
970 for (int i = 0; i < len; i++)
971 if (selString[i] == ':')
972 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000973 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000975 // Remember this name for metadata emission
976 MethodInternalNames[OMD] = NameStr;
977 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979 // Rewrite arguments
980 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000982 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000983 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000984 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000985 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000986 if (!LangOpts.Microsoft) {
987 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
988 ResultStr += "struct ";
989 }
990 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000991 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000992 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000993 }
994 else
Steve Naroff621edce2009-04-29 16:37:50 +0000995 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000997 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000998 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000999 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001001 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001002 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1003 E = OMD->param_end(); PI != E; ++PI) {
1004 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001005 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001006 if (PDecl->getType()->isObjCQualifiedIdType()) {
1007 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001008 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001009 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001010 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001011 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001012 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001013 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001014 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1015 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001016 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001017 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001018 ResultStr += Name;
1019 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001020 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001021 if (OMD->isVariadic())
1022 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001023 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Steve Naroff76e429d2008-07-16 14:40:40 +00001025 if (FPRetType) {
1026 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Steve Naroff76e429d2008-07-16 14:40:40 +00001028 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001029 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001030 ResultStr += "(";
1031 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1032 if (i) ResultStr += ", ";
1033 std::string ParamStr = FT->getArgType(i).getAsString();
1034 ResultStr += ParamStr;
1035 }
1036 if (FT->isVariadic()) {
1037 if (FT->getNumArgs()) ResultStr += ", ";
1038 ResultStr += "...";
1039 }
1040 ResultStr += ")";
1041 } else {
1042 ResultStr += "()";
1043 }
1044 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001045}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001046void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001047 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1048 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001050 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001051 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001052 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001053 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001055 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001056 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1057 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001058 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001059 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001060 ObjCMethodDecl *OMD = *I;
1061 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001062 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001063 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001064
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001065 const char *startBuf = SM->getCharacterData(LocStart);
1066 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001067 ReplaceText(LocStart, endBuf-startBuf,
1068 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001069 }
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001071 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001072 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1073 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001074 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001075 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001076 ObjCMethodDecl *OMD = *I;
1077 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001078 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001079 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 const char *startBuf = SM->getCharacterData(LocStart);
1082 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001083 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001084 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001085 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001086 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001087 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001088 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001089 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001090 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001091 }
1092
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001093 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001094 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001095 else
Mike Stump1eb44332009-09-09 15:08:12 +00001096 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001097}
1098
Steve Naroffb29b4272008-04-14 22:03:09 +00001099void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001100 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001101 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001102 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001103 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001104 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001105 ResultStr += "\n";
1106 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001107 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001108 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001109 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001110 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001111 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001112 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001113 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001114 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001115 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001116
1117 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001118 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001119 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001120 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001121 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001122 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001123 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001124 for (ObjCInterfaceDecl::classmeth_iterator
1125 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001126 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001127 RewriteMethodDeclaration(*I);
1128
Steve Naroff2feac5e2007-10-30 03:43:13 +00001129 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001130 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001131}
1132
Steve Naroffb619d952008-12-09 12:56:34 +00001133Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1134 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001135 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1136 // This allows us to reuse all the fun and games in SynthMessageExpr().
1137 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1138 ObjCMessageExpr *MsgExpr;
1139 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1140 llvm::SmallVector<Expr *, 1> ExprVec;
1141 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Steve Naroff8599e7a2008-12-08 16:43:47 +00001143 Stmt *Receiver = PropRefExpr->getBase();
1144 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1145 if (PRE && PropGetters[PRE]) {
1146 // This allows us to handle chain/nested property getters.
1147 Receiver = PropGetters[PRE];
1148 }
Mike Stump1eb44332009-09-09 15:08:12 +00001149 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1150 PDecl->getSetterName(), PDecl->getType(),
1151 PDecl->getSetterMethodDecl(),
1152 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001153 &ExprVec[0], 1);
1154 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Steve Naroffc77a6362008-12-04 16:24:46 +00001156 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001157 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001158 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001159 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1160 // to things that stay around.
1161 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001162 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001163}
1164
Steve Naroffc77a6362008-12-04 16:24:46 +00001165Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001166 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1167 // This allows us to reuse all the fun and games in SynthMessageExpr().
1168 ObjCMessageExpr *MsgExpr;
1169 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Steve Naroff8599e7a2008-12-08 16:43:47 +00001171 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Steve Naroff8599e7a2008-12-08 16:43:47 +00001173 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1174 if (PRE && PropGetters[PRE]) {
1175 // This allows us to handle chain/nested property getters.
1176 Receiver = PropGetters[PRE];
1177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1179 PDecl->getGetterName(), PDecl->getType(),
1180 PDecl->getGetterMethodDecl(),
1181 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001182 0, 0);
1183
Steve Naroff4c3580e2008-12-04 23:50:32 +00001184 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001185
1186 if (!PropParentMap)
1187 PropParentMap = new ParentMap(CurrentBody);
1188
1189 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1190 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1191 // We stash away the ReplacingStmt since actually doing the
1192 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1193 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001194 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1195 // to things that stay around.
1196 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001197 return PropRefExpr; // return the original...
1198 } else {
1199 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001200 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001201 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1202 // to things that stay around.
1203 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001204 return ReplacingStmt;
1205 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001206}
1207
Mike Stump1eb44332009-09-09 15:08:12 +00001208Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001209 SourceLocation OrigStart) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001211 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001212 if (CurMethodDef) {
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001213 if (BaseExpr->getType()->isObjCObjectPointerType() &&
1214 isa<DeclRefExpr>(BaseExpr)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001215 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001216 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Narofff0757612008-05-08 17:52:16 +00001217 // lookup which class implements the instance variable.
1218 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001219 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001220 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001221 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001222
Steve Narofff0757612008-05-08 17:52:16 +00001223 // Synthesize an explicit cast to gain access to the ivar.
1224 std::string RecName = clsDeclared->getIdentifier()->getName();
1225 RecName += "_IMPL";
1226 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001227 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001228 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001229 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1230 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001231 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1232 CastExpr::CK_Unknown,
1233 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001234 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001235 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1236 IV->getBase()->getLocEnd(),
1237 castExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001238 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001239 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001240 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1241 IV->getLocation(),
1242 D->getType());
Steve Narofff0757612008-05-08 17:52:16 +00001243 ReplaceStmt(IV, ME);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001244 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001245 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001246 }
Mike Stump1eb44332009-09-09 15:08:12 +00001247
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001248 ReplaceStmt(IV->getBase(), PE);
1249 // Cannot delete IV->getBase(), since PE points to it.
1250 // Replace the old base with the cast. This is important when doing
1251 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001252 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001253 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001254 }
Steve Naroff84472a82008-04-18 21:55:08 +00001255 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001256 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Steve Naroff9f525972008-05-06 23:20:07 +00001258 // Explicit ivar refs need to have a cast inserted.
1259 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001260 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001261 ObjCInterfaceType *iFaceDecl =
1262 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001263 // lookup which class implements the instance variable.
1264 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001265 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001266 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001267 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Steve Naroff9f525972008-05-06 23:20:07 +00001269 // Synthesize an explicit cast to gain access to the ivar.
1270 std::string RecName = clsDeclared->getIdentifier()->getName();
1271 RecName += "_IMPL";
1272 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001273 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001274 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001275 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1276 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001277 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1278 CastExpr::CK_Unknown,
1279 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001280 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001281 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001282 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff9f525972008-05-06 23:20:07 +00001283 ReplaceStmt(IV->getBase(), PE);
1284 // Cannot delete IV->getBase(), since PE points to it.
1285 // Replace the old base with the cast. This is important when doing
1286 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001287 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001288 return IV;
1289 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001290 }
Steve Naroff84472a82008-04-18 21:55:08 +00001291 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001292}
1293
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001294/// SynthCountByEnumWithState - To print:
1295/// ((unsigned int (*)
1296/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001297/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001298/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001299/// "countByEnumeratingWithState:objects:count:"),
1300/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001301/// (id *)items, (unsigned int)16)
1302///
Steve Naroffb29b4272008-04-14 22:03:09 +00001303void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001304 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1305 "id *, unsigned int))(void *)objc_msgSend)";
1306 buf += "\n\t\t";
1307 buf += "((id)l_collection,\n\t\t";
1308 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1309 buf += "\n\t\t";
1310 buf += "&enumState, "
1311 "(id *)items, (unsigned int)16)";
1312}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001313
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001314/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1315/// statement to exit to its outer synthesized loop.
1316///
Steve Naroffb29b4272008-04-14 22:03:09 +00001317Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001318 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1319 return S;
1320 // replace break with goto __break_label
1321 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001323 SourceLocation startLoc = S->getLocStart();
1324 buf = "goto __break_label_";
1325 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001326 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001327
1328 return 0;
1329}
1330
1331/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1332/// statement to continue with its inner synthesized loop.
1333///
Steve Naroffb29b4272008-04-14 22:03:09 +00001334Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001335 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1336 return S;
1337 // replace continue with goto __continue_label
1338 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001340 SourceLocation startLoc = S->getLocStart();
1341 buf = "goto __continue_label_";
1342 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001343 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001345 return 0;
1346}
1347
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001348/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001349/// It rewrites:
1350/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001352/// Into:
1353/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001354/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001355/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001356/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001357/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001358/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001359/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001360/// if (limit) {
1361/// unsigned long startMutations = *enumState.mutationsPtr;
1362/// do {
1363/// unsigned long counter = 0;
1364/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001365/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001366/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001367/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001368/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001369/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001370/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001371/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001372/// objects:items count:16]);
1373/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001374/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001375/// }
1376/// else
1377/// elem = nil;
1378/// }
1379///
Steve Naroffb29b4272008-04-14 22:03:09 +00001380Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001381 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001382 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001383 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001384 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001385 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001386 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001388 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001389 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001390 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001391 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001392 std::string buf;
1393 buf = "\n{\n\t";
1394 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1395 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001396 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001397 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001398 if (ElementType->isObjCQualifiedIdType() ||
1399 ElementType->isObjCQualifiedInterfaceType())
1400 // Simply use 'id' for all qualified types.
1401 elementTypeAsString = "id";
1402 else
1403 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001404 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001405 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001406 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001407 buf += elementName;
1408 buf += ";\n\t";
1409 }
Chris Lattner06767512008-04-08 05:52:18 +00001410 else {
1411 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001412 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001413 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1414 if (VD->getType()->isObjCQualifiedIdType() ||
1415 VD->getType()->isObjCQualifiedInterfaceType())
1416 // Simply use 'id' for all qualified types.
1417 elementTypeAsString = "id";
1418 else
1419 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001422 // struct __objcFastEnumerationState enumState = { 0 };
1423 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1424 // id items[16];
1425 buf += "id items[16];\n\t";
1426 // id l_collection = (id)
1427 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001428 // Find start location of 'collection' the hard way!
1429 const char *startCollectionBuf = startBuf;
1430 startCollectionBuf += 3; // skip 'for'
1431 startCollectionBuf = strchr(startCollectionBuf, '(');
1432 startCollectionBuf++; // skip '('
1433 // find 'in' and skip it.
1434 while (*startCollectionBuf != ' ' ||
1435 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1436 (*(startCollectionBuf+3) != ' ' &&
1437 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1438 startCollectionBuf++;
1439 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001440
1441 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001442 ReplaceText(startLoc, startCollectionBuf - startBuf,
1443 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001444 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001445 SourceLocation rightParenLoc = S->getRParenLoc();
1446 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1447 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001448 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001450 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1451 // objects:items count:16];
1452 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001453 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001454 // ((unsigned int (*)
1455 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001456 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001457 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // "countByEnumeratingWithState:objects:count:"),
1459 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001460 // (id *)items, (unsigned int)16);
1461 buf += "unsigned long limit =\n\t\t";
1462 SynthCountByEnumWithState(buf);
1463 buf += ";\n\t";
1464 /// if (limit) {
1465 /// unsigned long startMutations = *enumState.mutationsPtr;
1466 /// do {
1467 /// unsigned long counter = 0;
1468 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001469 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001470 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001471 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001472 buf += "if (limit) {\n\t";
1473 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1474 buf += "do {\n\t\t";
1475 buf += "unsigned long counter = 0;\n\t\t";
1476 buf += "do {\n\t\t\t";
1477 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1478 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1479 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001480 buf += " = (";
1481 buf += elementTypeAsString;
1482 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001483 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001484 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001486 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001488 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001489 /// objects:items count:16]);
1490 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001491 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001492 /// }
1493 /// else
1494 /// elem = nil;
1495 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001496 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001497 buf = ";\n\t";
1498 buf += "__continue_label_";
1499 buf += utostr(ObjCBcLabelNo.back());
1500 buf += ": ;";
1501 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001502 buf += "} while (counter < limit);\n\t";
1503 buf += "} while (limit = ";
1504 SynthCountByEnumWithState(buf);
1505 buf += ");\n\t";
1506 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001507 buf += " = ((";
1508 buf += elementTypeAsString;
1509 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001510 buf += "__break_label_";
1511 buf += utostr(ObjCBcLabelNo.back());
1512 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001513 buf += "}\n\t";
1514 buf += "else\n\t\t";
1515 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001516 buf += " = ((";
1517 buf += elementTypeAsString;
1518 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001519 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001522 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001523 if (isa<CompoundStmt>(S->getBody())) {
1524 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1525 InsertText(endBodyLoc, buf.c_str(), buf.size());
1526 } else {
1527 /* Need to treat single statements specially. For example:
1528 *
1529 * for (A *a in b) if (stuff()) break;
1530 * for (A *a in b) xxxyy;
1531 *
1532 * The following code simply scans ahead to the semi to find the actual end.
1533 */
1534 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1535 const char *semiBuf = strchr(stmtBuf, ';');
1536 assert(semiBuf && "Can't find ';'");
1537 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1538 InsertText(endBodyLoc, buf.c_str(), buf.size());
1539 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001540 Stmts.pop_back();
1541 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001542 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001543}
1544
Mike Stump1eb44332009-09-09 15:08:12 +00001545/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001546/// This routine rewrites @synchronized(expr) stmt;
1547/// into:
1548/// objc_sync_enter(expr);
1549/// @try stmt @finally { objc_sync_exit(expr); }
1550///
Steve Naroffb29b4272008-04-14 22:03:09 +00001551Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001552 // Get the start location and compute the semi location.
1553 SourceLocation startLoc = S->getLocStart();
1554 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001556 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001557
1558 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001559 buf = "objc_sync_enter((id)";
1560 const char *lparenBuf = startBuf;
1561 while (*lparenBuf != '(') lparenBuf++;
1562 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001563 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1564 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001565 // been rewritten! (which implies the SourceLocation's are invalid).
1566 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001567 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001568 while (*endBuf != ')') endBuf--;
1569 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001570 buf = ");\n";
1571 // declare a new scope with two variables, _stack and _rethrow.
1572 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1573 buf += "int buf[18/*32-bit i386*/];\n";
1574 buf += "char *pointers[4];} _stack;\n";
1575 buf += "id volatile _rethrow = 0;\n";
1576 buf += "objc_exception_try_enter(&_stack);\n";
1577 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001578 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001579 startLoc = S->getSynchBody()->getLocEnd();
1580 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Steve Naroffc7089f12008-08-19 13:04:19 +00001582 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001583 SourceLocation lastCurlyLoc = startLoc;
1584 buf = "}\nelse {\n";
1585 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001586 buf += "}\n";
1587 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001588 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001589
1590 std::string syncBuf;
1591 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001592 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1593 CastExpr::CK_Unknown,
1594 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001595 std::string syncExprBufS;
1596 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001597 syncExpr->printPretty(syncExprBuf, *Context, 0,
1598 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001599 syncBuf += syncExprBuf.str();
1600 syncBuf += ");";
1601
1602 buf += syncBuf;
1603 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001604 buf += "}\n";
1605 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Chris Lattneraadaf782008-01-31 19:51:04 +00001607 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001608
1609 bool hasReturns = false;
1610 HasReturnStmts(S->getSynchBody(), hasReturns);
1611 if (hasReturns)
1612 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1613
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001614 return 0;
1615}
1616
Steve Naroffb85e77a2009-12-05 21:43:12 +00001617void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1618{
Steve Naroff8c565152008-12-05 17:03:39 +00001619 // Perform a bottom up traversal of all children.
1620 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1621 CI != E; ++CI)
1622 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001623 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001624
Steve Naroffb85e77a2009-12-05 21:43:12 +00001625 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001626 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001627 TryFinallyContainsReturnDiag);
1628 }
1629 return;
1630}
1631
Steve Naroffb85e77a2009-12-05 21:43:12 +00001632void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1633{
1634 // Perform a bottom up traversal of all children.
1635 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1636 CI != E; ++CI)
1637 if (*CI)
1638 HasReturnStmts(*CI, hasReturns);
1639
1640 if (isa<ReturnStmt>(S))
1641 hasReturns = true;
1642 return;
1643}
1644
1645void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1646 // Perform a bottom up traversal of all children.
1647 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1648 CI != E; ++CI)
1649 if (*CI) {
1650 RewriteTryReturnStmts(*CI);
1651 }
1652 if (isa<ReturnStmt>(S)) {
1653 SourceLocation startLoc = S->getLocStart();
1654 const char *startBuf = SM->getCharacterData(startLoc);
1655
1656 const char *semiBuf = strchr(startBuf, ';');
1657 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1658 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1659
1660 std::string buf;
1661 buf = "{ objc_exception_try_exit(&_stack); return";
1662
1663 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1664 InsertText(onePastSemiLoc, "}", 1);
1665 }
1666 return;
1667}
1668
1669void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1670 // Perform a bottom up traversal of all children.
1671 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1672 CI != E; ++CI)
1673 if (*CI) {
1674 RewriteSyncReturnStmts(*CI, syncExitBuf);
1675 }
1676 if (isa<ReturnStmt>(S)) {
1677 SourceLocation startLoc = S->getLocStart();
1678 const char *startBuf = SM->getCharacterData(startLoc);
1679
1680 const char *semiBuf = strchr(startBuf, ';');
1681 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1682 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1683
1684 std::string buf;
1685 buf = "{ objc_exception_try_exit(&_stack);";
1686 buf += syncExitBuf;
1687 buf += " return";
1688
1689 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1690 InsertText(onePastSemiLoc, "}", 1);
1691 }
1692 return;
1693}
1694
Steve Naroffb29b4272008-04-14 22:03:09 +00001695Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001696 // Get the start location and compute the semi location.
1697 SourceLocation startLoc = S->getLocStart();
1698 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001699
Steve Naroff75730982007-11-07 04:08:17 +00001700 assert((*startBuf == '@') && "bogus @try location");
1701
1702 std::string buf;
1703 // declare a new scope with two variables, _stack and _rethrow.
1704 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1705 buf += "int buf[18/*32-bit i386*/];\n";
1706 buf += "char *pointers[4];} _stack;\n";
1707 buf += "id volatile _rethrow = 0;\n";
1708 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001709 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001710
Chris Lattneraadaf782008-01-31 19:51:04 +00001711 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Steve Naroff75730982007-11-07 04:08:17 +00001713 startLoc = S->getTryBody()->getLocEnd();
1714 startBuf = SM->getCharacterData(startLoc);
1715
1716 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Steve Naroff75730982007-11-07 04:08:17 +00001718 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001719 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1720 if (catchList) {
1721 startLoc = startLoc.getFileLocWithOffset(1);
1722 buf = " /* @catch begin */ else {\n";
1723 buf += " id _caught = objc_exception_extract(&_stack);\n";
1724 buf += " objc_exception_try_enter (&_stack);\n";
1725 buf += " if (_setjmp(_stack.buf))\n";
1726 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1727 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Steve Naroffc9ba1722008-07-16 15:31:30 +00001729 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001730 } else { /* no catch list */
1731 buf = "}\nelse {\n";
1732 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1733 buf += "}";
1734 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001735 }
Steve Naroff75730982007-11-07 04:08:17 +00001736 bool sawIdTypedCatch = false;
1737 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001738 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001739 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001740
Mike Stump1eb44332009-09-09 15:08:12 +00001741 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001742 buf = "if ("; // we are generating code for the first catch clause
1743 else
1744 buf = "else if (";
1745 startLoc = catchList->getLocStart();
1746 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Steve Naroff75730982007-11-07 04:08:17 +00001748 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001749
Steve Naroff75730982007-11-07 04:08:17 +00001750 const char *lParenLoc = strchr(startBuf, '(');
1751
Steve Naroffbe4b3332008-02-01 22:08:12 +00001752 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001753 // Now rewrite the body...
1754 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001755 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1756 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001757 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1758 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001759 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Steve Naroffe12e6922008-02-01 20:02:07 +00001761 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001762 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001763 } else if (catchDecl) {
1764 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001765 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001766 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001767 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001768 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001769 } else if (t->isObjCObjectPointerType()) {
1770 QualType InterfaceTy = t->getPointeeType();
1771 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1772 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001773 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001774 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001775 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001776 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001777 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001778 }
1779 }
1780 // Now rewrite the body...
1781 lastCatchBody = catchList->getCatchBody();
1782 SourceLocation rParenLoc = catchList->getRParenLoc();
1783 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1784 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1785 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1786 assert((*rParenBuf == ')') && "bogus @catch paren location");
1787 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Steve Naroff75730982007-11-07 04:08:17 +00001789 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001790 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001791 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001792 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001793 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001794 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001795 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001796 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001797 catchList = catchList->getNextCatchStmt();
1798 }
1799 // Complete the catch list...
1800 if (lastCatchBody) {
1801 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001802 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1803 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001804
Steve Naroff378f47a2008-09-11 15:29:03 +00001805 // Insert the last (implicit) else clause *before* the right curly brace.
1806 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1807 buf = "} /* last catch end */\n";
1808 buf += "else {\n";
1809 buf += " _rethrow = _caught;\n";
1810 buf += " objc_exception_try_exit(&_stack);\n";
1811 buf += "} } /* @catch end */\n";
1812 if (!S->getFinallyStmt())
1813 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001814 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Steve Naroff75730982007-11-07 04:08:17 +00001816 // Set lastCurlyLoc
1817 lastCurlyLoc = lastCatchBody->getLocEnd();
1818 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001819 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001820 startLoc = finalStmt->getLocStart();
1821 startBuf = SM->getCharacterData(startLoc);
1822 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Steve Naroff75730982007-11-07 04:08:17 +00001824 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001825 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001826
Steve Naroff75730982007-11-07 04:08:17 +00001827 Stmt *body = finalStmt->getFinallyBody();
1828 SourceLocation startLoc = body->getLocStart();
1829 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001830 assert(*SM->getCharacterData(startLoc) == '{' &&
1831 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001832 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001833 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroff75730982007-11-07 04:08:17 +00001835 startLoc = startLoc.getFileLocWithOffset(1);
1836 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001837 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001838 endLoc = endLoc.getFileLocWithOffset(-1);
1839 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001840 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Steve Naroff75730982007-11-07 04:08:17 +00001842 // Set lastCurlyLoc
1843 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Steve Naroff8c565152008-12-05 17:03:39 +00001845 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001846 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001847 } else { /* no finally clause - make sure we synthesize an implicit one */
1848 buf = "{ /* implicit finally clause */\n";
1849 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1850 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1851 buf += "}";
1852 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001853
1854 // Now check for any return/continue/go statements within the @try.
1855 // The implicit finally clause won't called if the @try contains any
1856 // jump statements.
1857 bool hasReturns = false;
1858 HasReturnStmts(S->getTryBody(), hasReturns);
1859 if (hasReturns)
1860 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001861 }
1862 // Now emit the final closing curly brace...
1863 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1864 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001865 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001866 return 0;
1867}
1868
Steve Naroffb29b4272008-04-14 22:03:09 +00001869Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001870 return 0;
1871}
1872
Steve Naroffb29b4272008-04-14 22:03:09 +00001873Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001874 return 0;
1875}
1876
Mike Stump1eb44332009-09-09 15:08:12 +00001877// This can't be done with ReplaceStmt(S, ThrowExpr), since
1878// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001879// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001880Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001881 // Get the start location and compute the semi location.
1882 SourceLocation startLoc = S->getLocStart();
1883 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Steve Naroff2bd03922007-11-07 15:32:26 +00001885 assert((*startBuf == '@') && "bogus @throw location");
1886
1887 std::string buf;
1888 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001889 if (S->getThrowExpr())
1890 buf = "objc_exception_throw(";
1891 else // add an implicit argument
1892 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001894 // handle "@ throw" correctly.
1895 const char *wBuf = strchr(startBuf, 'w');
1896 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1897 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001898
Steve Naroff2bd03922007-11-07 15:32:26 +00001899 const char *semiBuf = strchr(startBuf, ';');
1900 assert((*semiBuf == ';') && "@throw: can't find ';'");
1901 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1902 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001903 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001904 return 0;
1905}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001906
Steve Naroffb29b4272008-04-14 22:03:09 +00001907Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001908 // Create a new string expression.
1909 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001910 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001911 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001912 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1913 StrEncoding.length(), false,StrType,
1914 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001915 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001916
Chris Lattner07506182007-11-30 22:53:43 +00001917 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001918 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001919 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001920}
1921
Steve Naroffb29b4272008-04-14 22:03:09 +00001922Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001923 if (!SelGetUidFunctionDecl)
1924 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001925 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1926 // Create a call to sel_registerName("selName").
1927 llvm::SmallVector<Expr*, 8> SelExprs;
1928 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001929 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001930 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001931 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001932 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001933 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1934 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001935 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001936 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001937 return SelExp;
1938}
1939
Steve Naroffb29b4272008-04-14 22:03:09 +00001940CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001941 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001942 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001943 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001944
Steve Naroffebf2b562007-10-23 23:50:29 +00001945 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001946 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Steve Naroffebf2b562007-10-23 23:50:29 +00001948 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001949 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001950 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001951 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001952 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001953 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCall183700f2009-09-21 23:43:11 +00001955 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Ted Kremenek668bf912009-02-09 20:51:47 +00001957 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1958 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001959}
1960
Steve Naroffd5255f52007-11-01 13:24:47 +00001961static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1962 const char *&startRef, const char *&endRef) {
1963 while (startBuf < endBuf) {
1964 if (*startBuf == '<')
1965 startRef = startBuf; // mark the start.
1966 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001967 if (startRef && *startRef == '<') {
1968 endRef = startBuf; // mark the end.
1969 return true;
1970 }
1971 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001972 }
1973 startBuf++;
1974 }
1975 return false;
1976}
1977
Fariborz Jahanian61477f72007-12-11 22:50:14 +00001978static void scanToNextArgument(const char *&argRef) {
1979 int angle = 0;
1980 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1981 if (*argRef == '<')
1982 angle++;
1983 else if (*argRef == '>')
1984 angle--;
1985 argRef++;
1986 }
1987 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1988}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00001989
Steve Naroffb29b4272008-04-14 22:03:09 +00001990bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc15cb2a2009-07-18 15:33:26 +00001991 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroffd5255f52007-11-01 13:24:47 +00001992}
1993
Steve Naroff4f95b752008-07-29 18:15:38 +00001994void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1995 QualType Type = E->getType();
1996 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00001997 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Steve Naroffcda658e2008-11-19 21:15:47 +00001999 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2000 Loc = ECE->getLParenLoc();
2001 EndLoc = ECE->getRParenLoc();
2002 } else {
2003 Loc = E->getLocStart();
2004 EndLoc = E->getLocEnd();
2005 }
2006 // This will defend against trying to rewrite synthesized expressions.
2007 if (Loc.isInvalid() || EndLoc.isInvalid())
2008 return;
2009
Steve Naroff4f95b752008-07-29 18:15:38 +00002010 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002011 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002012 const char *startRef = 0, *endRef = 0;
2013 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2014 // Get the locations of the startRef, endRef.
2015 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2016 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2017 // Comment out the protocol references.
2018 InsertText(LessLoc, "/*", 2);
2019 InsertText(GreaterLoc, "*/", 2);
2020 }
2021 }
2022}
2023
Steve Naroffb29b4272008-04-14 22:03:09 +00002024void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002025 SourceLocation Loc;
2026 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002027 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002028 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2029 Loc = VD->getLocation();
2030 Type = VD->getType();
2031 }
2032 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2033 Loc = FD->getLocation();
2034 // Check for ObjC 'id' and class types that have been adorned with protocol
2035 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002036 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002037 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002038 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002039 if (!proto)
2040 return;
2041 Type = proto->getResultType();
2042 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002043 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2044 Loc = FD->getLocation();
2045 Type = FD->getType();
2046 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002047 else
2048 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002049
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002050 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002051 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Steve Naroffd5255f52007-11-01 13:24:47 +00002053 const char *endBuf = SM->getCharacterData(Loc);
2054 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002055 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002056 startBuf--; // scan backward (from the decl location) for return type.
2057 const char *startRef = 0, *endRef = 0;
2058 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2059 // Get the locations of the startRef, endRef.
2060 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2061 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2062 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002063 InsertText(LessLoc, "/*", 2);
2064 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002065 }
2066 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002067 if (!proto)
2068 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002069 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002070 const char *startBuf = SM->getCharacterData(Loc);
2071 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002072 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2073 if (needToScanForQualifiers(proto->getArgType(i))) {
2074 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Steve Naroffd5255f52007-11-01 13:24:47 +00002076 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002077 // scan forward (from the decl location) for argument types.
2078 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002079 const char *startRef = 0, *endRef = 0;
2080 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2081 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002082 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002083 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002084 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002085 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002086 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002087 InsertText(LessLoc, "/*", 2);
2088 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002089 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002090 startBuf = ++endBuf;
2091 }
2092 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002093 // If the function name is derived from a macro expansion, then the
2094 // argument buffer will not follow the name. Need to speak with Chris.
2095 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002096 startBuf++; // scan forward (from the decl location) for argument types.
2097 startBuf++;
2098 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002099 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002100}
2101
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002102// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002103void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002104 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2105 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002106 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002107 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002108 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002109 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002110 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002111 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002112 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002113 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002114}
2115
Steve Naroffb29b4272008-04-14 22:03:09 +00002116void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002117 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002118 if (FD->getIdentifier() &&
2119 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002120 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002121 return;
2122 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002123 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002124}
2125
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002126void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2127 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2128 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2129 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2130 if (!proto)
2131 return;
2132 QualType Type = proto->getResultType();
2133 std::string FdStr = Type.getAsString();
2134 FdStr += " ";
2135 FdStr += FD->getNameAsCString();
2136 FdStr += "(";
2137 unsigned numArgs = proto->getNumArgs();
2138 for (unsigned i = 0; i < numArgs; i++) {
2139 QualType ArgType = proto->getArgType(i);
2140 FdStr += ArgType.getAsString();
2141
2142 if (i+1 < numArgs)
2143 FdStr += ", ";
2144 }
2145 FdStr += ");\n";
2146 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2147 CurFunctionDeclToDeclareForBlock = 0;
2148}
2149
Steve Naroffc0a123c2008-03-11 17:37:02 +00002150// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002151void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002152 if (SuperContructorFunctionDecl)
2153 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002154 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002155 llvm::SmallVector<QualType, 16> ArgTys;
2156 QualType argT = Context->getObjCIdType();
2157 assert(!argT.isNull() && "Can't find 'id' type");
2158 ArgTys.push_back(argT);
2159 ArgTys.push_back(argT);
2160 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2161 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002162 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002163 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002164 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002165 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002166 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002167}
2168
Steve Naroff09b266e2007-10-30 23:14:51 +00002169// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002170void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002171 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2172 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002173 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002174 assert(!argT.isNull() && "Can't find 'id' type");
2175 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002176 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002177 assert(!argT.isNull() && "Can't find 'SEL' type");
2178 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002179 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002180 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002181 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002182 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002183 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002184 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002185 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002186}
2187
Steve Naroff874e2322007-11-15 10:28:18 +00002188// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002189void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002190 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2191 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002192 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002193 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002194 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002195 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2196 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2197 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002198 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002199 assert(!argT.isNull() && "Can't find 'SEL' type");
2200 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002201 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002202 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002203 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002204 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002205 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002206 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002207 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002208}
2209
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002210// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002211void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002212 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2213 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002214 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002215 assert(!argT.isNull() && "Can't find 'id' type");
2216 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002217 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002218 assert(!argT.isNull() && "Can't find 'SEL' type");
2219 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002220 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002221 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002222 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002223 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002224 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002225 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002226 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002227}
2228
Mike Stump1eb44332009-09-09 15:08:12 +00002229// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002230// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002231void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002232 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002233 &Context->Idents.get("objc_msgSendSuper_stret");
2234 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002235 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002236 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002237 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002238 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2239 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2240 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002241 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002242 assert(!argT.isNull() && "Can't find 'SEL' type");
2243 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002244 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002245 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002246 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002247 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002248 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002249 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002250 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002251}
2252
Steve Naroff1284db82008-05-08 22:02:18 +00002253// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002254void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002255 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2256 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002257 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002258 assert(!argT.isNull() && "Can't find 'id' type");
2259 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002260 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002261 assert(!argT.isNull() && "Can't find 'SEL' type");
2262 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002263 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002264 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002265 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002266 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002267 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002268 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002269 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002270}
2271
Steve Naroff09b266e2007-10-30 23:14:51 +00002272// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002273void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002274 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2275 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002276 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002277 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002278 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002279 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002280 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002281 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002282 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002283 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002284}
2285
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002286// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002287void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002288 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2289 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002290 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002291 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002292 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002293 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002294 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002295 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002296 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002297 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002298}
2299
Steve Naroffb29b4272008-04-14 22:03:09 +00002300Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002301 QualType strType = getConstantStringStructType();
2302
2303 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002304
2305 std::string tmpName = InFileName;
2306 unsigned i;
2307 for (i=0; i < tmpName.length(); i++) {
2308 char c = tmpName.at(i);
2309 // replace any non alphanumeric characters with '_'.
2310 if (!isalpha(c) && (c < '0' || c > '9'))
2311 tmpName[i] = '_';
2312 }
2313 S += tmpName;
2314 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002315 S += utostr(NumObjCStringLiterals++);
2316
Steve Naroffba92b2e2008-03-27 22:29:16 +00002317 Preamble += "static __NSConstantStringImpl " + S;
2318 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2319 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002320 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002321 std::string prettyBufS;
2322 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002323 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2324 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002325 Preamble += prettyBuf.str();
2326 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002327 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002328
2329 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2330 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002331 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002332 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2333 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002334 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002335 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002336 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002337 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2338 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002339 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002340 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002341 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002342}
2343
Steve Naroffb29b4272008-04-14 22:03:09 +00002344ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002345 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002346 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002347
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002348 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002349 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002350 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002351 assert(OPT);
2352 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002353 return IT->getDecl();
2354 }
2355 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002356}
2357
2358// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002359QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002360 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002361 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002362 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002363 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002364 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Steve Naroff874e2322007-11-15 10:28:18 +00002366 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002367 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002368 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002369 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002370
Steve Naroff874e2322007-11-15 10:28:18 +00002371 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002372 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002373 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2374 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002375 FieldTypes[i], 0,
2376 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002377 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002378 }
Mike Stump1eb44332009-09-09 15:08:12 +00002379
Douglas Gregor44b43212008-12-11 16:49:14 +00002380 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002381 }
2382 return Context->getTagDeclType(SuperStructDecl);
2383}
2384
Steve Naroffb29b4272008-04-14 22:03:09 +00002385QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002386 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002387 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002388 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002389 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002390 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002392 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002393 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002394 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002395 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002396 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002397 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002398 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002399 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002400
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002401 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002402 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002403 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2404 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002405 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002406 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002407 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002408 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002409 }
2410
2411 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002412 }
2413 return Context->getTagDeclType(ConstantStringDecl);
2414}
2415
Steve Naroffb29b4272008-04-14 22:03:09 +00002416Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002417 if (!SelGetUidFunctionDecl)
2418 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002419 if (!MsgSendFunctionDecl)
2420 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002421 if (!MsgSendSuperFunctionDecl)
2422 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002423 if (!MsgSendStretFunctionDecl)
2424 SynthMsgSendStretFunctionDecl();
2425 if (!MsgSendSuperStretFunctionDecl)
2426 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002427 if (!MsgSendFpretFunctionDecl)
2428 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002429 if (!GetClassFunctionDecl)
2430 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002431 if (!GetMetaClassFunctionDecl)
2432 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Steve Naroff874e2322007-11-15 10:28:18 +00002434 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002435 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2436 // May need to use objc_msgSend_stret() as well.
2437 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002438 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2439 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002440 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002441 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002442 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002443 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002444 }
Mike Stump1eb44332009-09-09 15:08:12 +00002445
Steve Naroff934f2762007-10-24 22:48:43 +00002446 // Synthesize a call to objc_msgSend().
2447 llvm::SmallVector<Expr*, 8> MsgExprs;
2448 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002449
Steve Naroff934f2762007-10-24 22:48:43 +00002450 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2451 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002452 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2453 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002454 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002455 MsgSendFlavor = MsgSendSuperFunctionDecl;
2456 if (MsgSendStretFlavor)
2457 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2458 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002459
2460 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002461 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002462
2463 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002464
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002465 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002466 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002467 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2468 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002469 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002470 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002471 SourceLocation()))
2472 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002473
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002474 llvm::SmallVector<Expr*, 8> ClsExprs;
2475 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002476 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002477 SuperDecl->getIdentifier()->getNameStart(),
2478 SuperDecl->getIdentifier()->getLength(),
2479 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002480 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002481 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002482 ClsExprs.size());
2483 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002484 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002485 NoTypeInfoCStyleCastExpr(Context,
2486 Context->getObjCIdType(),
2487 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002488 // struct objc_super
2489 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002490 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002491
Steve Naroff23f41272008-03-11 18:14:26 +00002492 if (LangOpts.Microsoft) {
2493 SynthSuperContructorFunctionDecl();
2494 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002495 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002496 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002497 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002498 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002499 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002500 // The code for super is a little tricky to prevent collision with
2501 // the structure definition in the header. The rewriter has it's own
2502 // internal definition (__rw_objc_super) that is uses. This is why
2503 // we need the cast below. For example:
2504 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2505 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002506 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002507 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002508 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002509 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2510 Context->getPointerType(superType),
2511 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002512 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002513 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002514 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2515 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002516 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002517 TypeSourceInfo *superTInfo
2518 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002519 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2520 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002521 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002522 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002523 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002524 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002525 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002526 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002527 } else {
2528 llvm::SmallVector<Expr*, 8> ClsExprs;
2529 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002530 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002531 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002532 clsName->getLength(),
2533 false, argType,
2534 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002535 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002536 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002537 ClsExprs.size());
2538 MsgExprs.push_back(Cls);
2539 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002540 } else { // instance message.
2541 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002542
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002543 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002544 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002545 if (MsgSendStretFlavor)
2546 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002547 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002548
Steve Naroff874e2322007-11-15 10:28:18 +00002549 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002550
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002551 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002552 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2553 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002554 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002555 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002556 SourceLocation()))
2557 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Steve Naroff874e2322007-11-15 10:28:18 +00002559 llvm::SmallVector<Expr*, 8> ClsExprs;
2560 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002561 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002562 SuperDecl->getIdentifier()->getNameStart(),
2563 SuperDecl->getIdentifier()->getLength(),
2564 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002565 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002566 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002567 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002568 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002569 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002570 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002571 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2572 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002573 // struct objc_super
2574 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002575 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Steve Naroffc0a123c2008-03-11 17:37:02 +00002577 if (LangOpts.Microsoft) {
2578 SynthSuperContructorFunctionDecl();
2579 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002580 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002581 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002582 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002583 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002584 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002585 // The code for super is a little tricky to prevent collision with
2586 // the structure definition in the header. The rewriter has it's own
2587 // internal definition (__rw_objc_super) that is uses. This is why
2588 // we need the cast below. For example:
2589 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2590 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002591 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002592 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002593 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002594 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2595 Context->getPointerType(superType),
2596 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002597 } else {
2598 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002599 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2600 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002601 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002602 TypeSourceInfo *superTInfo
2603 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002604 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2605 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002606 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002607 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002608 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002609 // Remove all type-casts because it may contain objc-style types; e.g.
2610 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002611 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002612 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002613 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2614 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002615 MsgExprs.push_back(recExpr);
2616 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002617 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002618 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002619 llvm::SmallVector<Expr*, 8> SelExprs;
2620 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002621 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002622 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002623 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002624 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002625 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2626 &SelExprs[0], SelExprs.size());
2627 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002628
Steve Naroff934f2762007-10-24 22:48:43 +00002629 // Now push any user supplied arguments.
2630 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002631 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002632 // Make all implicit casts explicit...ICE comes in handy:-)
2633 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2634 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002635 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002636 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002637 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002638 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2639 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002640 }
2641 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002642 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002643 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002644 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002645 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002646 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2647 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002648 }
Mike Stump1eb44332009-09-09 15:08:12 +00002649 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002650 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002651 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2652 // out the argument in the original expression (since we aren't deleting
2653 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2654 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002655 }
Steve Naroffab972d32007-11-04 22:37:50 +00002656 // Generate the funky cast.
2657 CastExpr *cast;
2658 llvm::SmallVector<QualType, 8> ArgTypes;
2659 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Steve Naroffab972d32007-11-04 22:37:50 +00002661 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002662 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2663 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2664 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002665 ArgTypes.push_back(Context->getObjCIdType());
2666 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002667 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002668 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002669 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2670 E = OMD->param_end(); PI != E; ++PI) {
2671 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002672 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002673 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002674 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002675 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002676 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002677 t = Context->getPointerType(BPT->getPointeeType());
2678 }
Steve Naroff352336b2007-11-05 14:36:37 +00002679 ArgTypes.push_back(t);
2680 }
Chris Lattner89951a82009-02-20 18:43:26 +00002681 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2682 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002683 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002684 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002685 }
2686 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002687 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Steve Naroffab972d32007-11-04 22:37:50 +00002689 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002690 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002691 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002692
Mike Stump1eb44332009-09-09 15:08:12 +00002693 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002694 // If we don't do this cast, we get the following bizarre warning/note:
2695 // xx.m:13: warning: function called through a non-compatible type
2696 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002697 cast = NoTypeInfoCStyleCastExpr(Context,
2698 Context->getPointerType(Context->VoidTy),
2699 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002700
Steve Naroffab972d32007-11-04 22:37:50 +00002701 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002702 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002703 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002704 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002705 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002706 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002707 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2708 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002709
2710 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002711 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002712
John McCall183700f2009-09-21 23:43:11 +00002713 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002714 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002715 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002716 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002717 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002718 if (MsgSendStretFlavor) {
2719 // We have the method which returns a struct/union. Must also generate
2720 // call to objc_msgSend_stret and hang both varieties on a conditional
2721 // expression which dictate which one to envoke depending on size of
2722 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002723
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002724 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002725 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002726 SourceLocation());
2727 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002728 cast = NoTypeInfoCStyleCastExpr(Context,
2729 Context->getPointerType(Context->VoidTy),
2730 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002731 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002732 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002733 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002734 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002735 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002736 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2737 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002739 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002740 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
John McCall183700f2009-09-21 23:43:11 +00002742 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002743 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002744 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002745 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002747 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002748 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002749 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002750 Context->getSizeType(),
2751 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002752 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2753 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2754 // For X86 it is more complicated and some kind of target specific routine
2755 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002756 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002757 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002758 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002759 Context->IntTy,
2760 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002761 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2762 BinaryOperator::LE,
2763 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002764 SourceLocation());
2765 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002766 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002767 new (Context) ConditionalOperator(lessThanExpr,
2768 SourceLocation(), CE,
2769 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002770 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002771 }
Mike Stump1eb44332009-09-09 15:08:12 +00002772 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002773 return ReplacingStmt;
2774}
2775
Steve Naroffb29b4272008-04-14 22:03:09 +00002776Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002777 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Steve Naroff934f2762007-10-24 22:48:43 +00002779 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002780 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002781
2782 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002783 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002784}
2785
Steve Naroff621edce2009-04-29 16:37:50 +00002786// typedef struct objc_object Protocol;
2787QualType RewriteObjC::getProtocolType() {
2788 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002789 TypeSourceInfo *TInfo
2790 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002791 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002792 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002793 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002794 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002795 }
2796 return Context->getTypeDeclType(ProtocolTypeDecl);
2797}
2798
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002799/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002800/// a synthesized/forward data reference (to the protocol's metadata).
2801/// The forward references (and metadata) are generated in
2802/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002803Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002804 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2805 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002806 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002807 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002808 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2809 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2810 Context->getPointerType(DRE->getType()),
2811 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002812 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2813 CastExpr::CK_Unknown,
2814 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002815 ReplaceStmt(Exp, castExpr);
2816 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002817 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002818 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002820}
2821
Mike Stump1eb44332009-09-09 15:08:12 +00002822bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002823 const char *endBuf) {
2824 while (startBuf < endBuf) {
2825 if (*startBuf == '#') {
2826 // Skip whitespace.
2827 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2828 ;
2829 if (!strncmp(startBuf, "if", strlen("if")) ||
2830 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2831 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2832 !strncmp(startBuf, "define", strlen("define")) ||
2833 !strncmp(startBuf, "undef", strlen("undef")) ||
2834 !strncmp(startBuf, "else", strlen("else")) ||
2835 !strncmp(startBuf, "elif", strlen("elif")) ||
2836 !strncmp(startBuf, "endif", strlen("endif")) ||
2837 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2838 !strncmp(startBuf, "include", strlen("include")) ||
2839 !strncmp(startBuf, "import", strlen("import")) ||
2840 !strncmp(startBuf, "include_next", strlen("include_next")))
2841 return true;
2842 }
2843 startBuf++;
2844 }
2845 return false;
2846}
2847
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002848/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002849/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002850void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002851 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002852 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002853 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002854 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002855 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002856 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002857 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002858 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002859 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002860 SourceLocation LocStart = CDecl->getLocStart();
2861 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Steve Narofffea763e82007-11-14 19:25:57 +00002863 const char *startBuf = SM->getCharacterData(LocStart);
2864 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002865
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002866 // If no ivars and no root or if its root, directly or indirectly,
2867 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002868 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2869 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002870 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002871 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002872 return;
2873 }
Mike Stump1eb44332009-09-09 15:08:12 +00002874
2875 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002876 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002877 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002878 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002879 if (LangOpts.Microsoft)
2880 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002881
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002882 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002883 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002884 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002885 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002886 // If the buffer contains preprocessor directives, we do more fine-grained
2887 // rewrites. This is intended to fix code that looks like (which occurs in
2888 // NSURL.h, for example):
2889 //
2890 // #ifdef XYZ
2891 // @interface Foo : NSObject
2892 // #else
2893 // @interface FooBar : NSObject
2894 // #endif
2895 // {
2896 // int i;
2897 // }
2898 // @end
2899 //
2900 // This clause is segregated to avoid breaking the common case.
2901 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002902 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002903 CDecl->getClassLoc();
2904 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002905 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002906
Chris Lattnercafeb352009-02-20 18:18:36 +00002907 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002908 // advance to the end of the referenced protocols.
2909 while (endHeader < cursor && *endHeader != '>') endHeader++;
2910 endHeader++;
2911 }
2912 // rewrite the original header
2913 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2914 } else {
2915 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002916 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002917 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002918 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002919 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002920 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002921 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002922 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002923 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Steve Narofffea763e82007-11-14 19:25:57 +00002925 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002926 SourceLocation OnePastCurly =
2927 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2928 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002929 }
2930 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002931
Steve Narofffea763e82007-11-14 19:25:57 +00002932 // Now comment out any visibility specifiers.
2933 while (cursor < endBuf) {
2934 if (*cursor == '@') {
2935 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002936 // Skip whitespace.
2937 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2938 /*scan*/;
2939
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002940 // FIXME: presence of @public, etc. inside comment results in
2941 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002942 if (!strncmp(cursor, "public", strlen("public")) ||
2943 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002944 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002945 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002946 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002947 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002948 // FIXME: If there are cases where '<' is used in ivar declaration part
2949 // of user code, then scan the ivar list and use needToScanForQualifiers
2950 // for type checking.
2951 else if (*cursor == '<') {
2952 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002953 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002954 cursor = strchr(cursor, '>');
2955 cursor++;
2956 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002957 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002958 } else if (*cursor == '^') { // rewrite block specifier.
2959 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2960 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002961 }
Steve Narofffea763e82007-11-14 19:25:57 +00002962 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002963 }
Steve Narofffea763e82007-11-14 19:25:57 +00002964 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002965 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00002966 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00002967 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00002968 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002969 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002970 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002971 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002972 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00002973 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002974 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002975 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002976 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00002977 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002978}
2979
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002980// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002981/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00002982template<typename MethodIterator>
2983void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2984 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00002985 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002986 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00002987 const char *ClassName,
2988 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002989 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Chris Lattnerab4c4d52007-12-12 07:46:12 +00002991 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002992 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00002993 SEL _cmd;
2994 char *method_types;
2995 void *_imp;
2996 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00002997 */
Chris Lattner158ecb92007-10-25 17:07:24 +00002998 Result += "\nstruct _objc_method {\n";
2999 Result += "\tSEL _cmd;\n";
3000 Result += "\tchar *method_types;\n";
3001 Result += "\tvoid *_imp;\n";
3002 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003004 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003005 }
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003007 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003008
Steve Naroff946a6932008-03-11 00:12:29 +00003009 /* struct {
3010 struct _objc_method_list *next_method;
3011 int method_count;
3012 struct _objc_method method_list[];
3013 }
3014 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003015 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003016 Result += "\nstatic struct {\n";
3017 Result += "\tstruct _objc_method_list *next_method;\n";
3018 Result += "\tint method_count;\n";
3019 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003020 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003021 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003022 Result += prefix;
3023 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3024 Result += "_METHODS_";
3025 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003026 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003027 Result += IsInstanceMethod ? "inst" : "cls";
3028 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003029 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003030
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003031 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003032 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003033 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003034 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003035 Result += "\", \"";
3036 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003037 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003038 Result += MethodInternalNames[*MethodBegin];
3039 Result += "}\n";
3040 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3041 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003042 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003043 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003044 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003045 Result += "\", \"";
3046 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003047 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003048 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003049 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003050 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003051 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003052}
3053
Steve Naroff621edce2009-04-29 16:37:50 +00003054/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003055void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003056RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3057 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003058 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003059
3060 // Output struct protocol_methods holder of method selector and type.
3061 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3062 /* struct protocol_methods {
3063 SEL _cmd;
3064 char *method_types;
3065 }
3066 */
3067 Result += "\nstruct _protocol_methods {\n";
3068 Result += "\tstruct objc_selector *_cmd;\n";
3069 Result += "\tchar *method_types;\n";
3070 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003071
Steve Naroff621edce2009-04-29 16:37:50 +00003072 objc_protocol_methods = true;
3073 }
3074 // Do not synthesize the protocol more than once.
3075 if (ObjCSynthesizedProtocols.count(PDecl))
3076 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003077
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003078 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3079 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3080 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003081 /* struct _objc_protocol_method_list {
3082 int protocol_method_count;
3083 struct protocol_methods protocols[];
3084 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003085 */
Steve Naroff621edce2009-04-29 16:37:50 +00003086 Result += "\nstatic struct {\n";
3087 Result += "\tint protocol_method_count;\n";
3088 Result += "\tstruct _protocol_methods protocol_methods[";
3089 Result += utostr(NumMethods);
3090 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3091 Result += PDecl->getNameAsString();
3092 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3093 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Steve Naroff621edce2009-04-29 16:37:50 +00003095 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003096 for (ObjCProtocolDecl::instmeth_iterator
3097 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003098 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003099 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003100 Result += "\t ,{{(struct objc_selector *)\"";
3101 else
3102 Result += "\t ,{(struct objc_selector *)\"";
3103 Result += (*I)->getSelector().getAsString().c_str();
3104 std::string MethodTypeString;
3105 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3106 Result += "\", \"";
3107 Result += MethodTypeString;
3108 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003109 }
Steve Naroff621edce2009-04-29 16:37:50 +00003110 Result += "\t }\n};\n";
3111 }
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Steve Naroff621edce2009-04-29 16:37:50 +00003113 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003114 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3115 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003116 if (NumMethods > 0) {
3117 /* struct _objc_protocol_method_list {
3118 int protocol_method_count;
3119 struct protocol_methods protocols[];
3120 }
3121 */
3122 Result += "\nstatic struct {\n";
3123 Result += "\tint protocol_method_count;\n";
3124 Result += "\tstruct _protocol_methods protocol_methods[";
3125 Result += utostr(NumMethods);
3126 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3127 Result += PDecl->getNameAsString();
3128 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3129 "{\n\t";
3130 Result += utostr(NumMethods);
3131 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Steve Naroff621edce2009-04-29 16:37:50 +00003133 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003134 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003135 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003136 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003137 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003138 Result += "\t ,{{(struct objc_selector *)\"";
3139 else
3140 Result += "\t ,{(struct objc_selector *)\"";
3141 Result += (*I)->getSelector().getAsString().c_str();
3142 std::string MethodTypeString;
3143 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3144 Result += "\", \"";
3145 Result += MethodTypeString;
3146 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003147 }
Steve Naroff621edce2009-04-29 16:37:50 +00003148 Result += "\t }\n};\n";
3149 }
3150
3151 // Output:
3152 /* struct _objc_protocol {
3153 // Objective-C 1.0 extensions
3154 struct _objc_protocol_extension *isa;
3155 char *protocol_name;
3156 struct _objc_protocol **protocol_list;
3157 struct _objc_protocol_method_list *instance_methods;
3158 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003159 };
Steve Naroff621edce2009-04-29 16:37:50 +00003160 */
3161 static bool objc_protocol = false;
3162 if (!objc_protocol) {
3163 Result += "\nstruct _objc_protocol {\n";
3164 Result += "\tstruct _objc_protocol_extension *isa;\n";
3165 Result += "\tchar *protocol_name;\n";
3166 Result += "\tstruct _objc_protocol **protocol_list;\n";
3167 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3168 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003169 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Steve Naroff621edce2009-04-29 16:37:50 +00003171 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003172 }
Mike Stump1eb44332009-09-09 15:08:12 +00003173
Steve Naroff621edce2009-04-29 16:37:50 +00003174 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3175 Result += PDecl->getNameAsString();
3176 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3177 "{\n\t0, \"";
3178 Result += PDecl->getNameAsString();
3179 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003180 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003181 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3182 Result += PDecl->getNameAsString();
3183 Result += ", ";
3184 }
3185 else
3186 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003187 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003188 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3189 Result += PDecl->getNameAsString();
3190 Result += "\n";
3191 }
3192 else
3193 Result += "0\n";
3194 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Steve Naroff621edce2009-04-29 16:37:50 +00003196 // Mark this protocol as having been generated.
3197 if (!ObjCSynthesizedProtocols.insert(PDecl))
3198 assert(false && "protocol already synthesized");
3199
3200}
3201
3202void RewriteObjC::
3203RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3204 const char *prefix, const char *ClassName,
3205 std::string &Result) {
3206 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Steve Naroff621edce2009-04-29 16:37:50 +00003208 for (unsigned i = 0; i != Protocols.size(); i++)
3209 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3210
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003211 // Output the top lovel protocol meta-data for the class.
3212 /* struct _objc_protocol_list {
3213 struct _objc_protocol_list *next;
3214 int protocol_count;
3215 struct _objc_protocol *class_protocols[];
3216 }
3217 */
3218 Result += "\nstatic struct {\n";
3219 Result += "\tstruct _objc_protocol_list *next;\n";
3220 Result += "\tint protocol_count;\n";
3221 Result += "\tstruct _objc_protocol *class_protocols[";
3222 Result += utostr(Protocols.size());
3223 Result += "];\n} _OBJC_";
3224 Result += prefix;
3225 Result += "_PROTOCOLS_";
3226 Result += ClassName;
3227 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3228 "{\n\t0, ";
3229 Result += utostr(Protocols.size());
3230 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003232 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003233 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003234 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003235
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003236 for (unsigned i = 1; i != Protocols.size(); i++) {
3237 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003238 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003239 Result += "\n";
3240 }
3241 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003242}
3243
Steve Naroff621edce2009-04-29 16:37:50 +00003244
Mike Stump1eb44332009-09-09 15:08:12 +00003245/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003246/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003247void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003248 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003249 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003250 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003251 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003252 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003253 CDecl = CDecl->getNextClassCategory())
3254 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3255 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003257 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003258 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003259 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003261 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003262 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003263 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003264
3265 // If any of our property implementations have associated getters or
3266 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003267 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3268 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003269 Prop != PropEnd; ++Prop) {
3270 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3271 continue;
3272 if (!(*Prop)->getPropertyIvarDecl())
3273 continue;
3274 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3275 if (!PD)
3276 continue;
3277 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3278 InstanceMethods.push_back(Getter);
3279 if (PD->isReadOnly())
3280 continue;
3281 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3282 InstanceMethods.push_back(Setter);
3283 }
3284 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003285 true, "CATEGORY_", FullCategoryName.c_str(),
3286 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003288 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003289 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003290 false, "CATEGORY_", FullCategoryName.c_str(),
3291 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003293 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003294 // Null CDecl is case of a category implementation with no category interface
3295 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003296 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3297 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003298 /* struct _objc_category {
3299 char *category_name;
3300 char *class_name;
3301 struct _objc_method_list *instance_methods;
3302 struct _objc_method_list *class_methods;
3303 struct _objc_protocol_list *protocols;
3304 // Objective-C 1.0 extensions
3305 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003306 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003307 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003308 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003309 */
Mike Stump1eb44332009-09-09 15:08:12 +00003310
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003311 static bool objc_category = false;
3312 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003313 Result += "\nstruct _objc_category {\n";
3314 Result += "\tchar *category_name;\n";
3315 Result += "\tchar *class_name;\n";
3316 Result += "\tstruct _objc_method_list *instance_methods;\n";
3317 Result += "\tstruct _objc_method_list *class_methods;\n";
3318 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003319 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003320 Result += "\tstruct _objc_property_list *instance_properties;\n";
3321 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003322 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003323 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003324 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3325 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003326 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003327 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003328 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003330 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003332 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003333 Result += "\t, (struct _objc_method_list *)"
3334 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3335 Result += FullCategoryName;
3336 Result += "\n";
3337 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003338 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003339 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003340 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003341 Result += "\t, (struct _objc_method_list *)"
3342 "&_OBJC_CATEGORY_CLASS_METHODS_";
3343 Result += FullCategoryName;
3344 Result += "\n";
3345 }
3346 else
3347 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003348
Chris Lattnercafeb352009-02-20 18:18:36 +00003349 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003350 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003351 Result += FullCategoryName;
3352 Result += "\n";
3353 }
3354 else
3355 Result += "\t, 0\n";
3356 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003357}
3358
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003359/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3360/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003361void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3362 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003363 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003364 if (ivar->isBitField()) {
3365 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3366 // place all bitfields at offset 0.
3367 Result += "0";
3368 } else {
3369 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003370 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003371 if (LangOpts.Microsoft)
3372 Result += "_IMPL";
3373 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003375 Result += ")";
3376 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003377}
3378
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003379//===----------------------------------------------------------------------===//
3380// Meta Data Emission
3381//===----------------------------------------------------------------------===//
3382
Steve Naroffb29b4272008-04-14 22:03:09 +00003383void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003384 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003385 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003386
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003387 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003388 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003389 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003390 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003391 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003392 }
Mike Stump1eb44332009-09-09 15:08:12 +00003393
Chris Lattnerbe6df082007-12-12 07:56:42 +00003394 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003395 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003396 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003397 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003398 if (NumIvars > 0) {
3399 static bool objc_ivar = false;
3400 if (!objc_ivar) {
3401 /* struct _objc_ivar {
3402 char *ivar_name;
3403 char *ivar_type;
3404 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003405 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003406 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003407 Result += "\nstruct _objc_ivar {\n";
3408 Result += "\tchar *ivar_name;\n";
3409 Result += "\tchar *ivar_type;\n";
3410 Result += "\tint ivar_offset;\n";
3411 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003412
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003413 objc_ivar = true;
3414 }
3415
Steve Naroff946a6932008-03-11 00:12:29 +00003416 /* struct {
3417 int ivar_count;
3418 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003419 };
Steve Naroff946a6932008-03-11 00:12:29 +00003420 */
Mike Stump1eb44332009-09-09 15:08:12 +00003421 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003422 Result += "\tint ivar_count;\n";
3423 Result += "\tstruct _objc_ivar ivar_list[";
3424 Result += utostr(NumIvars);
3425 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003426 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003427 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003428 "{\n\t";
3429 Result += utostr(NumIvars);
3430 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003431
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003432 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003433 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003434 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003435 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003436 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003437 IV != IVEnd; ++IV)
3438 IVars.push_back(*IV);
3439 IVI = IVars.begin();
3440 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003441 } else {
3442 IVI = CDecl->ivar_begin();
3443 IVE = CDecl->ivar_end();
3444 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003445 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003446 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003447 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003448 std::string TmpString, StrEncoding;
3449 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3450 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003451 Result += StrEncoding;
3452 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003453 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003454 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003455 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003456 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003457 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003458 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003459 std::string TmpString, StrEncoding;
3460 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3461 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003462 Result += StrEncoding;
3463 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003464 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003465 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003466 }
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003468 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003469 }
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003471 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003472 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003473 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003474
3475 // If any of our property implementations have associated getters or
3476 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003477 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3478 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003479 Prop != PropEnd; ++Prop) {
3480 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3481 continue;
3482 if (!(*Prop)->getPropertyIvarDecl())
3483 continue;
3484 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3485 if (!PD)
3486 continue;
3487 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3488 InstanceMethods.push_back(Getter);
3489 if (PD->isReadOnly())
3490 continue;
3491 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3492 InstanceMethods.push_back(Setter);
3493 }
3494 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003495 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003496
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003497 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003498 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003499 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003500
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003501 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003502 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3503 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003505 // Declaration of class/meta-class metadata
3506 /* struct _objc_class {
3507 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003508 const char *super_class_name;
3509 char *name;
3510 long version;
3511 long info;
3512 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003513 struct _objc_ivar_list *ivars;
3514 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003515 struct objc_cache *cache;
3516 struct objc_protocol_list *protocols;
3517 const char *ivar_layout;
3518 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003519 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003520 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003521 static bool objc_class = false;
3522 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003523 Result += "\nstruct _objc_class {\n";
3524 Result += "\tstruct _objc_class *isa;\n";
3525 Result += "\tconst char *super_class_name;\n";
3526 Result += "\tchar *name;\n";
3527 Result += "\tlong version;\n";
3528 Result += "\tlong info;\n";
3529 Result += "\tlong instance_size;\n";
3530 Result += "\tstruct _objc_ivar_list *ivars;\n";
3531 Result += "\tstruct _objc_method_list *methods;\n";
3532 Result += "\tstruct objc_cache *cache;\n";
3533 Result += "\tstruct _objc_protocol_list *protocols;\n";
3534 Result += "\tconst char *ivar_layout;\n";
3535 Result += "\tstruct _objc_class_ext *ext;\n";
3536 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003537 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003538 }
Mike Stump1eb44332009-09-09 15:08:12 +00003539
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003540 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003541 ObjCInterfaceDecl *RootClass = 0;
3542 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003543 while (SuperClass) {
3544 RootClass = SuperClass;
3545 SuperClass = SuperClass->getSuperClass();
3546 }
3547 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003549 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003550 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003551 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003552 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003553 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003554 Result += "\"";
3555
3556 if (SuperClass) {
3557 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003558 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003559 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003560 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003561 Result += "\"";
3562 }
3563 else {
3564 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003565 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003566 Result += "\"";
3567 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003568 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003569 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003570 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003571 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003572 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003573 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003574 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003575 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003576 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003577 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003578 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003579 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003580 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003581 Result += ",0,0\n";
3582 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003583 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003584 Result += "\t,0,0,0,0\n";
3585 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003587 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003588 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003589 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003590 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003591 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003592 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003593 if (SuperClass) {
3594 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003595 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003598 Result += "\"";
3599 }
3600 else {
3601 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003602 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += "\"";
3604 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003605 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003606 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003607 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003608 Result += ",0";
3609 else {
3610 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003611 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003612 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003613 if (LangOpts.Microsoft)
3614 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003615 Result += ")";
3616 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003617 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003618 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003619 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003620 Result += "\n\t";
3621 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003622 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003623 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003624 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003625 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003626 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003627 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003628 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003629 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003630 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003631 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003632 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003633 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003634 Result += ", 0,0\n";
3635 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003636 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003637 Result += ",0,0,0\n";
3638 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003639}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003640
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003641/// RewriteImplementations - This routine rewrites all method implementations
3642/// and emits meta-data.
3643
Steve Narofface66252008-11-13 20:07:04 +00003644void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003645 int ClsDefCount = ClassImplementation.size();
3646 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003648 // Rewrite implemented methods
3649 for (int i = 0; i < ClsDefCount; i++)
3650 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003651
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003652 for (int i = 0; i < CatDefCount; i++)
3653 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003654}
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Steve Narofface66252008-11-13 20:07:04 +00003656void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3657 int ClsDefCount = ClassImplementation.size();
3658 int CatDefCount = CategoryImplementation.size();
3659
Steve Naroff5df5b762008-05-07 21:23:49 +00003660 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003661 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003662 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003663 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003664 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003665
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003666 // For each implemented category, write out all its meta data.
3667 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003668 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003669
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003670 // Write objc_symtab metadata
3671 /*
3672 struct _objc_symtab
3673 {
3674 long sel_ref_cnt;
3675 SEL *refs;
3676 short cls_def_cnt;
3677 short cat_def_cnt;
3678 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003679 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003680 */
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003682 Result += "\nstruct _objc_symtab {\n";
3683 Result += "\tlong sel_ref_cnt;\n";
3684 Result += "\tSEL *refs;\n";
3685 Result += "\tshort cls_def_cnt;\n";
3686 Result += "\tshort cat_def_cnt;\n";
3687 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3688 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003690 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003691 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003692 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003693 + ", " + utostr(CatDefCount) + "\n";
3694 for (int i = 0; i < ClsDefCount; i++) {
3695 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003696 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003697 Result += "\n";
3698 }
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003700 for (int i = 0; i < CatDefCount; i++) {
3701 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003702 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003703 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003704 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003705 Result += "\n";
3706 }
Mike Stump1eb44332009-09-09 15:08:12 +00003707
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003708 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003709
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003710 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003711
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003712 /*
3713 struct _objc_module {
3714 long version;
3715 long size;
3716 const char *name;
3717 struct _objc_symtab *symtab;
3718 }
3719 */
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003721 Result += "\nstruct _objc_module {\n";
3722 Result += "\tlong version;\n";
3723 Result += "\tlong size;\n";
3724 Result += "\tconst char *name;\n";
3725 Result += "\tstruct _objc_symtab *symtab;\n";
3726 Result += "};\n\n";
3727 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003728 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003729 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003730 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003731 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003732
3733 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003734 if (ProtocolExprDecls.size()) {
3735 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3736 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003737 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003738 E = ProtocolExprDecls.end(); I != E; ++I) {
3739 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3740 Result += (*I)->getNameAsString();
3741 Result += " = &_OBJC_PROTOCOL_";
3742 Result += (*I)->getNameAsString();
3743 Result += ";\n";
3744 }
3745 Result += "#pragma data_seg(pop)\n\n";
3746 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003747 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003748 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003749 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3750 Result += "&_OBJC_MODULES;\n";
3751 Result += "#pragma data_seg(pop)\n\n";
3752 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003753}
Chris Lattner311ff022007-10-16 22:36:42 +00003754
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003755void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3756 const std::string &Name,
3757 ValueDecl *VD) {
3758 assert(BlockByRefDeclNo.count(VD) &&
3759 "RewriteByRefString: ByRef decl missing");
3760 ResultStr += "struct __Block_byref_" + Name +
3761 "_" + utostr(BlockByRefDeclNo[VD]) ;
3762}
3763
Steve Naroff54055232008-10-27 17:20:55 +00003764std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3765 const char *funcName,
3766 std::string Tag) {
3767 const FunctionType *AFT = CE->getFunctionType();
3768 QualType RT = AFT->getResultType();
3769 std::string StructRef = "struct " + Tag;
3770 std::string S = "static " + RT.getAsString() + " __" +
3771 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003772
Steve Naroff54055232008-10-27 17:20:55 +00003773 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Douglas Gregor72564e72009-02-26 23:50:07 +00003775 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003776 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003777 // block (to reference imported block decl refs).
3778 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003779 } else if (BD->param_empty()) {
3780 S += "(" + StructRef + " *__cself)";
3781 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003782 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003783 assert(FT && "SynthesizeBlockFunc: No function proto");
3784 S += '(';
3785 // first add the implicit argument.
3786 S += StructRef + " *__cself, ";
3787 std::string ParamStr;
3788 for (BlockDecl::param_iterator AI = BD->param_begin(),
3789 E = BD->param_end(); AI != E; ++AI) {
3790 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003791 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003792 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003793 S += ParamStr;
3794 }
3795 if (FT->isVariadic()) {
3796 if (!BD->param_empty()) S += ", ";
3797 S += "...";
3798 }
3799 S += ')';
3800 }
3801 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Steve Naroff54055232008-10-27 17:20:55 +00003803 // Create local declarations to avoid rewriting all closure decl ref exprs.
3804 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003805 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003806 E = BlockByRefDecls.end(); I != E; ++I) {
3807 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003808 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003809 std::string TypeString;
3810 RewriteByRefString(TypeString, Name, (*I));
3811 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003812 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003813 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003814 }
Steve Naroff54055232008-10-27 17:20:55 +00003815 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003816 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003817 E = BlockByCopyDecls.end(); I != E; ++I) {
3818 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003819 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003820 // Handle nested closure invocation. For example:
3821 //
3822 // void (^myImportedClosure)(void);
3823 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003824 //
Steve Naroff54055232008-10-27 17:20:55 +00003825 // void (^anotherClosure)(void);
3826 // anotherClosure = ^(void) {
3827 // myImportedClosure(); // import and invoke the closure
3828 // };
3829 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003830 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003831 S += "struct __block_impl *";
3832 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003833 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003834 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003835 }
3836 std::string RewrittenStr = RewrittenBlockExprs[CE];
3837 const char *cstr = RewrittenStr.c_str();
3838 while (*cstr++ != '{') ;
3839 S += cstr;
3840 S += "\n";
3841 return S;
3842}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003843
Steve Naroff54055232008-10-27 17:20:55 +00003844std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3845 const char *funcName,
3846 std::string Tag) {
3847 std::string StructRef = "struct " + Tag;
3848 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Steve Naroff54055232008-10-27 17:20:55 +00003850 S += funcName;
3851 S += "_block_copy_" + utostr(i);
3852 S += "(" + StructRef;
3853 S += "*dst, " + StructRef;
3854 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003855 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003856 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003857 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003858 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003859 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003860 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003861 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003862 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003863 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003864 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003865 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003866 S += "}\n";
3867
Steve Naroff54055232008-10-27 17:20:55 +00003868 S += "\nstatic void __";
3869 S += funcName;
3870 S += "_block_dispose_" + utostr(i);
3871 S += "(" + StructRef;
3872 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003873 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003874 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003875 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003876 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003877 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003878 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003879 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003880 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003881 }
Mike Stump1eb44332009-09-09 15:08:12 +00003882 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003883 return S;
3884}
3885
Steve Naroff01aec112009-12-06 21:14:13 +00003886std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3887 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003888 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003889 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Steve Naroff54055232008-10-27 17:20:55 +00003891 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003892 S += " struct " + Desc;
3893 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Steve Naroff01aec112009-12-06 21:14:13 +00003895 Constructor += "(void *fp, "; // Invoke function pointer.
3896 Constructor += "struct " + Desc; // Descriptor pointer.
3897 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Steve Naroff54055232008-10-27 17:20:55 +00003899 if (BlockDeclRefs.size()) {
3900 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003901 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003902 E = BlockByCopyDecls.end(); I != E; ++I) {
3903 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003904 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003905 std::string ArgName = "_" + FieldName;
3906 // Handle nested closure invocation. For example:
3907 //
3908 // void (^myImportedBlock)(void);
3909 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003910 //
Steve Naroff54055232008-10-27 17:20:55 +00003911 // void (^anotherBlock)(void);
3912 // anotherBlock = ^(void) {
3913 // myImportedBlock(); // import and invoke the closure
3914 // };
3915 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003916 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003917 S += "struct __block_impl *";
3918 Constructor += ", void *" + ArgName;
3919 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003920 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3921 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003922 Constructor += ", " + ArgName;
3923 }
3924 S += FieldName + ";\n";
3925 }
3926 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003927 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003928 E = BlockByRefDecls.end(); I != E; ++I) {
3929 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003930 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003931 std::string ArgName = "_" + FieldName;
3932 // Handle nested closure invocation. For example:
3933 //
3934 // void (^myImportedBlock)(void);
3935 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003936 //
Steve Naroff54055232008-10-27 17:20:55 +00003937 // void (^anotherBlock)(void);
3938 // anotherBlock = ^(void) {
3939 // myImportedBlock(); // import and invoke the closure
3940 // };
3941 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003942 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003943 S += "struct __block_impl *";
3944 Constructor += ", void *" + ArgName;
3945 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003946 std::string TypeString;
3947 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003948 TypeString += " *";
3949 FieldName = TypeString + FieldName;
3950 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003951 Constructor += ", " + ArgName;
3952 }
3953 S += FieldName + "; // by ref\n";
3954 }
3955 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003956 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003957 if (GlobalVarDecl)
3958 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3959 else
3960 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003961 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Steve Naroff01aec112009-12-06 21:14:13 +00003963 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003964
Steve Naroff54055232008-10-27 17:20:55 +00003965 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003966 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003967 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003968 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003969 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003970 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003971 Constructor += Name + " = (struct __block_impl *)_";
3972 else
3973 Constructor += Name + " = _";
3974 Constructor += Name + ";\n";
3975 }
3976 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003977 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003978 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003979 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003980 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003981 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003982 Constructor += Name + " = (struct __block_impl *)_";
3983 else
3984 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003985 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003986 }
3987 } else {
3988 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003989 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003990 if (GlobalVarDecl)
3991 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3992 else
3993 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003994 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3995 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003996 }
3997 Constructor += " ";
3998 Constructor += "}\n";
3999 S += Constructor;
4000 S += "};\n";
4001 return S;
4002}
4003
Steve Naroff01aec112009-12-06 21:14:13 +00004004std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4005 std::string ImplTag, int i,
4006 const char *FunName,
4007 unsigned hasCopy) {
4008 std::string S = "\nstatic struct " + DescTag;
4009
4010 S += " {\n unsigned long reserved;\n";
4011 S += " unsigned long Block_size;\n";
4012 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004013 S += " void (*copy)(struct ";
4014 S += ImplTag; S += "*, struct ";
4015 S += ImplTag; S += "*);\n";
4016
4017 S += " void (*dispose)(struct ";
4018 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004019 }
4020 S += "} ";
4021
4022 S += DescTag + "_DATA = { 0, sizeof(struct ";
4023 S += ImplTag + ")";
4024 if (hasCopy) {
4025 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4026 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4027 }
4028 S += "};\n";
4029 return S;
4030}
4031
Steve Naroff54055232008-10-27 17:20:55 +00004032void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004033 const char *FunName) {
4034 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004035 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004036 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004037 // Insert closures that were part of the function.
4038 for (unsigned i = 0; i < Blocks.size(); i++) {
4039
4040 CollectBlockDeclRefInfo(Blocks[i]);
4041
Steve Naroff01aec112009-12-06 21:14:13 +00004042 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4043 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Steve Naroff01aec112009-12-06 21:14:13 +00004045 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004046
4047 InsertText(FunLocStart, CI.c_str(), CI.size());
4048
Steve Naroff01aec112009-12-06 21:14:13 +00004049 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Steve Naroff54055232008-10-27 17:20:55 +00004051 InsertText(FunLocStart, CF.c_str(), CF.size());
4052
4053 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004054 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004055 InsertText(FunLocStart, HF.c_str(), HF.size());
4056 }
Steve Naroff01aec112009-12-06 21:14:13 +00004057 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4058 ImportedBlockDecls.size() > 0);
4059 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004060
Steve Naroff54055232008-10-27 17:20:55 +00004061 BlockDeclRefs.clear();
4062 BlockByRefDecls.clear();
4063 BlockByCopyDecls.clear();
4064 BlockCallExprs.clear();
4065 ImportedBlockDecls.clear();
4066 }
4067 Blocks.clear();
4068 RewrittenBlockExprs.clear();
4069}
4070
4071void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4072 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004073 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004074
Steve Naroff54055232008-10-27 17:20:55 +00004075 SynthesizeBlockLiterals(FunLocStart, FuncName);
4076}
4077
4078void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004079 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4080 //SourceLocation FunLocStart = MD->getLocStart();
4081 // FIXME: This hack works around a bug in Rewrite.InsertText().
4082 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattner077bf5e2008-11-24 03:33:13 +00004083 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004084 // Convert colons to underscores.
4085 std::string::size_type loc = 0;
4086 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4087 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004088
Steve Naroff54055232008-10-27 17:20:55 +00004089 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4090}
4091
4092void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4093 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4094 CI != E; ++CI)
4095 if (*CI) {
4096 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4097 GetBlockDeclRefExprs(CBE->getBody());
4098 else
4099 GetBlockDeclRefExprs(*CI);
4100 }
4101 // Handle specific things.
4102 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4103 // FIXME: Handle enums.
4104 if (!isa<FunctionDecl>(CDRE->getDecl()))
4105 BlockDeclRefs.push_back(CDRE);
4106 return;
4107}
4108
4109void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4110 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4111 CI != E; ++CI)
4112 if (*CI) {
4113 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4114 GetBlockCallExprs(CBE->getBody());
4115 else
4116 GetBlockCallExprs(*CI);
4117 }
Mike Stump1eb44332009-09-09 15:08:12 +00004118
Steve Naroff54055232008-10-27 17:20:55 +00004119 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4120 if (CE->getCallee()->getType()->isBlockPointerType()) {
4121 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4122 }
4123 }
4124 return;
4125}
4126
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004127Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004128 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004129 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004131 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004132 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004133 } else if (const BlockDeclRefExpr *CDRE =
4134 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004135 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004136 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004137 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004138 }
4139 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4140 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4141 }
4142 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4143 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4144 else if (const ConditionalOperator *CEXPR =
4145 dyn_cast<ConditionalOperator>(BlockExp)) {
4146 Expr *LHSExp = CEXPR->getLHS();
4147 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4148 Expr *RHSExp = CEXPR->getRHS();
4149 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4150 Expr *CONDExp = CEXPR->getCond();
4151 ConditionalOperator *CondExpr =
4152 new (Context) ConditionalOperator(CONDExp,
4153 SourceLocation(), cast<Expr>(LHSStmt),
4154 SourceLocation(), cast<Expr>(RHSStmt),
4155 Exp->getType());
4156 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004157 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4158 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004159 } else {
4160 assert(1 && "RewriteBlockClass: Bad type");
4161 }
4162 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004163 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004164 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004165 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004166 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004168 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4169 SourceLocation(),
4170 &Context->Idents.get("__block_impl"));
4171 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004172
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004173 // Generate a funky cast.
4174 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004175
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004176 // Push the block argument type.
4177 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004178 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004179 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004180 E = FTP->arg_type_end(); I && (I != E); ++I) {
4181 QualType t = *I;
4182 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004183 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004184 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004185 t = Context->getPointerType(BPT->getPointeeType());
4186 }
4187 ArgTypes.push_back(t);
4188 }
Steve Naroff54055232008-10-27 17:20:55 +00004189 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004190 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004191 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004192 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004193
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004194 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004195
John McCall9d125032010-01-15 18:39:57 +00004196 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4197 CastExpr::CK_Unknown,
4198 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004199 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004200 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4201 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004202 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Douglas Gregor44b43212008-12-11 16:49:14 +00004204 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004205 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004206 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004207 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4208 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004209
John McCall9d125032010-01-15 18:39:57 +00004210 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4211 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004212 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004213
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004214 llvm::SmallVector<Expr*, 8> BlkExprs;
4215 // Add the implicit argument.
4216 BlkExprs.push_back(BlkCast);
4217 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004218 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004219 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004220 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004221 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004222 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4223 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004224 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004225 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004226}
4227
4228void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004229 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004230 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004231}
4232
Steve Naroff621edce2009-04-29 16:37:50 +00004233// We need to return the rewritten expression to handle cases where the
4234// BlockDeclRefExpr is embedded in another expression being rewritten.
4235// For example:
4236//
4237// int main() {
4238// __block Foo *f;
4239// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004240//
Steve Naroff621edce2009-04-29 16:37:50 +00004241// void (^myblock)() = ^() {
4242// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4243// i = 77;
4244// };
4245//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004246Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004247 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004248 // for each DeclRefExp where BYREFVAR is name of the variable.
4249 ValueDecl *VD;
4250 bool isArrow = true;
4251 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4252 VD = BDRE->getDecl();
4253 else {
4254 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4255 isArrow = false;
4256 }
4257
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004258 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4259 &Context->Idents.get("__forwarding"),
4260 Context->VoidPtrTy, 0,
4261 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004262 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4263 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004264 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004265
4266 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004267 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4268 &Context->Idents.get(Name),
4269 Context->VoidPtrTy, 0,
4270 /*BitWidth=*/0, /*Mutable=*/true);
4271 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004272 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004273
4274
4275
Steve Naroffdf8570d2009-02-02 17:19:26 +00004276 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004277 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4278 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004279 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004280 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004281}
4282
Steve Naroffb2f9e512008-11-03 23:29:32 +00004283void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4284 SourceLocation LocStart = CE->getLParenLoc();
4285 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004286
4287 // Need to avoid trying to rewrite synthesized casts.
4288 if (LocStart.isInvalid())
4289 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004290 // Need to avoid trying to rewrite casts contained in macros.
4291 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4292 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004293
Steve Naroff54055232008-10-27 17:20:55 +00004294 const char *startBuf = SM->getCharacterData(LocStart);
4295 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004296 QualType QT = CE->getType();
4297 const Type* TypePtr = QT->getAs<Type>();
4298 if (isa<TypeOfExprType>(TypePtr)) {
4299 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4300 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4301 std::string TypeAsString = "(";
4302 TypeAsString += QT.getAsString();
4303 TypeAsString += ")";
4304 ReplaceText(LocStart, endBuf-startBuf+1,
4305 TypeAsString.c_str(), TypeAsString.size());
4306 return;
4307 }
4308
Steve Naroff54055232008-10-27 17:20:55 +00004309 // advance the location to startArgList.
4310 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Steve Naroff54055232008-10-27 17:20:55 +00004312 while (*argPtr++ && (argPtr < endBuf)) {
4313 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004314 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004315 // Replace the '^' with '*'.
4316 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4317 ReplaceText(LocStart, 1, "*", 1);
4318 break;
4319 }
4320 }
4321 return;
4322}
4323
4324void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4325 SourceLocation DeclLoc = FD->getLocation();
4326 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004327
Steve Naroff54055232008-10-27 17:20:55 +00004328 // We have 1 or more arguments that have closure pointers.
4329 const char *startBuf = SM->getCharacterData(DeclLoc);
4330 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Steve Naroff54055232008-10-27 17:20:55 +00004332 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Steve Naroff54055232008-10-27 17:20:55 +00004334 parenCount++;
4335 // advance the location to startArgList.
4336 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4337 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004338
Steve Naroff54055232008-10-27 17:20:55 +00004339 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Steve Naroff54055232008-10-27 17:20:55 +00004341 while (*argPtr++ && parenCount) {
4342 switch (*argPtr) {
Mike Stump1eb44332009-09-09 15:08:12 +00004343 case '^':
Steve Naroff54055232008-10-27 17:20:55 +00004344 // Replace the '^' with '*'.
4345 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4346 ReplaceText(DeclLoc, 1, "*", 1);
4347 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004348 case '(':
4349 parenCount++;
Steve Naroff54055232008-10-27 17:20:55 +00004350 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004351 case ')':
Steve Naroff54055232008-10-27 17:20:55 +00004352 parenCount--;
4353 break;
4354 }
4355 }
4356 return;
4357}
4358
4359bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004360 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004361 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004362 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004363 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004364 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004365 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004366 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004367 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004368 }
4369 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004370 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004371 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004372 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004373 return true;
4374 }
4375 return false;
4376}
4377
Ted Kremenek8189cde2009-02-07 01:47:29 +00004378void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4379 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004380 const char *argPtr = strchr(Name, '(');
4381 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Steve Naroff54055232008-10-27 17:20:55 +00004383 LParen = argPtr; // output the start.
4384 argPtr++; // skip past the left paren.
4385 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004386
Steve Naroff54055232008-10-27 17:20:55 +00004387 while (*argPtr && parenCount) {
4388 switch (*argPtr) {
4389 case '(': parenCount++; break;
4390 case ')': parenCount--; break;
4391 default: break;
4392 }
4393 if (parenCount) argPtr++;
4394 }
4395 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4396 RParen = argPtr; // output the end
4397}
4398
4399void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4400 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4401 RewriteBlockPointerFunctionArgs(FD);
4402 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004403 }
Steve Naroff54055232008-10-27 17:20:55 +00004404 // Handle Variables and Typedefs.
4405 SourceLocation DeclLoc = ND->getLocation();
4406 QualType DeclT;
4407 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4408 DeclT = VD->getType();
4409 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4410 DeclT = TDD->getUnderlyingType();
4411 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4412 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004413 else
Steve Naroff54055232008-10-27 17:20:55 +00004414 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004415
Steve Naroff54055232008-10-27 17:20:55 +00004416 const char *startBuf = SM->getCharacterData(DeclLoc);
4417 const char *endBuf = startBuf;
4418 // scan backward (from the decl location) for the end of the previous decl.
4419 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4420 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Steve Naroff54055232008-10-27 17:20:55 +00004422 // *startBuf != '^' if we are dealing with a pointer to function that
4423 // may take block argument types (which will be handled below).
4424 if (*startBuf == '^') {
4425 // Replace the '^' with '*', computing a negative offset.
4426 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4427 ReplaceText(DeclLoc, 1, "*", 1);
4428 }
4429 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4430 // Replace the '^' with '*' for arguments.
4431 DeclLoc = ND->getLocation();
4432 startBuf = SM->getCharacterData(DeclLoc);
4433 const char *argListBegin, *argListEnd;
4434 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4435 while (argListBegin < argListEnd) {
4436 if (*argListBegin == '^') {
4437 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4438 ReplaceText(CaretLoc, 1, "*", 1);
4439 }
4440 argListBegin++;
4441 }
4442 }
4443 return;
4444}
4445
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004446
4447/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4448/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4449/// struct Block_byref_id_object *src) {
4450/// _Block_object_assign (&_dest->object, _src->object,
4451/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4452/// [|BLOCK_FIELD_IS_WEAK]) // object
4453/// _Block_object_assign(&_dest->object, _src->object,
4454/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4455/// [|BLOCK_FIELD_IS_WEAK]) // block
4456/// }
4457/// And:
4458/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4459/// _Block_object_dispose(_src->object,
4460/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4461/// [|BLOCK_FIELD_IS_WEAK]) // object
4462/// _Block_object_dispose(_src->object,
4463/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4464/// [|BLOCK_FIELD_IS_WEAK]) // block
4465/// }
4466
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004467std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4468 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004469 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004470 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004471 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004472 CopyDestroyCache.insert(flag);
4473 S = "static void __Block_byref_id_object_copy_";
4474 S += utostr(flag);
4475 S += "(void *dst, void *src) {\n";
4476
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004477 // offset into the object pointer is computed as:
4478 // void * + void* + int + int + void* + void *
4479 unsigned IntSize =
4480 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4481 unsigned VoidPtrSize =
4482 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4483
4484 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4485 S += " _Block_object_assign((char*)dst + ";
4486 S += utostr(offset);
4487 S += ", *(void * *) ((char*)src + ";
4488 S += utostr(offset);
4489 S += "), ";
4490 S += utostr(flag);
4491 S += ");\n}\n";
4492
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004493 S += "static void __Block_byref_id_object_dispose_";
4494 S += utostr(flag);
4495 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004496 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4497 S += utostr(offset);
4498 S += "), ";
4499 S += utostr(flag);
4500 S += ");\n}\n";
4501 return S;
4502}
4503
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004504/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4505/// the declaration into:
4506/// struct __Block_byref_ND {
4507/// void *__isa; // NULL for everything except __weak pointers
4508/// struct __Block_byref_ND *__forwarding;
4509/// int32_t __flags;
4510/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004511/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4512/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004513/// typex ND;
4514/// };
4515///
4516/// It then replaces declaration of ND variable with:
4517/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4518/// __size=sizeof(struct __Block_byref_ND),
4519/// ND=initializer-if-any};
4520///
4521///
4522void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004523 // Insert declaration for the function in which block literal is
4524 // used.
4525 if (CurFunctionDeclToDeclareForBlock)
4526 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004527 int flag = 0;
4528 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004529 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4530 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004531 SourceLocation X = ND->getLocEnd();
4532 X = SM->getInstantiationLoc(X);
4533 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004534 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004535 std::string ByrefType;
4536 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004537 ByrefType += " {\n";
4538 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004539 RewriteByRefString(ByrefType, Name, ND);
4540 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004541 ByrefType += " int __flags;\n";
4542 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004543 // Add void *__Block_byref_id_object_copy;
4544 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004545 QualType Ty = ND->getType();
4546 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4547 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004548 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4549 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004550 }
4551
4552 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004553 ByrefType += " " + Name + ";\n";
4554 ByrefType += "};\n";
4555 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004556 SourceLocation FunLocStart;
4557 if (CurFunctionDef)
4558 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4559 else {
4560 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4561 FunLocStart = CurMethodDef->getLocStart();
4562 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004563 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004564 if (Ty.isObjCGCWeak()) {
4565 flag |= BLOCK_FIELD_IS_WEAK;
4566 isa = 1;
4567 }
4568
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004569 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004570 flag = BLOCK_BYREF_CALLER;
4571 QualType Ty = ND->getType();
4572 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4573 if (Ty->isBlockPointerType())
4574 flag |= BLOCK_FIELD_IS_BLOCK;
4575 else
4576 flag |= BLOCK_FIELD_IS_OBJECT;
4577 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004578 if (!HF.empty())
4579 InsertText(FunLocStart, HF.c_str(), HF.size());
4580 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004581
4582 // struct __Block_byref_ND ND =
4583 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4584 // initializer-if-any};
4585 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004586 unsigned flags = 0;
4587 if (HasCopyAndDispose)
4588 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004589 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004590 ByrefType.clear();
4591 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004592 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004593 ByrefType += " " + Name + " = {(void*)";
4594 ByrefType += utostr(isa);
4595 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004596 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004597 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004598 ByrefType += "sizeof(";
4599 RewriteByRefString(ByrefType, Name, ND);
4600 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004601 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004602 ByrefType += ", __Block_byref_id_object_copy_";
4603 ByrefType += utostr(flag);
4604 ByrefType += ", __Block_byref_id_object_dispose_";
4605 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004606 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004607 ByrefType += "};\n";
4608 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4609 ByrefType.c_str(), ByrefType.size());
4610 }
4611 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004612 SourceLocation startLoc;
4613 Expr *E = ND->getInit();
4614 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4615 startLoc = ECE->getLParenLoc();
4616 else
4617 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004618 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004619 endBuf = SM->getCharacterData(startLoc);
4620
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004621 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004622 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004623 ByrefType += utostr(isa);
4624 ByrefType += ", &" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004625 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004626 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004627 ByrefType += "sizeof(";
4628 RewriteByRefString(ByrefType, Name, ND);
4629 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004630 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004631 ByrefType += "__Block_byref_id_object_copy_";
4632 ByrefType += utostr(flag);
4633 ByrefType += ", __Block_byref_id_object_dispose_";
4634 ByrefType += utostr(flag);
4635 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004636 }
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004637 ReplaceText(DeclLoc, endBuf-startBuf,
4638 ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004639
4640 // Complete the newly synthesized compound expression by inserting a right
4641 // curly brace before the end of the declaration.
4642 // FIXME: This approach avoids rewriting the initializer expression. It
4643 // also assumes there is only one declarator. For example, the following
4644 // isn't currently supported by this routine (in general):
4645 //
4646 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4647 //
4648 const char *startBuf = SM->getCharacterData(startLoc);
4649 const char *semiBuf = strchr(startBuf, ';');
4650 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4651 SourceLocation semiLoc =
4652 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4653
4654 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004655 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004656 return;
4657}
4658
Mike Stump1eb44332009-09-09 15:08:12 +00004659void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004660 // Add initializers for any closure decl refs.
4661 GetBlockDeclRefExprs(Exp->getBody());
4662 if (BlockDeclRefs.size()) {
4663 // Unique all "by copy" declarations.
4664 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4665 if (!BlockDeclRefs[i]->isByRef())
4666 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4667 // Unique all "by ref" declarations.
4668 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4669 if (BlockDeclRefs[i]->isByRef()) {
4670 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4671 }
4672 // Find any imported blocks...they will need special attention.
4673 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004674 if (BlockDeclRefs[i]->isByRef() ||
4675 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4676 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004677 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004678 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4679 }
4680 }
4681}
4682
Steve Narofffa15fd92008-10-28 20:29:00 +00004683FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4684 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004685 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004686 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004687 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004688 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004689}
4690
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004691Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004692 Blocks.push_back(Exp);
4693
4694 CollectBlockDeclRefInfo(Exp);
4695 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004696
Steve Narofffa15fd92008-10-28 20:29:00 +00004697 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004698 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004699 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004700 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004701 // Convert colons to underscores.
4702 std::string::size_type loc = 0;
4703 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4704 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004705 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004706 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Steve Narofffa15fd92008-10-28 20:29:00 +00004708 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004709
Steve Narofffa15fd92008-10-28 20:29:00 +00004710 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4711 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004712
Steve Narofffa15fd92008-10-28 20:29:00 +00004713 // Get a pointer to the function type so we can cast appropriately.
4714 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4715
4716 FunctionDecl *FD;
4717 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004718
Steve Narofffa15fd92008-10-28 20:29:00 +00004719 // Simulate a contructor call...
4720 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004721 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Steve Narofffa15fd92008-10-28 20:29:00 +00004723 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004724
Steve Narofffdc03722008-10-29 21:23:59 +00004725 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004726 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004727 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4728 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004729 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4730 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004731 InitExprs.push_back(castExpr);
4732
Steve Naroff01aec112009-12-06 21:14:13 +00004733 // Initialize the block descriptor.
4734 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Steve Naroff01aec112009-12-06 21:14:13 +00004736 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4737 &Context->Idents.get(DescData.c_str()),
4738 Context->VoidPtrTy, 0,
4739 VarDecl::Static);
4740 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4741 new (Context) DeclRefExpr(NewVD,
4742 Context->VoidPtrTy, SourceLocation()),
4743 UnaryOperator::AddrOf,
4744 Context->getPointerType(Context->VoidPtrTy),
4745 SourceLocation());
4746 InitExprs.push_back(DescRefExpr);
4747
Steve Narofffa15fd92008-10-28 20:29:00 +00004748 // Add initializers for any closure decl refs.
4749 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004750 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004751 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004752 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004753 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004754 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004755 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004756 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004757 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004758 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004759 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004760 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004761 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4762 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004763 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004764 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004765 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004768 }
4769 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004770 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004771 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004772 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004773 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4774 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004775 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004776 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004777 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 }
4779 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004780 if (ImportedBlockDecls.size()) {
4781 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4782 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004783 unsigned IntSize =
4784 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004785 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4786 Context->IntTy, SourceLocation());
4787 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004788 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004789 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4790 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004791 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004792 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004793 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004794 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4795 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004796 BlockDeclRefs.clear();
4797 BlockByRefDecls.clear();
4798 BlockByCopyDecls.clear();
4799 ImportedBlockDecls.clear();
4800 return NewRep;
4801}
4802
4803//===----------------------------------------------------------------------===//
4804// Function Body / Expression rewriting
4805//===----------------------------------------------------------------------===//
4806
Steve Naroffc77a6362008-12-04 16:24:46 +00004807// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4808// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4809// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4810// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4811// Since the rewriter isn't capable of rewriting rewritten code, it's important
4812// we get this right.
4813void RewriteObjC::CollectPropertySetters(Stmt *S) {
4814 // Perform a bottom up traversal of all children.
4815 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4816 CI != E; ++CI)
4817 if (*CI)
4818 CollectPropertySetters(*CI);
4819
4820 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4821 if (BinOp->isAssignmentOp()) {
4822 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4823 PropSetters[PRE] = BinOp;
4824 }
4825 }
4826}
4827
Steve Narofffa15fd92008-10-28 20:29:00 +00004828Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004829 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004830 isa<DoStmt>(S) || isa<ForStmt>(S))
4831 Stmts.push_back(S);
4832 else if (isa<ObjCForCollectionStmt>(S)) {
4833 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004834 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004835 }
Mike Stump1eb44332009-09-09 15:08:12 +00004836
Steve Narofffa15fd92008-10-28 20:29:00 +00004837 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004838
Steve Narofffa15fd92008-10-28 20:29:00 +00004839 // Perform a bottom up rewrite of all children.
4840 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4841 CI != E; ++CI)
4842 if (*CI) {
4843 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump1eb44332009-09-09 15:08:12 +00004844 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004845 *CI = newStmt;
4846 }
Mike Stump1eb44332009-09-09 15:08:12 +00004847
Steve Narofffa15fd92008-10-28 20:29:00 +00004848 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4849 // Rewrite the block body in place.
4850 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Steve Narofffa15fd92008-10-28 20:29:00 +00004852 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004853 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004854 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004855
Steve Narofffa15fd92008-10-28 20:29:00 +00004856 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4857 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004858 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004859 return blockTranscribed;
4860 }
4861 // Handle specific things.
4862 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4863 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004864
Steve Narofffa15fd92008-10-28 20:29:00 +00004865 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4866 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4867
Steve Naroffc77a6362008-12-04 16:24:46 +00004868 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4869 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4870 if (BinOp) {
4871 // Because the rewriter doesn't allow us to rewrite rewritten code,
4872 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004873 DisableReplaceStmt = true;
4874 // Save the source range. Even if we disable the replacement, the
4875 // rewritten node will have been inserted into the tree. If the synthesized
4876 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004877 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004878 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4879 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004880 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004881 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004882 //
4883 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4884 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4885 // to see the original expression). Consider this example:
4886 //
4887 // Foo *obj1, *obj2;
4888 //
4889 // obj1.i = [obj2 rrrr];
4890 //
4891 // 'BinOp' for the previous expression looks like:
4892 //
4893 // (BinaryOperator 0x231ccf0 'int' '='
4894 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4895 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4896 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4897 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4898 //
4899 // 'newStmt' represents the rewritten message expression. For example:
4900 //
4901 // (CallExpr 0x231d300 'id':'struct objc_object *'
4902 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4903 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4904 // (CStyleCastExpr 0x231d220 'void *'
4905 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4906 //
4907 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4908 // can be used as the setter argument. ReplaceStmt() will still 'see'
4909 // the original RHS (since we haven't altered BinOp).
4910 //
Mike Stump1eb44332009-09-09 15:08:12 +00004911 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004912 // node. As a result, we now leak the original AST nodes.
4913 //
Steve Naroffb619d952008-12-09 12:56:34 +00004914 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004915 } else {
4916 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004917 }
4918 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004919 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4920 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004921
Steve Narofffa15fd92008-10-28 20:29:00 +00004922 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4923 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Steve Narofffa15fd92008-10-28 20:29:00 +00004925 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004926#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004927 // Before we rewrite it, put the original message expression in a comment.
4928 SourceLocation startLoc = MessExpr->getLocStart();
4929 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004930
Steve Narofffa15fd92008-10-28 20:29:00 +00004931 const char *startBuf = SM->getCharacterData(startLoc);
4932 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004933
Steve Narofffa15fd92008-10-28 20:29:00 +00004934 std::string messString;
4935 messString += "// ";
4936 messString.append(startBuf, endBuf-startBuf+1);
4937 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004938
4939 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004940 // InsertText(clang::SourceLocation, char const*, unsigned int).
4941 // InsertText(startLoc, messString.c_str(), messString.size());
4942 // Tried this, but it didn't work either...
4943 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004944#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004945 return RewriteMessageExpr(MessExpr);
4946 }
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Steve Narofffa15fd92008-10-28 20:29:00 +00004948 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4949 return RewriteObjCTryStmt(StmtTry);
4950
4951 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4952 return RewriteObjCSynchronizedStmt(StmtTry);
4953
4954 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4955 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004956
Steve Narofffa15fd92008-10-28 20:29:00 +00004957 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4958 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004959
4960 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004961 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004962 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004963 OrigStmtRange.getEnd());
4964 if (BreakStmt *StmtBreakStmt =
4965 dyn_cast<BreakStmt>(S))
4966 return RewriteBreakStmt(StmtBreakStmt);
4967 if (ContinueStmt *StmtContinueStmt =
4968 dyn_cast<ContinueStmt>(S))
4969 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004970
4971 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004972 // and cast exprs.
4973 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4974 // FIXME: What we're doing here is modifying the type-specifier that
4975 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004976 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004977 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4978 // the context of an ObjCForCollectionStmt. For example:
4979 // NSArray *someArray;
4980 // for (id <FooProtocol> index in someArray) ;
4981 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4982 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00004983 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004984 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004985
Steve Narofffa15fd92008-10-28 20:29:00 +00004986 // Blocks rewrite rules.
4987 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4988 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004989 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004990 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004991 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004992 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004993 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004994 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004995 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004996 if (VD->hasAttr<BlocksAttr>()) {
4997 static unsigned uniqueByrefDeclCount = 0;
4998 assert(!BlockByRefDeclNo.count(ND) &&
4999 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5000 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005001 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005002 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005003 }
5004 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005005 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005006 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005007 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005008 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5009 }
5010 }
5011 }
Mike Stump1eb44332009-09-09 15:08:12 +00005012
Steve Narofffa15fd92008-10-28 20:29:00 +00005013 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5014 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005015
5016 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005017 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5018 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005019 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5020 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005021 && "Statement stack mismatch");
5022 Stmts.pop_back();
5023 }
5024 // Handle blocks rewriting.
5025 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5026 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005027 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005028 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005029 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5030 ValueDecl *VD = DRE->getDecl();
5031 if (VD->hasAttr<BlocksAttr>())
5032 return RewriteBlockDeclRefExpr(DRE);
5033 }
5034
Steve Narofffa15fd92008-10-28 20:29:00 +00005035 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005036 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005037 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005038 ReplaceStmt(S, BlockCall);
5039 return BlockCall;
5040 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005041 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005042 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005043 RewriteCastExpr(CE);
5044 }
5045#if 0
5046 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005047 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005048 // Get the new text.
5049 std::string SStr;
5050 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005051 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005052 const std::string &Str = Buf.str();
5053
5054 printf("CAST = %s\n", &Str[0]);
5055 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5056 delete S;
5057 return Replacement;
5058 }
5059#endif
5060 // Return this stmt unmodified.
5061 return S;
5062}
5063
Steve Naroff3d7e7862009-12-05 15:55:59 +00005064void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5065 for (RecordDecl::field_iterator i = RD->field_begin(),
5066 e = RD->field_end(); i != e; ++i) {
5067 FieldDecl *FD = *i;
5068 if (isTopLevelBlockPointerType(FD->getType()))
5069 RewriteBlockPointerDecl(FD);
5070 if (FD->getType()->isObjCQualifiedIdType() ||
5071 FD->getType()->isObjCQualifiedInterfaceType())
5072 RewriteObjCQualifiedInterfaceTypes(FD);
5073 }
5074}
5075
Steve Narofffa15fd92008-10-28 20:29:00 +00005076/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5077/// main file of the input.
5078void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5079 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005080 if (FD->isOverloadedOperator())
5081 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005082
Steve Narofffa15fd92008-10-28 20:29:00 +00005083 // Since function prototypes don't have ParmDecl's, we check the function
5084 // prototype. This enables us to rewrite function declarations and
5085 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005086 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005087
Sebastian Redld3a413d2009-04-26 20:35:05 +00005088 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005089 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005090 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005091 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005092 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005093 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005094 Body =
5095 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5096 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005097 CurrentBody = 0;
5098 if (PropParentMap) {
5099 delete PropParentMap;
5100 PropParentMap = 0;
5101 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005102 // This synthesizes and inserts the block "impl" struct, invoke function,
5103 // and any copy/dispose helper functions.
5104 InsertBlockLiteralsWithinFunction(FD);
5105 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005106 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005107 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005108 return;
5109 }
5110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005111 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005112 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005113 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005114 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005115 Body =
5116 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5117 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005118 CurrentBody = 0;
5119 if (PropParentMap) {
5120 delete PropParentMap;
5121 PropParentMap = 0;
5122 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005123 InsertBlockLiteralsWithinMethod(MD);
5124 CurMethodDef = 0;
5125 }
5126 }
5127 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5128 ClassImplementation.push_back(CI);
5129 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5130 CategoryImplementation.push_back(CI);
5131 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5132 RewriteForwardClassDecl(CD);
5133 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5134 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005135 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005136 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005137 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005138 CheckFunctionPointerDecl(VD->getType(), VD);
5139 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005140 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005141 RewriteCastExpr(CE);
5142 }
5143 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005144 } else if (VD->getType()->isRecordType()) {
5145 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5146 if (RD->isDefinition())
5147 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005148 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005149 if (VD->getInit()) {
5150 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005151 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005152 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005153 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005154 CurrentBody = 0;
5155 if (PropParentMap) {
5156 delete PropParentMap;
5157 PropParentMap = 0;
5158 }
Mike Stump1eb44332009-09-09 15:08:12 +00005159 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005160 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005161 GlobalVarDecl = 0;
5162
5163 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005164 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005165 RewriteCastExpr(CE);
5166 }
5167 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005168 return;
5169 }
5170 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005171 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005172 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005173 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005174 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005175 else if (TD->getUnderlyingType()->isRecordType()) {
5176 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5177 if (RD->isDefinition())
5178 RewriteRecordBody(RD);
5179 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005180 return;
5181 }
5182 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005183 if (RD->isDefinition())
5184 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005185 return;
5186 }
5187 // Nothing yet.
5188}
5189
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005190void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005191 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005192
Steve Narofffa15fd92008-10-28 20:29:00 +00005193 // Rewrite tabs if we care.
5194 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005195
Steve Narofffa15fd92008-10-28 20:29:00 +00005196 if (Diags.hasErrorOccurred())
5197 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005198
Steve Narofffa15fd92008-10-28 20:29:00 +00005199 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005200
Steve Naroff621edce2009-04-29 16:37:50 +00005201 // Here's a great place to add any extra declarations that may be needed.
5202 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005203 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005204 E = ProtocolExprDecls.end(); I != E; ++I)
5205 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5206
Mike Stump1eb44332009-09-09 15:08:12 +00005207 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005208 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005209 if (ClassImplementation.size() || CategoryImplementation.size())
5210 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005211
Steve Narofffa15fd92008-10-28 20:29:00 +00005212 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5213 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005214 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005215 Rewrite.getRewriteBufferFor(MainFileID)) {
5216 //printf("Changed:\n");
5217 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5218 } else {
5219 fprintf(stderr, "No changes\n");
5220 }
Steve Narofface66252008-11-13 20:07:04 +00005221
Steve Naroff621edce2009-04-29 16:37:50 +00005222 if (ClassImplementation.size() || CategoryImplementation.size() ||
5223 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005224 // Rewrite Objective-c meta data*
5225 std::string ResultStr;
5226 SynthesizeMetaDataIntoBuffer(ResultStr);
5227 // Emit metadata.
5228 *OutFile << ResultStr;
5229 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005230 OutFile->flush();
5231}
5232