blob: 28485326009a423a908b4a087176e302492704c1 [file] [log] [blame]
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001//===--- RewriteBlocks.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the closure rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Steve Naroff1c9f81b2008-09-17 00:13:27 +000015#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/Basic/SourceManager.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/Diagnostic.h"
21#include "clang/Basic/LangOptions.h"
22#include "llvm/Support/MemoryBuffer.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include <sstream>
26
27using namespace clang;
28using llvm::utostr;
29
30namespace {
31
32class RewriteBlocks : public ASTConsumer {
33 Rewriter Rewrite;
34 Diagnostic &Diags;
35 const LangOptions &LangOpts;
36 unsigned RewriteFailedDiag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000037
38 ASTContext *Context;
39 SourceManager *SM;
Chris Lattner2b2453a2009-01-17 06:22:33 +000040 FileID MainFileID;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000041 const char *MainFileStart, *MainFileEnd;
42
43 // Block expressions.
44 llvm::SmallVector<BlockExpr *, 32> Blocks;
45 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
46 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
47
48 // Block related declarations.
49 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
50 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Steve Naroff4e13b762008-10-03 20:28:15 +000051 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Steve Naroff70f95502008-10-04 17:06:23 +000052
53 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000054
55 // The function/method we are rewriting.
56 FunctionDecl *CurFunctionDef;
57 ObjCMethodDecl *CurMethodDef;
58
59 bool IsHeader;
Steve Naroffa0b75cf2008-10-02 23:30:43 +000060
61 std::string Preamble;
Steve Naroff1c9f81b2008-09-17 00:13:27 +000062public:
Eli Friedman66d6f042009-05-18 22:20:00 +000063 RewriteBlocks(std::string inFile, Diagnostic &D,
Steve Naroff13188952008-09-18 14:10:13 +000064 const LangOptions &LOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000065 ~RewriteBlocks() {
66 // Get the buffer corresponding to MainFileID.
67 // If we haven't changed it, then we are done.
68 if (const RewriteBuffer *RewriteBuf =
69 Rewrite.getRewriteBufferFor(MainFileID)) {
70 std::string S(RewriteBuf->begin(), RewriteBuf->end());
71 printf("%s\n", S.c_str());
72 } else {
73 printf("No changes\n");
74 }
75 }
76
77 void Initialize(ASTContext &context);
78
79 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen);
80 void ReplaceText(SourceLocation Start, unsigned OrigLength,
81 const char *NewStr, unsigned NewLength);
82
83 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +000084 virtual void HandleTopLevelDecl(DeclGroupRef D) {
85 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
86 HandleTopLevelSingleDecl(*I);
87 }
88 void HandleTopLevelSingleDecl(Decl *D);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000089 void HandleDeclInMainFile(Decl *D);
90
91 // Top level
92 Stmt *RewriteFunctionBody(Stmt *S);
93 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
94 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
95
96 // Block specific rewrite rules.
Steve Naroff70f95502008-10-04 17:06:23 +000097 std::string SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD=0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +000098
99 void RewriteBlockCall(CallExpr *Exp);
100 void RewriteBlockPointerDecl(NamedDecl *VD);
Steve Naroff5e52b172008-10-04 18:52:47 +0000101 void RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000102 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
103
Steve Naroff4e13b762008-10-03 20:28:15 +0000104 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
105 const char *funcName, std::string Tag);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000106 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
107 const char *funcName, std::string Tag);
Steve Naroffacba0f22008-10-04 23:47:37 +0000108 std::string SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
109 bool hasCopyDisposeHelpers);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000110 std::string SynthesizeBlockCall(CallExpr *Exp);
111 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
112 const char *FunName);
113
Steve Naroffd3f77902008-10-05 00:06:12 +0000114 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000115 void GetBlockCallExprs(Stmt *S);
Steve Naroffacba0f22008-10-04 23:47:37 +0000116 void GetBlockDeclRefExprs(Stmt *S);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000117
118 // We avoid calling Type::isBlockPointerType(), since it operates on the
119 // canonical type. We only care if the top-level type is a closure pointer.
120 bool isBlockPointerType(QualType T) { return isa<BlockPointerType>(T); }
121
122 // FIXME: This predicate seems like it would be useful to add to ASTContext.
123 bool isObjCType(QualType T) {
124 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
125 return false;
126
127 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
128
129 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
130 OCT == Context->getCanonicalType(Context->getObjCClassType()))
131 return true;
132
133 if (const PointerType *PT = OCT->getAsPointerType()) {
134 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000135 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000136 return true;
137 }
138 return false;
139 }
140 // ObjC rewrite methods.
141 void RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl);
142 void RewriteCategoryDecl(ObjCCategoryDecl *CatDecl);
143 void RewriteProtocolDecl(ObjCProtocolDecl *PDecl);
144 void RewriteMethodDecl(ObjCMethodDecl *MDecl);
Steve Naroffca743602008-10-15 18:38:58 +0000145
Douglas Gregor72564e72009-02-26 23:50:07 +0000146 void RewriteFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroffca743602008-10-15 18:38:58 +0000147 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
148 void RewriteCastExpr(CastExpr *CE);
Steve Naroffeab5f632008-09-23 19:24:41 +0000149
Steve Naroffca743602008-10-15 18:38:58 +0000150 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000151 void GetExtentOfArgList(const char *Name, const char *&LParen, const char *&RParen);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000152};
153
154}
155
156static bool IsHeaderFile(const std::string &Filename) {
157 std::string::size_type DotPos = Filename.rfind('.');
158
159 if (DotPos == std::string::npos) {
160 // no file extension
161 return false;
162 }
163
164 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
165 // C header: .h
166 // C++ header: .hh or .H;
167 return Ext == "h" || Ext == "hh" || Ext == "H";
168}
169
Eli Friedman66d6f042009-05-18 22:20:00 +0000170RewriteBlocks::RewriteBlocks(std::string inFile,
Steve Naroff13188952008-09-18 14:10:13 +0000171 Diagnostic &D, const LangOptions &LOpts) :
172 Diags(D), LangOpts(LOpts) {
173 IsHeader = IsHeaderFile(inFile);
Steve Naroff13188952008-09-18 14:10:13 +0000174 CurFunctionDef = 0;
175 CurMethodDef = 0;
176 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
177 "rewriting failed");
Steve Naroff13188952008-09-18 14:10:13 +0000178}
179
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000180ASTConsumer *clang::CreateBlockRewriter(const std::string& InFile,
181 Diagnostic &Diags,
182 const LangOptions &LangOpts) {
Eli Friedman66d6f042009-05-18 22:20:00 +0000183 return new RewriteBlocks(InFile, Diags, LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000184}
185
186void RewriteBlocks::Initialize(ASTContext &context) {
187 Context = &context;
188 SM = &Context->getSourceManager();
189
190 // Get the ID and start/end of the main file.
191 MainFileID = SM->getMainFileID();
192 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
193 MainFileStart = MainBuf->getBufferStart();
194 MainFileEnd = MainBuf->getBufferEnd();
195
Chris Lattner2c78b872009-04-14 23:22:57 +0000196 Rewrite.setSourceMgr(Context->getSourceManager(), LangOpts);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000197
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000198 if (IsHeader)
199 Preamble = "#pragma once\n";
200 Preamble += "#ifndef BLOCK_IMPL\n";
201 Preamble += "#define BLOCK_IMPL\n";
202 Preamble += "struct __block_impl {\n";
203 Preamble += " void *isa;\n";
204 Preamble += " int Flags;\n";
205 Preamble += " int Size;\n";
206 Preamble += " void *FuncPtr;\n";
207 Preamble += "};\n";
208 Preamble += "enum {\n";
209 Preamble += " BLOCK_HAS_COPY_DISPOSE = (1<<25),\n";
210 Preamble += " BLOCK_IS_GLOBAL = (1<<28)\n";
211 Preamble += "};\n";
212 if (LangOpts.Microsoft)
213 Preamble += "#define __OBJC_RW_EXTERN extern \"C\" __declspec(dllimport)\n";
214 else
215 Preamble += "#define __OBJC_RW_EXTERN extern\n";
216 Preamble += "// Runtime copy/destroy helper functions\n";
217 Preamble += "__OBJC_RW_EXTERN void _Block_copy_assign(void *, void *);\n";
218 Preamble += "__OBJC_RW_EXTERN void _Block_byref_assign_copy(void *, void *);\n";
219 Preamble += "__OBJC_RW_EXTERN void _Block_destroy(void *);\n";
220 Preamble += "__OBJC_RW_EXTERN void _Block_byref_release(void *);\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000221 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteGlobalBlock;\n";
222 Preamble += "__OBJC_RW_EXTERN void *_NSConcreteStackBlock;\n";
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000223 Preamble += "#endif\n";
224
Chris Lattner2b2453a2009-01-17 06:22:33 +0000225 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000226 Preamble.c_str(), Preamble.size());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000227}
228
229void RewriteBlocks::InsertText(SourceLocation Loc, const char *StrData,
230 unsigned StrLen)
231{
232 if (!Rewrite.InsertText(Loc, StrData, StrLen))
233 return;
234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235}
236
237void RewriteBlocks::ReplaceText(SourceLocation Start, unsigned OrigLength,
238 const char *NewStr, unsigned NewLength) {
239 if (!Rewrite.ReplaceText(Start, OrigLength, NewStr, NewLength))
240 return;
241 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
242}
243
244void RewriteBlocks::RewriteMethodDecl(ObjCMethodDecl *Method) {
245 bool haveBlockPtrs = false;
246 for (ObjCMethodDecl::param_iterator I = Method->param_begin(),
247 E = Method->param_end(); I != E; ++I)
248 if (isBlockPointerType((*I)->getType()))
249 haveBlockPtrs = true;
250
251 if (!haveBlockPtrs)
252 return;
253
254 // Do a fuzzy rewrite.
255 // We have 1 or more arguments that have closure pointers.
256 SourceLocation Loc = Method->getLocStart();
257 SourceLocation LocEnd = Method->getLocEnd();
258 const char *startBuf = SM->getCharacterData(Loc);
259 const char *endBuf = SM->getCharacterData(LocEnd);
260
261 const char *methodPtr = startBuf;
Steve Naroff8af6a452008-10-02 17:12:56 +0000262 std::string Tag = "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000263
264 while (*methodPtr++ && (methodPtr != endBuf)) {
265 switch (*methodPtr) {
266 case ':':
267 methodPtr++;
268 if (*methodPtr == '(') {
269 const char *scanType = ++methodPtr;
270 bool foundBlockPointer = false;
271 unsigned parenCount = 1;
272
273 while (parenCount) {
274 switch (*scanType) {
275 case '(':
276 parenCount++;
277 break;
278 case ')':
279 parenCount--;
280 break;
281 case '^':
282 foundBlockPointer = true;
283 break;
284 }
285 scanType++;
286 }
287 if (foundBlockPointer) {
288 // advance the location to startArgList.
289 Loc = Loc.getFileLocWithOffset(methodPtr-startBuf);
290 assert((Loc.isValid()) && "Invalid Loc");
291 ReplaceText(Loc, scanType-methodPtr-1, Tag.c_str(), Tag.size());
292
293 // Advance startBuf. Since the underlying buffer has changed,
294 // it's very important to advance startBuf (so we can correctly
295 // compute a relative Loc the next time around).
296 startBuf = methodPtr;
297 }
298 // Advance the method ptr to the end of the type.
299 methodPtr = scanType;
300 }
301 break;
302 }
303 }
304 return;
305}
306
307void RewriteBlocks::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000308 for (ObjCInterfaceDecl::instmeth_iterator
309 I = ClassDecl->instmeth_begin(*Context),
310 E = ClassDecl->instmeth_end(*Context);
311 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000312 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000313 for (ObjCInterfaceDecl::classmeth_iterator
314 I = ClassDecl->classmeth_begin(*Context),
315 E = ClassDecl->classmeth_end(*Context);
316 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000317 RewriteMethodDecl(*I);
318}
319
320void RewriteBlocks::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000321 for (ObjCCategoryDecl::instmeth_iterator
322 I = CatDecl->instmeth_begin(*Context),
323 E = CatDecl->instmeth_end(*Context);
324 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000325 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000326 for (ObjCCategoryDecl::classmeth_iterator
327 I = CatDecl->classmeth_begin(*Context),
328 E = CatDecl->classmeth_end(*Context);
329 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000330 RewriteMethodDecl(*I);
331}
332
333void RewriteBlocks::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000334 for (ObjCProtocolDecl::instmeth_iterator
335 I = PDecl->instmeth_begin(*Context),
336 E = PDecl->instmeth_end(*Context);
337 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000338 RewriteMethodDecl(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000339 for (ObjCProtocolDecl::classmeth_iterator
340 I = PDecl->classmeth_begin(*Context),
341 E = PDecl->classmeth_end(*Context);
342 I != E; ++I)
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000343 RewriteMethodDecl(*I);
344}
345
346//===----------------------------------------------------------------------===//
347// Top Level Driver Code
348//===----------------------------------------------------------------------===//
349
Chris Lattner682bf922009-03-29 16:50:03 +0000350void RewriteBlocks::HandleTopLevelSingleDecl(Decl *D) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000351 // Two cases: either the decl could be in the main file, or it could be in a
352 // #included file. If the former, rewrite it now. If the later, check to see
353 // if we rewrote the #include/#import.
354 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000355 Loc = SM->getInstantiationLoc(Loc);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000356
357 // If this is for a builtin, ignore it.
358 if (Loc.isInvalid()) return;
359
360 if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D))
361 RewriteInterfaceDecl(MD);
362 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D))
363 RewriteCategoryDecl(CD);
364 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
365 RewriteProtocolDecl(PD);
366
367 // If we have a decl in the main file, see if we should rewrite it.
Chris Lattner23f2c582009-01-25 22:02:19 +0000368 if (SM->isFromMainFile(Loc))
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000369 HandleDeclInMainFile(D);
370 return;
371}
372
373std::string RewriteBlocks::SynthesizeBlockFunc(BlockExpr *CE, int i,
374 const char *funcName,
375 std::string Tag) {
376 const FunctionType *AFT = CE->getFunctionType();
377 QualType RT = AFT->getResultType();
Steve Naroff48a8c612008-10-03 12:09:49 +0000378 std::string StructRef = "struct " + Tag;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000379 std::string S = "static " + RT.getAsString() + " __" +
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000380 funcName + "_" + "block_func_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000381
Steve Naroff56ee6892008-10-08 17:01:13 +0000382 BlockDecl *BD = CE->getBlockDecl();
383
Douglas Gregor72564e72009-02-26 23:50:07 +0000384 if (isa<FunctionNoProtoType>(AFT)) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000385 S += "()";
Steve Naroff56ee6892008-10-08 17:01:13 +0000386 } else if (BD->param_empty()) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000387 S += "(" + StructRef + " *__cself)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000388 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +0000389 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000390 assert(FT && "SynthesizeBlockFunc: No function proto");
391 S += '(';
392 // first add the implicit argument.
Steve Naroff48a8c612008-10-03 12:09:49 +0000393 S += StructRef + " *__cself, ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000394 std::string ParamStr;
Steve Naroff56ee6892008-10-08 17:01:13 +0000395 for (BlockDecl::param_iterator AI = BD->param_begin(),
396 E = BD->param_end(); AI != E; ++AI) {
397 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000398 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000399 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000400 S += ParamStr;
401 }
402 if (FT->isVariadic()) {
Steve Naroff56ee6892008-10-08 17:01:13 +0000403 if (!BD->param_empty()) S += ", ";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000404 S += "...";
405 }
406 S += ')';
407 }
408 S += " {\n";
409
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000410 // Create local declarations to avoid rewriting all closure decl ref exprs.
411 // First, emit a declaration for all "by ref" decls.
412 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
413 E = BlockByRefDecls.end(); I != E; ++I) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000414 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000415 std::string Name = (*I)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000416 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
417 Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000418 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000419 }
420 // Next, emit a declaration for all "by copy" declarations.
421 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
422 E = BlockByCopyDecls.end(); I != E; ++I) {
423 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000424 std::string Name = (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000425 // Handle nested closure invocation. For example:
426 //
427 // void (^myImportedClosure)(void);
428 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
429 //
430 // void (^anotherClosure)(void);
431 // anotherClosure = ^(void) {
432 // myImportedClosure(); // import and invoke the closure
433 // };
434 //
435 if (isBlockPointerType((*I)->getType()))
Steve Naroff8af6a452008-10-02 17:12:56 +0000436 S += "struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000437 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000438 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000439 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000440 }
Steve Naroff70f95502008-10-04 17:06:23 +0000441 std::string RewrittenStr = RewrittenBlockExprs[CE];
442 const char *cstr = RewrittenStr.c_str();
443 while (*cstr++ != '{') ;
444 S += cstr;
445 S += "\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000446 return S;
447}
448
Steve Naroff4e13b762008-10-03 20:28:15 +0000449std::string RewriteBlocks::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
450 const char *funcName,
451 std::string Tag) {
452 std::string StructRef = "struct " + Tag;
453 std::string S = "static void __";
454
455 S += funcName;
456 S += "_block_copy_" + utostr(i);
457 S += "(" + StructRef;
458 S += "*dst, " + StructRef;
459 S += "*src) {";
460 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
461 E = ImportedBlockDecls.end(); I != E; ++I) {
462 S += "_Block_copy_assign(&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000463 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000464 S += ", src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000465 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000466 S += ");}";
467 }
468 S += "\nstatic void __";
469 S += funcName;
470 S += "_block_dispose_" + utostr(i);
471 S += "(" + StructRef;
472 S += "*src) {";
473 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
474 E = ImportedBlockDecls.end(); I != E; ++I) {
475 S += "_Block_destroy(src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000476 S += (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000477 S += ");";
478 }
479 S += "}\n";
480 return S;
481}
482
Steve Naroffacba0f22008-10-04 23:47:37 +0000483std::string RewriteBlocks::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
484 bool hasCopyDisposeHelpers) {
Steve Naroff48a8c612008-10-03 12:09:49 +0000485 std::string S = "struct " + Tag;
486 std::string Constructor = " " + Tag;
487
488 S += " {\n struct __block_impl impl;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000489
490 if (hasCopyDisposeHelpers)
491 S += " void *copy;\n void *dispose;\n";
492
Steve Naroff48a8c612008-10-03 12:09:49 +0000493 Constructor += "(void *fp";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000494
Steve Naroffacba0f22008-10-04 23:47:37 +0000495 if (hasCopyDisposeHelpers)
496 Constructor += ", void *copyHelp, void *disposeHelp";
497
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000498 if (BlockDeclRefs.size()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000499 // Output all "by copy" declarations.
500 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
501 E = BlockByCopyDecls.end(); I != E; ++I) {
502 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000503 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000504 std::string ArgName = "_" + FieldName;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000505 // Handle nested closure invocation. For example:
506 //
507 // void (^myImportedBlock)(void);
508 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
509 //
510 // void (^anotherBlock)(void);
511 // anotherBlock = ^(void) {
512 // myImportedBlock(); // import and invoke the closure
513 // };
514 //
Steve Naroff4e13b762008-10-03 20:28:15 +0000515 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000516 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000517 Constructor += ", void *" + ArgName;
518 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000519 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
520 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff4e13b762008-10-03 20:28:15 +0000521 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000522 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000523 S += FieldName + ";\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000524 }
525 // Output all "by ref" declarations.
526 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
527 E = BlockByRefDecls.end(); I != E; ++I) {
528 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000529 std::string FieldName = (*I)->getNameAsString();
Steve Naroff4e13b762008-10-03 20:28:15 +0000530 std::string ArgName = "_" + FieldName;
531 // Handle nested closure invocation. For example:
532 //
533 // void (^myImportedBlock)(void);
534 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
535 //
536 // void (^anotherBlock)(void);
537 // anotherBlock = ^(void) {
538 // myImportedBlock(); // import and invoke the closure
539 // };
540 //
541 if (isBlockPointerType((*I)->getType())) {
Steve Naroff8af6a452008-10-02 17:12:56 +0000542 S += "struct __block_impl *";
Steve Naroff4e13b762008-10-03 20:28:15 +0000543 Constructor += ", void *" + ArgName;
544 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000545 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
546 Context->PrintingPolicy);
547 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
548 Context->PrintingPolicy);
Steve Naroff4e13b762008-10-03 20:28:15 +0000549 Constructor += ", " + ArgName;
Steve Naroff48a8c612008-10-03 12:09:49 +0000550 }
Steve Naroff4e13b762008-10-03 20:28:15 +0000551 S += FieldName + "; // by ref\n";
Steve Naroff48a8c612008-10-03 12:09:49 +0000552 }
553 // Finish writing the constructor.
554 // FIXME: handle NSConcreteGlobalBlock.
555 Constructor += ", int flags=0) {\n";
Steve Naroff83ba14e2008-10-03 15:04:50 +0000556 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
Steve Naroff48a8c612008-10-03 12:09:49 +0000557 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
558
Steve Naroffacba0f22008-10-04 23:47:37 +0000559 if (hasCopyDisposeHelpers)
560 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
561
Steve Naroff48a8c612008-10-03 12:09:49 +0000562 // Initialize all "by copy" arguments.
563 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
564 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000565 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000566 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000567 if (isBlockPointerType((*I)->getType()))
568 Constructor += Name + " = (struct __block_impl *)_";
569 else
570 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000571 Constructor += Name + ";\n";
572 }
573 // Initialize all "by ref" arguments.
574 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
575 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000576 std::string Name = (*I)->getNameAsString();
Steve Naroff48a8c612008-10-03 12:09:49 +0000577 Constructor += " ";
Steve Naroff4e13b762008-10-03 20:28:15 +0000578 if (isBlockPointerType((*I)->getType()))
579 Constructor += Name + " = (struct __block_impl *)_";
580 else
581 Constructor += Name + " = _";
Steve Naroff48a8c612008-10-03 12:09:49 +0000582 Constructor += Name + ";\n";
583 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000584 } else {
585 // Finish writing the constructor.
586 // FIXME: handle NSConcreteGlobalBlock.
587 Constructor += ", int flags=0) {\n";
588 Constructor += " impl.isa = 0/*&_NSConcreteStackBlock*/;\n impl.Size = sizeof(";
589 Constructor += Tag + ");\n impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Steve Naroffacba0f22008-10-04 23:47:37 +0000590 if (hasCopyDisposeHelpers)
591 Constructor += " copy = copyHelp;\n dispose = disposeHelp;\n";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000592 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000593 Constructor += " ";
594 Constructor += "}\n";
595 S += Constructor;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000596 S += "};\n";
597 return S;
598}
599
600void RewriteBlocks::SynthesizeBlockLiterals(SourceLocation FunLocStart,
601 const char *FunName) {
602 // Insert closures that were part of the function.
603 for (unsigned i = 0; i < Blocks.size(); i++) {
Steve Naroffacba0f22008-10-04 23:47:37 +0000604
Steve Naroffd3f77902008-10-05 00:06:12 +0000605 CollectBlockDeclRefInfo(Blocks[i]);
606
Steve Naroff48a8c612008-10-03 12:09:49 +0000607 std::string Tag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000608
Steve Naroffacba0f22008-10-04 23:47:37 +0000609 std::string CI = SynthesizeBlockImpl(Blocks[i], Tag,
610 ImportedBlockDecls.size() > 0);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000611
612 InsertText(FunLocStart, CI.c_str(), CI.size());
Steve Naroff4e13b762008-10-03 20:28:15 +0000613
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000614 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, Tag);
615
616 InsertText(FunLocStart, CF.c_str(), CF.size());
617
Steve Naroff4e13b762008-10-03 20:28:15 +0000618 if (ImportedBlockDecls.size()) {
619 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, Tag);
620 InsertText(FunLocStart, HF.c_str(), HF.size());
621 }
622
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000623 BlockDeclRefs.clear();
624 BlockByRefDecls.clear();
625 BlockByCopyDecls.clear();
626 BlockCallExprs.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +0000627 ImportedBlockDecls.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000628 }
629 Blocks.clear();
Steve Naroff8e9216d2008-10-04 17:10:02 +0000630 RewrittenBlockExprs.clear();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000631}
632
633void RewriteBlocks::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Steve Naroff3ad29e22008-10-03 00:12:09 +0000634 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +0000635 const char *FuncName = FD->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000636
637 SynthesizeBlockLiterals(FunLocStart, FuncName);
638}
639
640void RewriteBlocks::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
641 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +0000642 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000643 // Convert colons to underscores.
644 std::string::size_type loc = 0;
645 while ((loc = FuncName.find(":", loc)) != std::string::npos)
646 FuncName.replace(loc, 1, "_");
647
648 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
649}
650
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000651void RewriteBlocks::GetBlockDeclRefExprs(Stmt *S) {
652 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
653 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000654 if (*CI) {
655 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
656 GetBlockDeclRefExprs(CBE->getBody());
657 else
658 GetBlockDeclRefExprs(*CI);
659 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000660 // Handle specific things.
661 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
662 // FIXME: Handle enums.
663 if (!isa<FunctionDecl>(CDRE->getDecl()))
664 BlockDeclRefs.push_back(CDRE);
665 return;
666}
667
668void RewriteBlocks::GetBlockCallExprs(Stmt *S) {
669 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
670 CI != E; ++CI)
Steve Naroff84a969f2008-10-08 17:31:13 +0000671 if (*CI) {
672 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
673 GetBlockCallExprs(CBE->getBody());
674 else
675 GetBlockCallExprs(*CI);
676 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000677
678 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff4e13b762008-10-03 20:28:15 +0000679 if (CE->getCallee()->getType()->isBlockPointerType()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000680 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
Steve Naroff4e13b762008-10-03 20:28:15 +0000681 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000682 }
683 return;
684}
685
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000686std::string RewriteBlocks::SynthesizeBlockCall(CallExpr *Exp) {
687 // Navigate to relevant type information.
Steve Naroffcc2ece22008-09-24 22:46:45 +0000688 const char *closureName = 0;
689 const BlockPointerType *CPT = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000690
691 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000692 closureName = DRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000693 CPT = DRE->getType()->getAsBlockPointerType();
694 } else if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000695 closureName = CDRE->getDecl()->getNameAsCString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000696 CPT = CDRE->getType()->getAsBlockPointerType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000697 } else if (MemberExpr *MExpr = dyn_cast<MemberExpr>(Exp->getCallee())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000698 closureName = MExpr->getMemberDecl()->getNameAsCString();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000699 CPT = MExpr->getType()->getAsBlockPointerType();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000700 } else {
701 assert(1 && "RewriteBlockClass: Bad type");
702 }
703 assert(CPT && "RewriteBlockClass: Bad type");
704 const FunctionType *FT = CPT->getPointeeType()->getAsFunctionType();
705 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000706 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000707 // FTP will be null for closures that don't take arguments.
708
709 // Build a closure call - start with a paren expr to enforce precedence.
710 std::string BlockCall = "(";
711
712 // Synthesize the cast.
713 BlockCall += "(" + Exp->getType().getAsString() + "(*)";
Steve Naroff8af6a452008-10-02 17:12:56 +0000714 BlockCall += "(struct __block_impl *";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000715 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000716 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000717 E = FTP->arg_type_end(); I && (I != E); ++I)
718 BlockCall += ", " + (*I).getAsString();
719 }
720 BlockCall += "))"; // close the argument list and paren expression.
721
Steve Naroff83ba14e2008-10-03 15:04:50 +0000722 // Invoke the closure. We need to cast it since the declaration type is
723 // bogus (it's a function pointer type)
724 BlockCall += "((struct __block_impl *)";
725 std::string closureExprBufStr;
726 llvm::raw_string_ostream closureExprBuf(closureExprBufStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000727 Exp->getCallee()->printPretty(closureExprBuf, *Context, 0,
728 PrintingPolicy(LangOpts));
Steve Naroff83ba14e2008-10-03 15:04:50 +0000729 BlockCall += closureExprBuf.str();
730 BlockCall += ")->FuncPtr)";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000731
732 // Add the arguments.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000733 BlockCall += "((struct __block_impl *)";
Steve Naroffb65a4f12008-10-04 17:45:51 +0000734 BlockCall += closureExprBuf.str();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000735 for (CallExpr::arg_iterator I = Exp->arg_begin(),
736 E = Exp->arg_end(); I != E; ++I) {
737 std::string syncExprBufS;
738 llvm::raw_string_ostream Buf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +0000739 (*I)->printPretty(Buf, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000740 BlockCall += ", " + Buf.str();
741 }
742 return BlockCall;
743}
744
745void RewriteBlocks::RewriteBlockCall(CallExpr *Exp) {
746 std::string BlockCall = SynthesizeBlockCall(Exp);
747
748 const char *startBuf = SM->getCharacterData(Exp->getLocStart());
749 const char *endBuf = SM->getCharacterData(Exp->getLocEnd());
750
751 ReplaceText(Exp->getLocStart(), endBuf-startBuf,
752 BlockCall.c_str(), BlockCall.size());
753}
754
Steve Naroff5e52b172008-10-04 18:52:47 +0000755void RewriteBlocks::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
756 // FIXME: Add more elaborate code generation required by the ABI.
757 InsertText(BDRE->getLocStart(), "*", 1);
758}
759
Steve Naroffca743602008-10-15 18:38:58 +0000760void RewriteBlocks::RewriteCastExpr(CastExpr *CE) {
761 SourceLocation LocStart = CE->getLocStart();
762 SourceLocation LocEnd = CE->getLocEnd();
763
Steve Naroff8f6ce572008-11-03 11:20:24 +0000764 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
765 return;
766
Steve Naroffca743602008-10-15 18:38:58 +0000767 const char *startBuf = SM->getCharacterData(LocStart);
768 const char *endBuf = SM->getCharacterData(LocEnd);
769
770 // advance the location to startArgList.
771 const char *argPtr = startBuf;
772
773 while (*argPtr++ && (argPtr < endBuf)) {
774 switch (*argPtr) {
775 case '^':
776 // Replace the '^' with '*'.
777 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
778 ReplaceText(LocStart, 1, "*", 1);
779 break;
780 }
781 }
782 return;
783}
784
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000785void RewriteBlocks::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
786 SourceLocation DeclLoc = FD->getLocation();
Steve Naroffe0109a52008-10-10 15:33:34 +0000787 unsigned parenCount = 0;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000788
789 // We have 1 or more arguments that have closure pointers.
790 const char *startBuf = SM->getCharacterData(DeclLoc);
791 const char *startArgList = strchr(startBuf, '(');
792
793 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
794
795 parenCount++;
796 // advance the location to startArgList.
Steve Naroffe0109a52008-10-10 15:33:34 +0000797 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000798 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
799
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000800 const char *argPtr = startArgList;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000801
802 while (*argPtr++ && parenCount) {
803 switch (*argPtr) {
804 case '^':
Steve Naroffe0109a52008-10-10 15:33:34 +0000805 // Replace the '^' with '*'.
806 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
807 ReplaceText(DeclLoc, 1, "*", 1);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000808 break;
809 case '(':
810 parenCount++;
811 break;
812 case ')':
813 parenCount--;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000814 break;
815 }
816 }
817 return;
818}
819
Steve Naroffca743602008-10-15 18:38:58 +0000820bool RewriteBlocks::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000821 const FunctionProtoType *FTP;
Steve Naroffca743602008-10-15 18:38:58 +0000822 const PointerType *PT = QT->getAsPointerType();
823 if (PT) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000824 FTP = PT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000825 } else {
826 const BlockPointerType *BPT = QT->getAsBlockPointerType();
827 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
Douglas Gregor72564e72009-02-26 23:50:07 +0000828 FTP = BPT->getPointeeType()->getAsFunctionProtoType();
Steve Naroffca743602008-10-15 18:38:58 +0000829 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000830 if (FTP) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000831 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffeab5f632008-09-23 19:24:41 +0000832 E = FTP->arg_type_end(); I != E; ++I)
833 if (isBlockPointerType(*I))
834 return true;
835 }
836 return false;
837}
838
839void RewriteBlocks::GetExtentOfArgList(const char *Name,
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000840 const char *&LParen, const char *&RParen) {
841 const char *argPtr = strchr(Name, '(');
Steve Naroffeab5f632008-09-23 19:24:41 +0000842 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
843
844 LParen = argPtr; // output the start.
845 argPtr++; // skip past the left paren.
846 unsigned parenCount = 1;
847
848 while (*argPtr && parenCount) {
849 switch (*argPtr) {
850 case '(': parenCount++; break;
851 case ')': parenCount--; break;
852 default: break;
853 }
854 if (parenCount) argPtr++;
855 }
856 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
857 RParen = argPtr; // output the end
858}
859
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000860void RewriteBlocks::RewriteBlockPointerDecl(NamedDecl *ND) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000861 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
862 RewriteBlockPointerFunctionArgs(FD);
863 return;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000864 }
865 // Handle Variables and Typedefs.
866 SourceLocation DeclLoc = ND->getLocation();
867 QualType DeclT;
868 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
869 DeclT = VD->getType();
870 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
871 DeclT = TDD->getUnderlyingType();
Steve Naroff83ba14e2008-10-03 15:04:50 +0000872 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
873 DeclT = FD->getType();
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000874 else
875 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Steve Naroffeab5f632008-09-23 19:24:41 +0000876
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000877 const char *startBuf = SM->getCharacterData(DeclLoc);
878 const char *endBuf = startBuf;
879 // scan backward (from the decl location) for the end of the previous decl.
880 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
881 startBuf--;
Steve Naroffca743602008-10-15 18:38:58 +0000882
883 // *startBuf != '^' if we are dealing with a pointer to function that
884 // may take block argument types (which will be handled below).
885 if (*startBuf == '^') {
886 // Replace the '^' with '*', computing a negative offset.
887 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
888 ReplaceText(DeclLoc, 1, "*", 1);
889 }
890 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000891 // Replace the '^' with '*' for arguments.
892 DeclLoc = ND->getLocation();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000893 startBuf = SM->getCharacterData(DeclLoc);
Steve Naroff1f6c3ae2008-09-24 17:22:34 +0000894 const char *argListBegin, *argListEnd;
Steve Naroffca3bb4f2008-09-23 21:15:53 +0000895 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
896 while (argListBegin < argListEnd) {
897 if (*argListBegin == '^') {
898 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
899 ReplaceText(CaretLoc, 1, "*", 1);
900 }
901 argListBegin++;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000902 }
Steve Naroffeab5f632008-09-23 19:24:41 +0000903 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000904 return;
905}
906
Steve Naroffd3f77902008-10-05 00:06:12 +0000907void RewriteBlocks::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000908 // Add initializers for any closure decl refs.
Steve Naroff84a969f2008-10-08 17:31:13 +0000909 GetBlockDeclRefExprs(Exp->getBody());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000910 if (BlockDeclRefs.size()) {
911 // Unique all "by copy" declarations.
912 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
913 if (!BlockDeclRefs[i]->isByRef())
914 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
915 // Unique all "by ref" declarations.
916 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
917 if (BlockDeclRefs[i]->isByRef()) {
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000918 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
919 }
Steve Naroffacba0f22008-10-04 23:47:37 +0000920 // Find any imported blocks...they will need special attention.
921 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
922 if (isBlockPointerType(BlockDeclRefs[i]->getType())) {
923 GetBlockCallExprs(Blocks[i]);
924 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
925 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000926 }
Steve Naroffd3f77902008-10-05 00:06:12 +0000927}
928
929std::string RewriteBlocks::SynthesizeBlockInitExpr(BlockExpr *Exp, VarDecl *VD) {
930 Blocks.push_back(Exp);
931
932 CollectBlockDeclRefInfo(Exp);
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000933 std::string FuncName;
934
935 if (CurFunctionDef)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000936 FuncName = std::string(CurFunctionDef->getNameAsString());
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000937 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +0000938 FuncName = CurMethodDef->getSelector().getAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000939 // Convert colons to underscores.
940 std::string::size_type loc = 0;
941 while ((loc = FuncName.find(":", loc)) != std::string::npos)
942 FuncName.replace(loc, 1, "_");
Steve Naroff39622b92008-10-03 15:38:09 +0000943 } else if (VD)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000944 FuncName = std::string(VD->getNameAsString());
Steve Naroff39622b92008-10-03 15:38:09 +0000945
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000946 std::string BlockNumber = utostr(Blocks.size()-1);
947
Steve Naroff83ba14e2008-10-03 15:04:50 +0000948 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
Steve Naroffa0b75cf2008-10-02 23:30:43 +0000949 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000950
Steve Naroff83ba14e2008-10-03 15:04:50 +0000951 std::string FunkTypeStr;
952
953 // Get a pointer to the function type so we can cast appropriately.
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000954 Context->getPointerType(QualType(Exp->getFunctionType(),0))
955 .getAsStringInternal(FunkTypeStr, Context->PrintingPolicy);
Steve Naroff83ba14e2008-10-03 15:04:50 +0000956
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000957 // Rewrite the closure block with a compound literal. The first cast is
958 // to prevent warnings from the C compiler.
Steve Naroff83ba14e2008-10-03 15:04:50 +0000959 std::string Init = "(" + FunkTypeStr;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000960
Steve Naroff83ba14e2008-10-03 15:04:50 +0000961 Init += ")&" + Tag;
962
963 // Initialize the block function.
964 Init += "((void*)" + Func;
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000965
Steve Naroffacba0f22008-10-04 23:47:37 +0000966 if (ImportedBlockDecls.size()) {
967 std::string Buf = "__" + FuncName + "_block_copy_" + BlockNumber;
968 Init += ",(void*)" + Buf;
969 Buf = "__" + FuncName + "_block_dispose_" + BlockNumber;
970 Init += ",(void*)" + Buf;
971 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000972 // Add initializers for any closure decl refs.
973 if (BlockDeclRefs.size()) {
974 // Output all "by copy" declarations.
975 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
976 E = BlockByCopyDecls.end(); I != E; ++I) {
977 Init += ",";
978 if (isObjCType((*I)->getType())) {
979 Init += "[[";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000980 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000981 Init += " retain] autorelease]";
Steve Naroff4e13b762008-10-03 20:28:15 +0000982 } else if (isBlockPointerType((*I)->getType())) {
983 Init += "(void *)";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000984 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000985 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000986 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000987 }
988 }
989 // Output all "by ref" declarations.
990 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
991 E = BlockByRefDecls.end(); I != E; ++I) {
992 Init += ",&";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000993 Init += (*I)->getNameAsString();
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000994 }
995 }
Steve Naroff83ba14e2008-10-03 15:04:50 +0000996 Init += ")";
Steve Naroff1c9f81b2008-09-17 00:13:27 +0000997 BlockDeclRefs.clear();
998 BlockByRefDecls.clear();
999 BlockByCopyDecls.clear();
Steve Naroff4e13b762008-10-03 20:28:15 +00001000 ImportedBlockDecls.clear();
1001
Steve Naroff70f95502008-10-04 17:06:23 +00001002 return Init;
1003}
1004
1005//===----------------------------------------------------------------------===//
1006// Function Body / Expression rewriting
1007//===----------------------------------------------------------------------===//
1008
1009Stmt *RewriteBlocks::RewriteFunctionBody(Stmt *S) {
1010 // Start by rewriting all children.
1011 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1012 CI != E; ++CI)
1013 if (*CI) {
1014 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
Eli Friedman687abff2009-06-08 04:24:21 +00001015 RewriteFunctionBody(CBE->getBody());
Steve Naroff70f95502008-10-04 17:06:23 +00001016
1017 // We've just rewritten the block body in place.
1018 // Now we snarf the rewritten text and stash it away for later use.
1019 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1020 RewrittenBlockExprs[CBE] = S;
1021 std::string Init = SynthesizeBlockInitExpr(CBE);
1022 // Do the rewrite, using S.size() which contains the rewritten size.
1023 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
1024 } else {
Eli Friedman687abff2009-06-08 04:24:21 +00001025 RewriteFunctionBody(*CI);
Steve Naroff70f95502008-10-04 17:06:23 +00001026 }
1027 }
1028 // Handle specific things.
1029 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1030 if (CE->getCallee()->getType()->isBlockPointerType())
1031 RewriteBlockCall(CE);
1032 }
Steve Naroffca743602008-10-15 18:38:58 +00001033 if (CastExpr *CE = dyn_cast<CastExpr>(S)) {
1034 RewriteCastExpr(CE);
1035 }
Steve Naroff70f95502008-10-04 17:06:23 +00001036 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001037 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
1038 DI != DE; ++DI) {
1039
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001040 Decl *SD = *DI;
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001041 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
1042 if (isBlockPointerType(ND->getType()))
1043 RewriteBlockPointerDecl(ND);
Steve Naroffca743602008-10-15 18:38:58 +00001044 else if (ND->getType()->isFunctionPointerType())
1045 CheckFunctionPointerDecl(ND->getType(), ND);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001046 }
1047 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
1048 if (isBlockPointerType(TD->getUnderlyingType()))
1049 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001050 else if (TD->getUnderlyingType()->isFunctionPointerType())
1051 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Ted Kremenekfda4fed2008-10-06 18:47:09 +00001052 }
Steve Naroff70f95502008-10-04 17:06:23 +00001053 }
1054 }
Steve Naroff5e52b172008-10-04 18:52:47 +00001055 // Handle specific things.
1056 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
1057 if (BDRE->isByRef())
1058 RewriteBlockDeclRefExpr(BDRE);
1059 }
Steve Naroff70f95502008-10-04 17:06:23 +00001060 // Return this stmt unmodified.
1061 return S;
1062}
1063
Douglas Gregor72564e72009-02-26 23:50:07 +00001064void RewriteBlocks::RewriteFunctionProtoType(QualType funcType, NamedDecl *D) {
1065 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
1066 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroffca743602008-10-15 18:38:58 +00001067 E = fproto->arg_type_end(); I && (I != E); ++I)
1068 if (isBlockPointerType(*I)) {
1069 // All the args are checked/rewritten. Don't call twice!
1070 RewriteBlockPointerDecl(D);
1071 break;
1072 }
1073 }
1074}
1075
1076void RewriteBlocks::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
1077 const PointerType *PT = funcType->getAsPointerType();
1078 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +00001079 RewriteFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroffca743602008-10-15 18:38:58 +00001080}
1081
Steve Naroff70f95502008-10-04 17:06:23 +00001082/// HandleDeclInMainFile - This is called for each top-level decl defined in the
1083/// main file of the input.
1084void RewriteBlocks::HandleDeclInMainFile(Decl *D) {
1085 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001086 // Since function prototypes don't have ParmDecl's, we check the function
1087 // prototype. This enables us to rewrite function declarations and
1088 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00001089 RewriteFunctionProtoType(FD->getType(), FD);
Sebastian Redld3a413d2009-04-26 20:35:05 +00001090
1091 // FIXME: Handle CXXTryStmt
1092 if (CompoundStmt *Body = FD->getCompoundBody(*Context)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001093 CurFunctionDef = FD;
Ted Kremenekeaab2062009-03-12 18:33:24 +00001094 FD->setBody(cast_or_null<CompoundStmt>(RewriteFunctionBody(Body)));
Steve Naroff70f95502008-10-04 17:06:23 +00001095 // This synthesizes and inserts the block "impl" struct, invoke function,
1096 // and any copy/dispose helper functions.
1097 InsertBlockLiteralsWithinFunction(FD);
1098 CurFunctionDef = 0;
1099 }
1100 return;
1101 }
1102 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
1103 RewriteMethodDecl(MD);
Douglas Gregor72971342009-04-18 00:02:19 +00001104 if (Stmt *Body = MD->getBody(*Context)) {
Steve Naroff70f95502008-10-04 17:06:23 +00001105 CurMethodDef = MD;
1106 RewriteFunctionBody(Body);
1107 InsertBlockLiteralsWithinMethod(MD);
1108 CurMethodDef = 0;
1109 }
1110 }
1111 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1112 if (isBlockPointerType(VD->getType())) {
1113 RewriteBlockPointerDecl(VD);
1114 if (VD->getInit()) {
1115 if (BlockExpr *CBE = dyn_cast<BlockExpr>(VD->getInit())) {
Douglas Gregor72971342009-04-18 00:02:19 +00001116 RewriteFunctionBody(CBE->getBody(*Context));
Steve Naroff70f95502008-10-04 17:06:23 +00001117
1118 // We've just rewritten the block body in place.
1119 // Now we snarf the rewritten text and stash it away for later use.
1120 std::string S = Rewrite.getRewritenText(CBE->getSourceRange());
1121 RewrittenBlockExprs[CBE] = S;
1122 std::string Init = SynthesizeBlockInitExpr(CBE, VD);
1123 // Do the rewrite, using S.size() which contains the rewritten size.
1124 ReplaceText(CBE->getLocStart(), S.size(), Init.c_str(), Init.size());
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001125 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00001126 VD->getNameAsCString());
Steve Naroffca743602008-10-15 18:38:58 +00001127 } else if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1128 RewriteCastExpr(CE);
1129 }
1130 }
1131 } else if (VD->getType()->isFunctionPointerType()) {
1132 CheckFunctionPointerDecl(VD->getType(), VD);
1133 if (VD->getInit()) {
1134 if (CastExpr *CE = dyn_cast<CastExpr>(VD->getInit())) {
1135 RewriteCastExpr(CE);
Steve Naroff70f95502008-10-04 17:06:23 +00001136 }
1137 }
1138 }
1139 return;
1140 }
1141 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
1142 if (isBlockPointerType(TD->getUnderlyingType()))
1143 RewriteBlockPointerDecl(TD);
Steve Naroffca743602008-10-15 18:38:58 +00001144 else if (TD->getUnderlyingType()->isFunctionPointerType())
1145 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff70f95502008-10-04 17:06:23 +00001146 return;
1147 }
1148 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1149 if (RD->isDefinition()) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001150 for (RecordDecl::field_iterator i = RD->field_begin(*Context),
1151 e = RD->field_end(*Context); i != e; ++i) {
Steve Naroff70f95502008-10-04 17:06:23 +00001152 FieldDecl *FD = *i;
1153 if (isBlockPointerType(FD->getType()))
1154 RewriteBlockPointerDecl(FD);
1155 }
1156 }
1157 return;
1158 }
Steve Naroff1c9f81b2008-09-17 00:13:27 +00001159}