blob: abdb09b2790f9457b86c5b7b8c104ba86cda466e [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
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 code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
111 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
118
119 // Block expressions.
120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
123
124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
125
126 // Block related declarations.
127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
141
142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
147 bool DisableReplaceStmt;
148 class DisableReplaceStmtScope {
149 RewriteModernObjC &R;
150 bool SavedValue;
151
152 public:
153 DisableReplaceStmtScope(RewriteModernObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
161 void InitializeCommon(ASTContext &context);
162
163 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000164 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000165 // Top Level Driver code.
166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000172 } else {
173 // Keep track of all interface declarations seen.
174 ObjCInterfacesSeen.push_back(Class->getCanonicalDecl());
175 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 }
177 }
178
179 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180 if (!Proto->isThisDeclarationADefinition()) {
181 RewriteForwardProtocolDecl(D);
182 break;
183 }
184 }
185
186 HandleTopLevelSingleDecl(*I);
187 }
188 return true;
189 }
190 void HandleTopLevelSingleDecl(Decl *D);
191 void HandleDeclInMainFile(Decl *D);
192 RewriteModernObjC(std::string inFile, raw_ostream *OS,
193 DiagnosticsEngine &D, const LangOptions &LOpts,
194 bool silenceMacroWarn);
195
196 ~RewriteModernObjC() {}
197
198 virtual void HandleTranslationUnit(ASTContext &C);
199
200 void ReplaceStmt(Stmt *Old, Stmt *New) {
201 Stmt *ReplacingStmt = ReplacedNodes[Old];
202
203 if (ReplacingStmt)
204 return; // We can't rewrite the same node twice.
205
206 if (DisableReplaceStmt)
207 return;
208
209 // If replacement succeeded or warning disabled return with no warning.
210 if (!Rewrite.ReplaceStmt(Old, New)) {
211 ReplacedNodes[Old] = New;
212 return;
213 }
214 if (SilenceRewriteMacroWarning)
215 return;
216 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
217 << Old->getSourceRange();
218 }
219
220 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
221 if (DisableReplaceStmt)
222 return;
223
224 // Measure the old text.
225 int Size = Rewrite.getRangeSize(SrcRange);
226 if (Size == -1) {
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 return;
230 }
231 // Get the new text.
232 std::string SStr;
233 llvm::raw_string_ostream S(SStr);
234 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
235 const std::string &Str = S.str();
236
237 // If replacement succeeded or warning disabled return with no warning.
238 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
239 ReplacedNodes[Old] = New;
240 return;
241 }
242 if (SilenceRewriteMacroWarning)
243 return;
244 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
245 << Old->getSourceRange();
246 }
247
248 void InsertText(SourceLocation Loc, StringRef Str,
249 bool InsertAfter = true) {
250 // If insertion succeeded or warning disabled return with no warning.
251 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
252 SilenceRewriteMacroWarning)
253 return;
254
255 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
256 }
257
258 void ReplaceText(SourceLocation Start, unsigned OrigLength,
259 StringRef Str) {
260 // If removal succeeded or warning disabled return with no warning.
261 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
266 }
267
268 // Syntactic Rewriting.
269 void RewriteRecordBody(RecordDecl *RD);
270 void RewriteInclude();
271 void RewriteForwardClassDecl(DeclGroupRef D);
272 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
273 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
274 const std::string &typedefString);
275 void RewriteImplementations();
276 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
277 ObjCImplementationDecl *IMD,
278 ObjCCategoryImplDecl *CID);
279 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
280 void RewriteImplementationDecl(Decl *Dcl);
281 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
282 ObjCMethodDecl *MDecl, std::string &ResultStr);
283 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
284 const FunctionType *&FPRetType);
285 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
286 ValueDecl *VD, bool def=false);
287 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
288 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
289 void RewriteForwardProtocolDecl(DeclGroupRef D);
290 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
291 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
292 void RewriteProperty(ObjCPropertyDecl *prop);
293 void RewriteFunctionDecl(FunctionDecl *FD);
294 void RewriteBlockPointerType(std::string& Str, QualType Type);
295 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
296 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
297 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
298 void RewriteTypeOfDecl(VarDecl *VD);
299 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
300
301 // Expression Rewriting.
302 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
303 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
304 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
305 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
306 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
307 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
308 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
309 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
310 void RewriteTryReturnStmts(Stmt *S);
311 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
312 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
313 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
314 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
315 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
316 SourceLocation OrigEnd);
317 Stmt *RewriteBreakStmt(BreakStmt *S);
318 Stmt *RewriteContinueStmt(ContinueStmt *S);
319 void RewriteCastExpr(CStyleCastExpr *CE);
320
321 // Block rewriting.
322 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
323
324 // Block specific rewrite rules.
325 void RewriteBlockPointerDecl(NamedDecl *VD);
326 void RewriteByRefVar(VarDecl *VD);
327 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
328 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
329 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
330
331 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
332 std::string &Result);
333
334 virtual void Initialize(ASTContext &context);
335
336 // Misc. AST transformation routines. Somtimes they end up calling
337 // rewriting routines on the new ASTs.
338 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
339 Expr **args, unsigned nargs,
340 SourceLocation StartLoc=SourceLocation(),
341 SourceLocation EndLoc=SourceLocation());
342
343 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
344 SourceLocation StartLoc=SourceLocation(),
345 SourceLocation EndLoc=SourceLocation());
346
347 void SynthCountByEnumWithState(std::string &buf);
348 void SynthMsgSendFunctionDecl();
349 void SynthMsgSendSuperFunctionDecl();
350 void SynthMsgSendStretFunctionDecl();
351 void SynthMsgSendFpretFunctionDecl();
352 void SynthMsgSendSuperStretFunctionDecl();
353 void SynthGetClassFunctionDecl();
354 void SynthGetMetaClassFunctionDecl();
355 void SynthGetSuperClassFunctionDecl();
356 void SynthSelGetUidFunctionDecl();
357 void SynthSuperContructorFunctionDecl();
358
359 // Rewriting metadata
360 template<typename MethodIterator>
361 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
362 MethodIterator MethodEnd,
363 bool IsInstanceMethod,
364 StringRef prefix,
365 StringRef ClassName,
366 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000367 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
368 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000369 virtual void RewriteObjCProtocolListMetaData(
370 const ObjCList<ObjCProtocolDecl> &Prots,
371 StringRef prefix, StringRef ClassName, std::string &Result);
372 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
373 std::string &Result);
374 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
375 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
376 std::string &Result);
377
378 // Rewriting ivar
379 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
380 std::string &Result);
381 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
382
383
384 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
385 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
386 StringRef funcName, std::string Tag);
387 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
388 StringRef funcName, std::string Tag);
389 std::string SynthesizeBlockImpl(BlockExpr *CE,
390 std::string Tag, std::string Desc);
391 std::string SynthesizeBlockDescriptor(std::string DescTag,
392 std::string ImplTag,
393 int i, StringRef funcName,
394 unsigned hasCopy);
395 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
396 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
397 StringRef FunName);
398 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
399 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
400 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
401
402 // Misc. helper routines.
403 QualType getProtocolType();
404 void WarnAboutReturnGotoStmts(Stmt *S);
405 void HasReturnStmts(Stmt *S, bool &hasReturns);
406 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
407 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
408 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
409
410 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
411 void CollectBlockDeclRefInfo(BlockExpr *Exp);
412 void GetBlockDeclRefExprs(Stmt *S);
413 void GetInnerBlockDeclRefExprs(Stmt *S,
414 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
415 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
416
417 // We avoid calling Type::isBlockPointerType(), since it operates on the
418 // canonical type. We only care if the top-level type is a closure pointer.
419 bool isTopLevelBlockPointerType(QualType T) {
420 return isa<BlockPointerType>(T);
421 }
422
423 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
424 /// to a function pointer type and upon success, returns true; false
425 /// otherwise.
426 bool convertBlockPointerToFunctionPointer(QualType &T) {
427 if (isTopLevelBlockPointerType(T)) {
428 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
429 T = Context->getPointerType(BPT->getPointeeType());
430 return true;
431 }
432 return false;
433 }
434
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000435 bool convertObjCTypeToCStyleType(QualType &T);
436
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000437 bool needToScanForQualifiers(QualType T);
438 QualType getSuperStructType();
439 QualType getConstantStringStructType();
440 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
441 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
442
443 void convertToUnqualifiedObjCType(QualType &T) {
444 if (T->isObjCQualifiedIdType())
445 T = Context->getObjCIdType();
446 else if (T->isObjCQualifiedClassType())
447 T = Context->getObjCClassType();
448 else if (T->isObjCObjectPointerType() &&
449 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
450 if (const ObjCObjectPointerType * OBJPT =
451 T->getAsObjCInterfacePointerType()) {
452 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
453 T = QualType(IFaceT, 0);
454 T = Context->getPointerType(T);
455 }
456 }
457 }
458
459 // FIXME: This predicate seems like it would be useful to add to ASTContext.
460 bool isObjCType(QualType T) {
461 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
462 return false;
463
464 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
465
466 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
467 OCT == Context->getCanonicalType(Context->getObjCClassType()))
468 return true;
469
470 if (const PointerType *PT = OCT->getAs<PointerType>()) {
471 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
472 PT->getPointeeType()->isObjCQualifiedIdType())
473 return true;
474 }
475 return false;
476 }
477 bool PointerTypeTakesAnyBlockArguments(QualType QT);
478 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
479 void GetExtentOfArgList(const char *Name, const char *&LParen,
480 const char *&RParen);
481
482 void QuoteDoublequotes(std::string &From, std::string &To) {
483 for (unsigned i = 0; i < From.length(); i++) {
484 if (From[i] == '"')
485 To += "\\\"";
486 else
487 To += From[i];
488 }
489 }
490
491 QualType getSimpleFunctionType(QualType result,
492 const QualType *args,
493 unsigned numArgs,
494 bool variadic = false) {
495 if (result == Context->getObjCInstanceType())
496 result = Context->getObjCIdType();
497 FunctionProtoType::ExtProtoInfo fpi;
498 fpi.Variadic = variadic;
499 return Context->getFunctionType(result, args, numArgs, fpi);
500 }
501
502 // Helper function: create a CStyleCastExpr with trivial type source info.
503 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
504 CastKind Kind, Expr *E) {
505 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
506 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
507 SourceLocation(), SourceLocation());
508 }
509 };
510
511}
512
513void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
514 NamedDecl *D) {
515 if (const FunctionProtoType *fproto
516 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
517 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
518 E = fproto->arg_type_end(); I && (I != E); ++I)
519 if (isTopLevelBlockPointerType(*I)) {
520 // All the args are checked/rewritten. Don't call twice!
521 RewriteBlockPointerDecl(D);
522 break;
523 }
524 }
525}
526
527void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
528 const PointerType *PT = funcType->getAs<PointerType>();
529 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
530 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
531}
532
533static bool IsHeaderFile(const std::string &Filename) {
534 std::string::size_type DotPos = Filename.rfind('.');
535
536 if (DotPos == std::string::npos) {
537 // no file extension
538 return false;
539 }
540
541 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
542 // C header: .h
543 // C++ header: .hh or .H;
544 return Ext == "h" || Ext == "hh" || Ext == "H";
545}
546
547RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
548 DiagnosticsEngine &D, const LangOptions &LOpts,
549 bool silenceMacroWarn)
550 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
551 SilenceRewriteMacroWarning(silenceMacroWarn) {
552 IsHeader = IsHeaderFile(inFile);
553 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
554 "rewriting sub-expression within a macro (may not be correct)");
555 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
556 DiagnosticsEngine::Warning,
557 "rewriter doesn't support user-specified control flow semantics "
558 "for @try/@finally (code may not execute properly)");
559}
560
561ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
562 raw_ostream* OS,
563 DiagnosticsEngine &Diags,
564 const LangOptions &LOpts,
565 bool SilenceRewriteMacroWarning) {
566 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
567}
568
569void RewriteModernObjC::InitializeCommon(ASTContext &context) {
570 Context = &context;
571 SM = &Context->getSourceManager();
572 TUDecl = Context->getTranslationUnitDecl();
573 MsgSendFunctionDecl = 0;
574 MsgSendSuperFunctionDecl = 0;
575 MsgSendStretFunctionDecl = 0;
576 MsgSendSuperStretFunctionDecl = 0;
577 MsgSendFpretFunctionDecl = 0;
578 GetClassFunctionDecl = 0;
579 GetMetaClassFunctionDecl = 0;
580 GetSuperClassFunctionDecl = 0;
581 SelGetUidFunctionDecl = 0;
582 CFStringFunctionDecl = 0;
583 ConstantStringClassReference = 0;
584 NSStringRecord = 0;
585 CurMethodDef = 0;
586 CurFunctionDef = 0;
587 CurFunctionDeclToDeclareForBlock = 0;
588 GlobalVarDecl = 0;
589 SuperStructDecl = 0;
590 ProtocolTypeDecl = 0;
591 ConstantStringDecl = 0;
592 BcLabelCount = 0;
593 SuperContructorFunctionDecl = 0;
594 NumObjCStringLiterals = 0;
595 PropParentMap = 0;
596 CurrentBody = 0;
597 DisableReplaceStmt = false;
598 objc_impl_method = false;
599
600 // Get the ID and start/end of the main file.
601 MainFileID = SM->getMainFileID();
602 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
603 MainFileStart = MainBuf->getBufferStart();
604 MainFileEnd = MainBuf->getBufferEnd();
605
606 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
607}
608
609//===----------------------------------------------------------------------===//
610// Top Level Driver Code
611//===----------------------------------------------------------------------===//
612
613void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
614 if (Diags.hasErrorOccurred())
615 return;
616
617 // Two cases: either the decl could be in the main file, or it could be in a
618 // #included file. If the former, rewrite it now. If the later, check to see
619 // if we rewrote the #include/#import.
620 SourceLocation Loc = D->getLocation();
621 Loc = SM->getExpansionLoc(Loc);
622
623 // If this is for a builtin, ignore it.
624 if (Loc.isInvalid()) return;
625
626 // Look for built-in declarations that we need to refer during the rewrite.
627 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
628 RewriteFunctionDecl(FD);
629 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
630 // declared in <Foundation/NSString.h>
631 if (FVD->getName() == "_NSConstantStringClassReference") {
632 ConstantStringClassReference = FVD;
633 return;
634 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000635 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
636 RewriteCategoryDecl(CD);
637 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
638 if (PD->isThisDeclarationADefinition())
639 RewriteProtocolDecl(PD);
640 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
641 // Recurse into linkage specifications
642 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
643 DIEnd = LSD->decls_end();
644 DI != DIEnd; ) {
645 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
646 if (!IFace->isThisDeclarationADefinition()) {
647 SmallVector<Decl *, 8> DG;
648 SourceLocation StartLoc = IFace->getLocStart();
649 do {
650 if (isa<ObjCInterfaceDecl>(*DI) &&
651 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
652 StartLoc == (*DI)->getLocStart())
653 DG.push_back(*DI);
654 else
655 break;
656
657 ++DI;
658 } while (DI != DIEnd);
659 RewriteForwardClassDecl(DG);
660 continue;
661 }
662 }
663
664 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
665 if (!Proto->isThisDeclarationADefinition()) {
666 SmallVector<Decl *, 8> DG;
667 SourceLocation StartLoc = Proto->getLocStart();
668 do {
669 if (isa<ObjCProtocolDecl>(*DI) &&
670 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
671 StartLoc == (*DI)->getLocStart())
672 DG.push_back(*DI);
673 else
674 break;
675
676 ++DI;
677 } while (DI != DIEnd);
678 RewriteForwardProtocolDecl(DG);
679 continue;
680 }
681 }
682
683 HandleTopLevelSingleDecl(*DI);
684 ++DI;
685 }
686 }
687 // If we have a decl in the main file, see if we should rewrite it.
688 if (SM->isFromMainFile(Loc))
689 return HandleDeclInMainFile(D);
690}
691
692//===----------------------------------------------------------------------===//
693// Syntactic (non-AST) Rewriting Code
694//===----------------------------------------------------------------------===//
695
696void RewriteModernObjC::RewriteInclude() {
697 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
698 StringRef MainBuf = SM->getBufferData(MainFileID);
699 const char *MainBufStart = MainBuf.begin();
700 const char *MainBufEnd = MainBuf.end();
701 size_t ImportLen = strlen("import");
702
703 // Loop over the whole file, looking for includes.
704 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
705 if (*BufPtr == '#') {
706 if (++BufPtr == MainBufEnd)
707 return;
708 while (*BufPtr == ' ' || *BufPtr == '\t')
709 if (++BufPtr == MainBufEnd)
710 return;
711 if (!strncmp(BufPtr, "import", ImportLen)) {
712 // replace import with include
713 SourceLocation ImportLoc =
714 LocStart.getLocWithOffset(BufPtr-MainBufStart);
715 ReplaceText(ImportLoc, ImportLen, "include");
716 BufPtr += ImportLen;
717 }
718 }
719 }
720}
721
722static std::string getIvarAccessString(ObjCIvarDecl *OID) {
723 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
724 std::string S;
725 S = "((struct ";
726 S += ClassDecl->getIdentifier()->getName();
727 S += "_IMPL *)self)->";
728 S += OID->getName();
729 return S;
730}
731
732void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
733 ObjCImplementationDecl *IMD,
734 ObjCCategoryImplDecl *CID) {
735 static bool objcGetPropertyDefined = false;
736 static bool objcSetPropertyDefined = false;
737 SourceLocation startLoc = PID->getLocStart();
738 InsertText(startLoc, "// ");
739 const char *startBuf = SM->getCharacterData(startLoc);
740 assert((*startBuf == '@') && "bogus @synthesize location");
741 const char *semiBuf = strchr(startBuf, ';');
742 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
743 SourceLocation onePastSemiLoc =
744 startLoc.getLocWithOffset(semiBuf-startBuf+1);
745
746 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
747 return; // FIXME: is this correct?
748
749 // Generate the 'getter' function.
750 ObjCPropertyDecl *PD = PID->getPropertyDecl();
751 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
752
753 if (!OID)
754 return;
755 unsigned Attributes = PD->getPropertyAttributes();
756 if (!PD->getGetterMethodDecl()->isDefined()) {
757 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
758 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
759 ObjCPropertyDecl::OBJC_PR_copy));
760 std::string Getr;
761 if (GenGetProperty && !objcGetPropertyDefined) {
762 objcGetPropertyDefined = true;
763 // FIXME. Is this attribute correct in all cases?
764 Getr = "\nextern \"C\" __declspec(dllimport) "
765 "id objc_getProperty(id, SEL, long, bool);\n";
766 }
767 RewriteObjCMethodDecl(OID->getContainingInterface(),
768 PD->getGetterMethodDecl(), Getr);
769 Getr += "{ ";
770 // Synthesize an explicit cast to gain access to the ivar.
771 // See objc-act.c:objc_synthesize_new_getter() for details.
772 if (GenGetProperty) {
773 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
774 Getr += "typedef ";
775 const FunctionType *FPRetType = 0;
776 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
777 FPRetType);
778 Getr += " _TYPE";
779 if (FPRetType) {
780 Getr += ")"; // close the precedence "scope" for "*".
781
782 // Now, emit the argument types (if any).
783 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
784 Getr += "(";
785 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
786 if (i) Getr += ", ";
787 std::string ParamStr = FT->getArgType(i).getAsString(
788 Context->getPrintingPolicy());
789 Getr += ParamStr;
790 }
791 if (FT->isVariadic()) {
792 if (FT->getNumArgs()) Getr += ", ";
793 Getr += "...";
794 }
795 Getr += ")";
796 } else
797 Getr += "()";
798 }
799 Getr += ";\n";
800 Getr += "return (_TYPE)";
801 Getr += "objc_getProperty(self, _cmd, ";
802 RewriteIvarOffsetComputation(OID, Getr);
803 Getr += ", 1)";
804 }
805 else
806 Getr += "return " + getIvarAccessString(OID);
807 Getr += "; }";
808 InsertText(onePastSemiLoc, Getr);
809 }
810
811 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
812 return;
813
814 // Generate the 'setter' function.
815 std::string Setr;
816 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
817 ObjCPropertyDecl::OBJC_PR_copy);
818 if (GenSetProperty && !objcSetPropertyDefined) {
819 objcSetPropertyDefined = true;
820 // FIXME. Is this attribute correct in all cases?
821 Setr = "\nextern \"C\" __declspec(dllimport) "
822 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
823 }
824
825 RewriteObjCMethodDecl(OID->getContainingInterface(),
826 PD->getSetterMethodDecl(), Setr);
827 Setr += "{ ";
828 // Synthesize an explicit cast to initialize the ivar.
829 // See objc-act.c:objc_synthesize_new_setter() for details.
830 if (GenSetProperty) {
831 Setr += "objc_setProperty (self, _cmd, ";
832 RewriteIvarOffsetComputation(OID, Setr);
833 Setr += ", (id)";
834 Setr += PD->getName();
835 Setr += ", ";
836 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
837 Setr += "0, ";
838 else
839 Setr += "1, ";
840 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
841 Setr += "1)";
842 else
843 Setr += "0)";
844 }
845 else {
846 Setr += getIvarAccessString(OID) + " = ";
847 Setr += PD->getName();
848 }
849 Setr += "; }";
850 InsertText(onePastSemiLoc, Setr);
851}
852
853static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
854 std::string &typedefString) {
855 typedefString += "#ifndef _REWRITER_typedef_";
856 typedefString += ForwardDecl->getNameAsString();
857 typedefString += "\n";
858 typedefString += "#define _REWRITER_typedef_";
859 typedefString += ForwardDecl->getNameAsString();
860 typedefString += "\n";
861 typedefString += "typedef struct objc_object ";
862 typedefString += ForwardDecl->getNameAsString();
863 typedefString += ";\n#endif\n";
864}
865
866void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
867 const std::string &typedefString) {
868 SourceLocation startLoc = ClassDecl->getLocStart();
869 const char *startBuf = SM->getCharacterData(startLoc);
870 const char *semiPtr = strchr(startBuf, ';');
871 // Replace the @class with typedefs corresponding to the classes.
872 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
873}
874
875void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
876 std::string typedefString;
877 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
878 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
879 if (I == D.begin()) {
880 // Translate to typedef's that forward reference structs with the same name
881 // as the class. As a convenience, we include the original declaration
882 // as a comment.
883 typedefString += "// @class ";
884 typedefString += ForwardDecl->getNameAsString();
885 typedefString += ";\n";
886 }
887 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
888 }
889 DeclGroupRef::iterator I = D.begin();
890 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
891}
892
893void RewriteModernObjC::RewriteForwardClassDecl(
894 const llvm::SmallVector<Decl*, 8> &D) {
895 std::string typedefString;
896 for (unsigned i = 0; i < D.size(); i++) {
897 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
898 if (i == 0) {
899 typedefString += "// @class ";
900 typedefString += ForwardDecl->getNameAsString();
901 typedefString += ";\n";
902 }
903 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
904 }
905 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
906}
907
908void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
909 // When method is a synthesized one, such as a getter/setter there is
910 // nothing to rewrite.
911 if (Method->isImplicit())
912 return;
913 SourceLocation LocStart = Method->getLocStart();
914 SourceLocation LocEnd = Method->getLocEnd();
915
916 if (SM->getExpansionLineNumber(LocEnd) >
917 SM->getExpansionLineNumber(LocStart)) {
918 InsertText(LocStart, "#if 0\n");
919 ReplaceText(LocEnd, 1, ";\n#endif\n");
920 } else {
921 InsertText(LocStart, "// ");
922 }
923}
924
925void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
926 SourceLocation Loc = prop->getAtLoc();
927
928 ReplaceText(Loc, 0, "// ");
929 // FIXME: handle properties that are declared across multiple lines.
930}
931
932void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
933 SourceLocation LocStart = CatDecl->getLocStart();
934
935 // FIXME: handle category headers that are declared across multiple lines.
936 ReplaceText(LocStart, 0, "// ");
937
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000938 for (ObjCCategoryDecl::ivar_iterator
939 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
940 ObjCIvarDecl *Ivar = (*I);
941 SourceLocation LocStart = Ivar->getLocStart();
942 ReplaceText(LocStart, 0, "// ");
943 }
944
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000945 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
946 E = CatDecl->prop_end(); I != E; ++I)
947 RewriteProperty(*I);
948
949 for (ObjCCategoryDecl::instmeth_iterator
950 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
951 I != E; ++I)
952 RewriteMethodDeclaration(*I);
953 for (ObjCCategoryDecl::classmeth_iterator
954 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
955 I != E; ++I)
956 RewriteMethodDeclaration(*I);
957
958 // Lastly, comment out the @end.
959 ReplaceText(CatDecl->getAtEndRange().getBegin(),
960 strlen("@end"), "/* @end */");
961}
962
963void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
964 SourceLocation LocStart = PDecl->getLocStart();
965 assert(PDecl->isThisDeclarationADefinition());
966
967 // FIXME: handle protocol headers that are declared across multiple lines.
968 ReplaceText(LocStart, 0, "// ");
969
970 for (ObjCProtocolDecl::instmeth_iterator
971 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
972 I != E; ++I)
973 RewriteMethodDeclaration(*I);
974 for (ObjCProtocolDecl::classmeth_iterator
975 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
976 I != E; ++I)
977 RewriteMethodDeclaration(*I);
978
979 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
980 E = PDecl->prop_end(); I != E; ++I)
981 RewriteProperty(*I);
982
983 // Lastly, comment out the @end.
984 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
985 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
986
987 // Must comment out @optional/@required
988 const char *startBuf = SM->getCharacterData(LocStart);
989 const char *endBuf = SM->getCharacterData(LocEnd);
990 for (const char *p = startBuf; p < endBuf; p++) {
991 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
992 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
993 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
994
995 }
996 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
997 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
998 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
999
1000 }
1001 }
1002}
1003
1004void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1005 SourceLocation LocStart = (*D.begin())->getLocStart();
1006 if (LocStart.isInvalid())
1007 llvm_unreachable("Invalid SourceLocation");
1008 // FIXME: handle forward protocol that are declared across multiple lines.
1009 ReplaceText(LocStart, 0, "// ");
1010}
1011
1012void
1013RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1014 SourceLocation LocStart = DG[0]->getLocStart();
1015 if (LocStart.isInvalid())
1016 llvm_unreachable("Invalid SourceLocation");
1017 // FIXME: handle forward protocol that are declared across multiple lines.
1018 ReplaceText(LocStart, 0, "// ");
1019}
1020
1021void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1022 const FunctionType *&FPRetType) {
1023 if (T->isObjCQualifiedIdType())
1024 ResultStr += "id";
1025 else if (T->isFunctionPointerType() ||
1026 T->isBlockPointerType()) {
1027 // needs special handling, since pointer-to-functions have special
1028 // syntax (where a decaration models use).
1029 QualType retType = T;
1030 QualType PointeeTy;
1031 if (const PointerType* PT = retType->getAs<PointerType>())
1032 PointeeTy = PT->getPointeeType();
1033 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1034 PointeeTy = BPT->getPointeeType();
1035 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1036 ResultStr += FPRetType->getResultType().getAsString(
1037 Context->getPrintingPolicy());
1038 ResultStr += "(*";
1039 }
1040 } else
1041 ResultStr += T.getAsString(Context->getPrintingPolicy());
1042}
1043
1044void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1045 ObjCMethodDecl *OMD,
1046 std::string &ResultStr) {
1047 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1048 const FunctionType *FPRetType = 0;
1049 ResultStr += "\nstatic ";
1050 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1051 ResultStr += " ";
1052
1053 // Unique method name
1054 std::string NameStr;
1055
1056 if (OMD->isInstanceMethod())
1057 NameStr += "_I_";
1058 else
1059 NameStr += "_C_";
1060
1061 NameStr += IDecl->getNameAsString();
1062 NameStr += "_";
1063
1064 if (ObjCCategoryImplDecl *CID =
1065 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1066 NameStr += CID->getNameAsString();
1067 NameStr += "_";
1068 }
1069 // Append selector names, replacing ':' with '_'
1070 {
1071 std::string selString = OMD->getSelector().getAsString();
1072 int len = selString.size();
1073 for (int i = 0; i < len; i++)
1074 if (selString[i] == ':')
1075 selString[i] = '_';
1076 NameStr += selString;
1077 }
1078 // Remember this name for metadata emission
1079 MethodInternalNames[OMD] = NameStr;
1080 ResultStr += NameStr;
1081
1082 // Rewrite arguments
1083 ResultStr += "(";
1084
1085 // invisible arguments
1086 if (OMD->isInstanceMethod()) {
1087 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1088 selfTy = Context->getPointerType(selfTy);
1089 if (!LangOpts.MicrosoftExt) {
1090 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1091 ResultStr += "struct ";
1092 }
1093 // When rewriting for Microsoft, explicitly omit the structure name.
1094 ResultStr += IDecl->getNameAsString();
1095 ResultStr += " *";
1096 }
1097 else
1098 ResultStr += Context->getObjCClassType().getAsString(
1099 Context->getPrintingPolicy());
1100
1101 ResultStr += " self, ";
1102 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1103 ResultStr += " _cmd";
1104
1105 // Method arguments.
1106 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1107 E = OMD->param_end(); PI != E; ++PI) {
1108 ParmVarDecl *PDecl = *PI;
1109 ResultStr += ", ";
1110 if (PDecl->getType()->isObjCQualifiedIdType()) {
1111 ResultStr += "id ";
1112 ResultStr += PDecl->getNameAsString();
1113 } else {
1114 std::string Name = PDecl->getNameAsString();
1115 QualType QT = PDecl->getType();
1116 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1117 if (convertBlockPointerToFunctionPointer(QT))
1118 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1119 else
1120 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1121 ResultStr += Name;
1122 }
1123 }
1124 if (OMD->isVariadic())
1125 ResultStr += ", ...";
1126 ResultStr += ") ";
1127
1128 if (FPRetType) {
1129 ResultStr += ")"; // close the precedence "scope" for "*".
1130
1131 // Now, emit the argument types (if any).
1132 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1133 ResultStr += "(";
1134 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1135 if (i) ResultStr += ", ";
1136 std::string ParamStr = FT->getArgType(i).getAsString(
1137 Context->getPrintingPolicy());
1138 ResultStr += ParamStr;
1139 }
1140 if (FT->isVariadic()) {
1141 if (FT->getNumArgs()) ResultStr += ", ";
1142 ResultStr += "...";
1143 }
1144 ResultStr += ")";
1145 } else {
1146 ResultStr += "()";
1147 }
1148 }
1149}
1150void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1151 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1152 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1153
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001154 if (IMD) {
1155 InsertText(IMD->getLocStart(), "// ");
1156 for (ObjCImplementationDecl::ivar_iterator
1157 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1158 ObjCIvarDecl *Ivar = (*I);
1159 SourceLocation LocStart = Ivar->getLocStart();
1160 ReplaceText(LocStart, 0, "// ");
1161 }
1162 }
1163 else
1164 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001165
1166 for (ObjCCategoryImplDecl::instmeth_iterator
1167 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1168 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1169 I != E; ++I) {
1170 std::string ResultStr;
1171 ObjCMethodDecl *OMD = *I;
1172 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1173 SourceLocation LocStart = OMD->getLocStart();
1174 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1175
1176 const char *startBuf = SM->getCharacterData(LocStart);
1177 const char *endBuf = SM->getCharacterData(LocEnd);
1178 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1179 }
1180
1181 for (ObjCCategoryImplDecl::classmeth_iterator
1182 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1183 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1184 I != E; ++I) {
1185 std::string ResultStr;
1186 ObjCMethodDecl *OMD = *I;
1187 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1188 SourceLocation LocStart = OMD->getLocStart();
1189 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1190
1191 const char *startBuf = SM->getCharacterData(LocStart);
1192 const char *endBuf = SM->getCharacterData(LocEnd);
1193 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1194 }
1195 for (ObjCCategoryImplDecl::propimpl_iterator
1196 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1197 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1198 I != E; ++I) {
1199 RewritePropertyImplDecl(*I, IMD, CID);
1200 }
1201
1202 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1203}
1204
1205void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001206 // Do not synthesize more than once.
1207 if (ObjCSynthesizedStructs.count(ClassDecl))
1208 return;
1209 // Make sure super class's are written before current class is written.
1210 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1211 while (SuperClass) {
1212 RewriteInterfaceDecl(SuperClass);
1213 SuperClass = SuperClass->getSuperClass();
1214 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001215 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001216 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001217 // we haven't seen a forward decl - generate a typedef.
1218 ResultStr = "#ifndef _REWRITER_typedef_";
1219 ResultStr += ClassDecl->getNameAsString();
1220 ResultStr += "\n";
1221 ResultStr += "#define _REWRITER_typedef_";
1222 ResultStr += ClassDecl->getNameAsString();
1223 ResultStr += "\n";
1224 ResultStr += "typedef struct objc_object ";
1225 ResultStr += ClassDecl->getNameAsString();
1226 ResultStr += ";\n#endif\n";
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001227 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001228 // Mark this typedef as having been written into its c++ equivalent.
1229 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001230
1231 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001232 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001233 RewriteProperty(*I);
1234 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001235 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001236 I != E; ++I)
1237 RewriteMethodDeclaration(*I);
1238 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001239 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001240 I != E; ++I)
1241 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001242
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001243 // Lastly, comment out the @end.
1244 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1245 "/* @end */");
1246 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001247}
1248
1249Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1250 SourceRange OldRange = PseudoOp->getSourceRange();
1251
1252 // We just magically know some things about the structure of this
1253 // expression.
1254 ObjCMessageExpr *OldMsg =
1255 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1256 PseudoOp->getNumSemanticExprs() - 1));
1257
1258 // Because the rewriter doesn't allow us to rewrite rewritten code,
1259 // we need to suppress rewriting the sub-statements.
1260 Expr *Base, *RHS;
1261 {
1262 DisableReplaceStmtScope S(*this);
1263
1264 // Rebuild the base expression if we have one.
1265 Base = 0;
1266 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1267 Base = OldMsg->getInstanceReceiver();
1268 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1269 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1270 }
1271
1272 // Rebuild the RHS.
1273 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1274 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1275 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1276 }
1277
1278 // TODO: avoid this copy.
1279 SmallVector<SourceLocation, 1> SelLocs;
1280 OldMsg->getSelectorLocs(SelLocs);
1281
1282 ObjCMessageExpr *NewMsg = 0;
1283 switch (OldMsg->getReceiverKind()) {
1284 case ObjCMessageExpr::Class:
1285 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1286 OldMsg->getValueKind(),
1287 OldMsg->getLeftLoc(),
1288 OldMsg->getClassReceiverTypeInfo(),
1289 OldMsg->getSelector(),
1290 SelLocs,
1291 OldMsg->getMethodDecl(),
1292 RHS,
1293 OldMsg->getRightLoc(),
1294 OldMsg->isImplicit());
1295 break;
1296
1297 case ObjCMessageExpr::Instance:
1298 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1299 OldMsg->getValueKind(),
1300 OldMsg->getLeftLoc(),
1301 Base,
1302 OldMsg->getSelector(),
1303 SelLocs,
1304 OldMsg->getMethodDecl(),
1305 RHS,
1306 OldMsg->getRightLoc(),
1307 OldMsg->isImplicit());
1308 break;
1309
1310 case ObjCMessageExpr::SuperClass:
1311 case ObjCMessageExpr::SuperInstance:
1312 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1313 OldMsg->getValueKind(),
1314 OldMsg->getLeftLoc(),
1315 OldMsg->getSuperLoc(),
1316 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1317 OldMsg->getSuperType(),
1318 OldMsg->getSelector(),
1319 SelLocs,
1320 OldMsg->getMethodDecl(),
1321 RHS,
1322 OldMsg->getRightLoc(),
1323 OldMsg->isImplicit());
1324 break;
1325 }
1326
1327 Stmt *Replacement = SynthMessageExpr(NewMsg);
1328 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1329 return Replacement;
1330}
1331
1332Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1333 SourceRange OldRange = PseudoOp->getSourceRange();
1334
1335 // We just magically know some things about the structure of this
1336 // expression.
1337 ObjCMessageExpr *OldMsg =
1338 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1339
1340 // Because the rewriter doesn't allow us to rewrite rewritten code,
1341 // we need to suppress rewriting the sub-statements.
1342 Expr *Base = 0;
1343 {
1344 DisableReplaceStmtScope S(*this);
1345
1346 // Rebuild the base expression if we have one.
1347 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1348 Base = OldMsg->getInstanceReceiver();
1349 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1350 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1351 }
1352 }
1353
1354 // Intentionally empty.
1355 SmallVector<SourceLocation, 1> SelLocs;
1356 SmallVector<Expr*, 1> Args;
1357
1358 ObjCMessageExpr *NewMsg = 0;
1359 switch (OldMsg->getReceiverKind()) {
1360 case ObjCMessageExpr::Class:
1361 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1362 OldMsg->getValueKind(),
1363 OldMsg->getLeftLoc(),
1364 OldMsg->getClassReceiverTypeInfo(),
1365 OldMsg->getSelector(),
1366 SelLocs,
1367 OldMsg->getMethodDecl(),
1368 Args,
1369 OldMsg->getRightLoc(),
1370 OldMsg->isImplicit());
1371 break;
1372
1373 case ObjCMessageExpr::Instance:
1374 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1375 OldMsg->getValueKind(),
1376 OldMsg->getLeftLoc(),
1377 Base,
1378 OldMsg->getSelector(),
1379 SelLocs,
1380 OldMsg->getMethodDecl(),
1381 Args,
1382 OldMsg->getRightLoc(),
1383 OldMsg->isImplicit());
1384 break;
1385
1386 case ObjCMessageExpr::SuperClass:
1387 case ObjCMessageExpr::SuperInstance:
1388 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1389 OldMsg->getValueKind(),
1390 OldMsg->getLeftLoc(),
1391 OldMsg->getSuperLoc(),
1392 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1393 OldMsg->getSuperType(),
1394 OldMsg->getSelector(),
1395 SelLocs,
1396 OldMsg->getMethodDecl(),
1397 Args,
1398 OldMsg->getRightLoc(),
1399 OldMsg->isImplicit());
1400 break;
1401 }
1402
1403 Stmt *Replacement = SynthMessageExpr(NewMsg);
1404 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1405 return Replacement;
1406}
1407
1408/// SynthCountByEnumWithState - To print:
1409/// ((unsigned int (*)
1410/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1411/// (void *)objc_msgSend)((id)l_collection,
1412/// sel_registerName(
1413/// "countByEnumeratingWithState:objects:count:"),
1414/// &enumState,
1415/// (id *)__rw_items, (unsigned int)16)
1416///
1417void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1418 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1419 "id *, unsigned int))(void *)objc_msgSend)";
1420 buf += "\n\t\t";
1421 buf += "((id)l_collection,\n\t\t";
1422 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1423 buf += "\n\t\t";
1424 buf += "&enumState, "
1425 "(id *)__rw_items, (unsigned int)16)";
1426}
1427
1428/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1429/// statement to exit to its outer synthesized loop.
1430///
1431Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1432 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1433 return S;
1434 // replace break with goto __break_label
1435 std::string buf;
1436
1437 SourceLocation startLoc = S->getLocStart();
1438 buf = "goto __break_label_";
1439 buf += utostr(ObjCBcLabelNo.back());
1440 ReplaceText(startLoc, strlen("break"), buf);
1441
1442 return 0;
1443}
1444
1445/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1446/// statement to continue with its inner synthesized loop.
1447///
1448Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1449 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1450 return S;
1451 // replace continue with goto __continue_label
1452 std::string buf;
1453
1454 SourceLocation startLoc = S->getLocStart();
1455 buf = "goto __continue_label_";
1456 buf += utostr(ObjCBcLabelNo.back());
1457 ReplaceText(startLoc, strlen("continue"), buf);
1458
1459 return 0;
1460}
1461
1462/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1463/// It rewrites:
1464/// for ( type elem in collection) { stmts; }
1465
1466/// Into:
1467/// {
1468/// type elem;
1469/// struct __objcFastEnumerationState enumState = { 0 };
1470/// id __rw_items[16];
1471/// id l_collection = (id)collection;
1472/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1473/// objects:__rw_items count:16];
1474/// if (limit) {
1475/// unsigned long startMutations = *enumState.mutationsPtr;
1476/// do {
1477/// unsigned long counter = 0;
1478/// do {
1479/// if (startMutations != *enumState.mutationsPtr)
1480/// objc_enumerationMutation(l_collection);
1481/// elem = (type)enumState.itemsPtr[counter++];
1482/// stmts;
1483/// __continue_label: ;
1484/// } while (counter < limit);
1485/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1486/// objects:__rw_items count:16]);
1487/// elem = nil;
1488/// __break_label: ;
1489/// }
1490/// else
1491/// elem = nil;
1492/// }
1493///
1494Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1495 SourceLocation OrigEnd) {
1496 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1497 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1498 "ObjCForCollectionStmt Statement stack mismatch");
1499 assert(!ObjCBcLabelNo.empty() &&
1500 "ObjCForCollectionStmt - Label No stack empty");
1501
1502 SourceLocation startLoc = S->getLocStart();
1503 const char *startBuf = SM->getCharacterData(startLoc);
1504 StringRef elementName;
1505 std::string elementTypeAsString;
1506 std::string buf;
1507 buf = "\n{\n\t";
1508 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1509 // type elem;
1510 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1511 QualType ElementType = cast<ValueDecl>(D)->getType();
1512 if (ElementType->isObjCQualifiedIdType() ||
1513 ElementType->isObjCQualifiedInterfaceType())
1514 // Simply use 'id' for all qualified types.
1515 elementTypeAsString = "id";
1516 else
1517 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1518 buf += elementTypeAsString;
1519 buf += " ";
1520 elementName = D->getName();
1521 buf += elementName;
1522 buf += ";\n\t";
1523 }
1524 else {
1525 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1526 elementName = DR->getDecl()->getName();
1527 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1528 if (VD->getType()->isObjCQualifiedIdType() ||
1529 VD->getType()->isObjCQualifiedInterfaceType())
1530 // Simply use 'id' for all qualified types.
1531 elementTypeAsString = "id";
1532 else
1533 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1534 }
1535
1536 // struct __objcFastEnumerationState enumState = { 0 };
1537 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1538 // id __rw_items[16];
1539 buf += "id __rw_items[16];\n\t";
1540 // id l_collection = (id)
1541 buf += "id l_collection = (id)";
1542 // Find start location of 'collection' the hard way!
1543 const char *startCollectionBuf = startBuf;
1544 startCollectionBuf += 3; // skip 'for'
1545 startCollectionBuf = strchr(startCollectionBuf, '(');
1546 startCollectionBuf++; // skip '('
1547 // find 'in' and skip it.
1548 while (*startCollectionBuf != ' ' ||
1549 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1550 (*(startCollectionBuf+3) != ' ' &&
1551 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1552 startCollectionBuf++;
1553 startCollectionBuf += 3;
1554
1555 // Replace: "for (type element in" with string constructed thus far.
1556 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1557 // Replace ')' in for '(' type elem in collection ')' with ';'
1558 SourceLocation rightParenLoc = S->getRParenLoc();
1559 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1560 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1561 buf = ";\n\t";
1562
1563 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1564 // objects:__rw_items count:16];
1565 // which is synthesized into:
1566 // unsigned int limit =
1567 // ((unsigned int (*)
1568 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1569 // (void *)objc_msgSend)((id)l_collection,
1570 // sel_registerName(
1571 // "countByEnumeratingWithState:objects:count:"),
1572 // (struct __objcFastEnumerationState *)&state,
1573 // (id *)__rw_items, (unsigned int)16);
1574 buf += "unsigned long limit =\n\t\t";
1575 SynthCountByEnumWithState(buf);
1576 buf += ";\n\t";
1577 /// if (limit) {
1578 /// unsigned long startMutations = *enumState.mutationsPtr;
1579 /// do {
1580 /// unsigned long counter = 0;
1581 /// do {
1582 /// if (startMutations != *enumState.mutationsPtr)
1583 /// objc_enumerationMutation(l_collection);
1584 /// elem = (type)enumState.itemsPtr[counter++];
1585 buf += "if (limit) {\n\t";
1586 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1587 buf += "do {\n\t\t";
1588 buf += "unsigned long counter = 0;\n\t\t";
1589 buf += "do {\n\t\t\t";
1590 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1591 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1592 buf += elementName;
1593 buf += " = (";
1594 buf += elementTypeAsString;
1595 buf += ")enumState.itemsPtr[counter++];";
1596 // Replace ')' in for '(' type elem in collection ')' with all of these.
1597 ReplaceText(lparenLoc, 1, buf);
1598
1599 /// __continue_label: ;
1600 /// } while (counter < limit);
1601 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1602 /// objects:__rw_items count:16]);
1603 /// elem = nil;
1604 /// __break_label: ;
1605 /// }
1606 /// else
1607 /// elem = nil;
1608 /// }
1609 ///
1610 buf = ";\n\t";
1611 buf += "__continue_label_";
1612 buf += utostr(ObjCBcLabelNo.back());
1613 buf += ": ;";
1614 buf += "\n\t\t";
1615 buf += "} while (counter < limit);\n\t";
1616 buf += "} while (limit = ";
1617 SynthCountByEnumWithState(buf);
1618 buf += ");\n\t";
1619 buf += elementName;
1620 buf += " = ((";
1621 buf += elementTypeAsString;
1622 buf += ")0);\n\t";
1623 buf += "__break_label_";
1624 buf += utostr(ObjCBcLabelNo.back());
1625 buf += ": ;\n\t";
1626 buf += "}\n\t";
1627 buf += "else\n\t\t";
1628 buf += elementName;
1629 buf += " = ((";
1630 buf += elementTypeAsString;
1631 buf += ")0);\n\t";
1632 buf += "}\n";
1633
1634 // Insert all these *after* the statement body.
1635 // FIXME: If this should support Obj-C++, support CXXTryStmt
1636 if (isa<CompoundStmt>(S->getBody())) {
1637 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1638 InsertText(endBodyLoc, buf);
1639 } else {
1640 /* Need to treat single statements specially. For example:
1641 *
1642 * for (A *a in b) if (stuff()) break;
1643 * for (A *a in b) xxxyy;
1644 *
1645 * The following code simply scans ahead to the semi to find the actual end.
1646 */
1647 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1648 const char *semiBuf = strchr(stmtBuf, ';');
1649 assert(semiBuf && "Can't find ';'");
1650 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1651 InsertText(endBodyLoc, buf);
1652 }
1653 Stmts.pop_back();
1654 ObjCBcLabelNo.pop_back();
1655 return 0;
1656}
1657
1658/// RewriteObjCSynchronizedStmt -
1659/// This routine rewrites @synchronized(expr) stmt;
1660/// into:
1661/// objc_sync_enter(expr);
1662/// @try stmt @finally { objc_sync_exit(expr); }
1663///
1664Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1665 // Get the start location and compute the semi location.
1666 SourceLocation startLoc = S->getLocStart();
1667 const char *startBuf = SM->getCharacterData(startLoc);
1668
1669 assert((*startBuf == '@') && "bogus @synchronized location");
1670
1671 std::string buf;
1672 buf = "objc_sync_enter((id)";
1673 const char *lparenBuf = startBuf;
1674 while (*lparenBuf != '(') lparenBuf++;
1675 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1676 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1677 // the sync expression is typically a message expression that's already
1678 // been rewritten! (which implies the SourceLocation's are invalid).
1679 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1680 const char *endBuf = SM->getCharacterData(endLoc);
1681 while (*endBuf != ')') endBuf--;
1682 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1683 buf = ");\n";
1684 // declare a new scope with two variables, _stack and _rethrow.
1685 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1686 buf += "int buf[18/*32-bit i386*/];\n";
1687 buf += "char *pointers[4];} _stack;\n";
1688 buf += "id volatile _rethrow = 0;\n";
1689 buf += "objc_exception_try_enter(&_stack);\n";
1690 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1691 ReplaceText(rparenLoc, 1, buf);
1692 startLoc = S->getSynchBody()->getLocEnd();
1693 startBuf = SM->getCharacterData(startLoc);
1694
1695 assert((*startBuf == '}') && "bogus @synchronized block");
1696 SourceLocation lastCurlyLoc = startLoc;
1697 buf = "}\nelse {\n";
1698 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1699 buf += "}\n";
1700 buf += "{ /* implicit finally clause */\n";
1701 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1702
1703 std::string syncBuf;
1704 syncBuf += " objc_sync_exit(";
1705
1706 Expr *syncExpr = S->getSynchExpr();
1707 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1708 ? CK_BitCast :
1709 syncExpr->getType()->isBlockPointerType()
1710 ? CK_BlockPointerToObjCPointerCast
1711 : CK_CPointerToObjCPointerCast;
1712 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1713 CK, syncExpr);
1714 std::string syncExprBufS;
1715 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1716 syncExpr->printPretty(syncExprBuf, *Context, 0,
1717 PrintingPolicy(LangOpts));
1718 syncBuf += syncExprBuf.str();
1719 syncBuf += ");";
1720
1721 buf += syncBuf;
1722 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1723 buf += "}\n";
1724 buf += "}";
1725
1726 ReplaceText(lastCurlyLoc, 1, buf);
1727
1728 bool hasReturns = false;
1729 HasReturnStmts(S->getSynchBody(), hasReturns);
1730 if (hasReturns)
1731 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1732
1733 return 0;
1734}
1735
1736void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1737{
1738 // Perform a bottom up traversal of all children.
1739 for (Stmt::child_range CI = S->children(); CI; ++CI)
1740 if (*CI)
1741 WarnAboutReturnGotoStmts(*CI);
1742
1743 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1744 Diags.Report(Context->getFullLoc(S->getLocStart()),
1745 TryFinallyContainsReturnDiag);
1746 }
1747 return;
1748}
1749
1750void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1751{
1752 // Perform a bottom up traversal of all children.
1753 for (Stmt::child_range CI = S->children(); CI; ++CI)
1754 if (*CI)
1755 HasReturnStmts(*CI, hasReturns);
1756
1757 if (isa<ReturnStmt>(S))
1758 hasReturns = true;
1759 return;
1760}
1761
1762void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1763 // Perform a bottom up traversal of all children.
1764 for (Stmt::child_range CI = S->children(); CI; ++CI)
1765 if (*CI) {
1766 RewriteTryReturnStmts(*CI);
1767 }
1768 if (isa<ReturnStmt>(S)) {
1769 SourceLocation startLoc = S->getLocStart();
1770 const char *startBuf = SM->getCharacterData(startLoc);
1771
1772 const char *semiBuf = strchr(startBuf, ';');
1773 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1774 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1775
1776 std::string buf;
1777 buf = "{ objc_exception_try_exit(&_stack); return";
1778
1779 ReplaceText(startLoc, 6, buf);
1780 InsertText(onePastSemiLoc, "}");
1781 }
1782 return;
1783}
1784
1785void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1786 // Perform a bottom up traversal of all children.
1787 for (Stmt::child_range CI = S->children(); CI; ++CI)
1788 if (*CI) {
1789 RewriteSyncReturnStmts(*CI, syncExitBuf);
1790 }
1791 if (isa<ReturnStmt>(S)) {
1792 SourceLocation startLoc = S->getLocStart();
1793 const char *startBuf = SM->getCharacterData(startLoc);
1794
1795 const char *semiBuf = strchr(startBuf, ';');
1796 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1797 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1798
1799 std::string buf;
1800 buf = "{ objc_exception_try_exit(&_stack);";
1801 buf += syncExitBuf;
1802 buf += " return";
1803
1804 ReplaceText(startLoc, 6, buf);
1805 InsertText(onePastSemiLoc, "}");
1806 }
1807 return;
1808}
1809
1810Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1811 // Get the start location and compute the semi location.
1812 SourceLocation startLoc = S->getLocStart();
1813 const char *startBuf = SM->getCharacterData(startLoc);
1814
1815 assert((*startBuf == '@') && "bogus @try location");
1816
1817 std::string buf;
1818 // declare a new scope with two variables, _stack and _rethrow.
1819 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1820 buf += "int buf[18/*32-bit i386*/];\n";
1821 buf += "char *pointers[4];} _stack;\n";
1822 buf += "id volatile _rethrow = 0;\n";
1823 buf += "objc_exception_try_enter(&_stack);\n";
1824 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1825
1826 ReplaceText(startLoc, 4, buf);
1827
1828 startLoc = S->getTryBody()->getLocEnd();
1829 startBuf = SM->getCharacterData(startLoc);
1830
1831 assert((*startBuf == '}') && "bogus @try block");
1832
1833 SourceLocation lastCurlyLoc = startLoc;
1834 if (S->getNumCatchStmts()) {
1835 startLoc = startLoc.getLocWithOffset(1);
1836 buf = " /* @catch begin */ else {\n";
1837 buf += " id _caught = objc_exception_extract(&_stack);\n";
1838 buf += " objc_exception_try_enter (&_stack);\n";
1839 buf += " if (_setjmp(_stack.buf))\n";
1840 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1841 buf += " else { /* @catch continue */";
1842
1843 InsertText(startLoc, buf);
1844 } else { /* no catch list */
1845 buf = "}\nelse {\n";
1846 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1847 buf += "}";
1848 ReplaceText(lastCurlyLoc, 1, buf);
1849 }
1850 Stmt *lastCatchBody = 0;
1851 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1852 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1853 VarDecl *catchDecl = Catch->getCatchParamDecl();
1854
1855 if (I == 0)
1856 buf = "if ("; // we are generating code for the first catch clause
1857 else
1858 buf = "else if (";
1859 startLoc = Catch->getLocStart();
1860 startBuf = SM->getCharacterData(startLoc);
1861
1862 assert((*startBuf == '@') && "bogus @catch location");
1863
1864 const char *lParenLoc = strchr(startBuf, '(');
1865
1866 if (Catch->hasEllipsis()) {
1867 // Now rewrite the body...
1868 lastCatchBody = Catch->getCatchBody();
1869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1871 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1872 "bogus @catch paren location");
1873 assert((*bodyBuf == '{') && "bogus @catch body location");
1874
1875 buf += "1) { id _tmp = _caught;";
1876 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1877 } else if (catchDecl) {
1878 QualType t = catchDecl->getType();
1879 if (t == Context->getObjCIdType()) {
1880 buf += "1) { ";
1881 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1882 } else if (const ObjCObjectPointerType *Ptr =
1883 t->getAs<ObjCObjectPointerType>()) {
1884 // Should be a pointer to a class.
1885 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1886 if (IDecl) {
1887 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1888 buf += IDecl->getNameAsString();
1889 buf += "\"), (struct objc_object *)_caught)) { ";
1890 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1891 }
1892 }
1893 // Now rewrite the body...
1894 lastCatchBody = Catch->getCatchBody();
1895 SourceLocation rParenLoc = Catch->getRParenLoc();
1896 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1897 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1898 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1899 assert((*rParenBuf == ')') && "bogus @catch paren location");
1900 assert((*bodyBuf == '{') && "bogus @catch body location");
1901
1902 // Here we replace ") {" with "= _caught;" (which initializes and
1903 // declares the @catch parameter).
1904 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1905 } else {
1906 llvm_unreachable("@catch rewrite bug");
1907 }
1908 }
1909 // Complete the catch list...
1910 if (lastCatchBody) {
1911 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1912 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1913 "bogus @catch body location");
1914
1915 // Insert the last (implicit) else clause *before* the right curly brace.
1916 bodyLoc = bodyLoc.getLocWithOffset(-1);
1917 buf = "} /* last catch end */\n";
1918 buf += "else {\n";
1919 buf += " _rethrow = _caught;\n";
1920 buf += " objc_exception_try_exit(&_stack);\n";
1921 buf += "} } /* @catch end */\n";
1922 if (!S->getFinallyStmt())
1923 buf += "}\n";
1924 InsertText(bodyLoc, buf);
1925
1926 // Set lastCurlyLoc
1927 lastCurlyLoc = lastCatchBody->getLocEnd();
1928 }
1929 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1930 startLoc = finalStmt->getLocStart();
1931 startBuf = SM->getCharacterData(startLoc);
1932 assert((*startBuf == '@') && "bogus @finally start");
1933
1934 ReplaceText(startLoc, 8, "/* @finally */");
1935
1936 Stmt *body = finalStmt->getFinallyBody();
1937 SourceLocation startLoc = body->getLocStart();
1938 SourceLocation endLoc = body->getLocEnd();
1939 assert(*SM->getCharacterData(startLoc) == '{' &&
1940 "bogus @finally body location");
1941 assert(*SM->getCharacterData(endLoc) == '}' &&
1942 "bogus @finally body location");
1943
1944 startLoc = startLoc.getLocWithOffset(1);
1945 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1946 endLoc = endLoc.getLocWithOffset(-1);
1947 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1948
1949 // Set lastCurlyLoc
1950 lastCurlyLoc = body->getLocEnd();
1951
1952 // Now check for any return/continue/go statements within the @try.
1953 WarnAboutReturnGotoStmts(S->getTryBody());
1954 } else { /* no finally clause - make sure we synthesize an implicit one */
1955 buf = "{ /* implicit finally clause */\n";
1956 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1957 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1958 buf += "}";
1959 ReplaceText(lastCurlyLoc, 1, buf);
1960
1961 // Now check for any return/continue/go statements within the @try.
1962 // The implicit finally clause won't called if the @try contains any
1963 // jump statements.
1964 bool hasReturns = false;
1965 HasReturnStmts(S->getTryBody(), hasReturns);
1966 if (hasReturns)
1967 RewriteTryReturnStmts(S->getTryBody());
1968 }
1969 // Now emit the final closing curly brace...
1970 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1971 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1972 return 0;
1973}
1974
1975// This can't be done with ReplaceStmt(S, ThrowExpr), since
1976// the throw expression is typically a message expression that's already
1977// been rewritten! (which implies the SourceLocation's are invalid).
1978Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1979 // Get the start location and compute the semi location.
1980 SourceLocation startLoc = S->getLocStart();
1981 const char *startBuf = SM->getCharacterData(startLoc);
1982
1983 assert((*startBuf == '@') && "bogus @throw location");
1984
1985 std::string buf;
1986 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1987 if (S->getThrowExpr())
1988 buf = "objc_exception_throw(";
1989 else // add an implicit argument
1990 buf = "objc_exception_throw(_caught";
1991
1992 // handle "@ throw" correctly.
1993 const char *wBuf = strchr(startBuf, 'w');
1994 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1995 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1996
1997 const char *semiBuf = strchr(startBuf, ';');
1998 assert((*semiBuf == ';') && "@throw: can't find ';'");
1999 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2000 ReplaceText(semiLoc, 1, ");");
2001 return 0;
2002}
2003
2004Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2005 // Create a new string expression.
2006 QualType StrType = Context->getPointerType(Context->CharTy);
2007 std::string StrEncoding;
2008 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2009 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2010 StringLiteral::Ascii, false,
2011 StrType, SourceLocation());
2012 ReplaceStmt(Exp, Replacement);
2013
2014 // Replace this subexpr in the parent.
2015 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2016 return Replacement;
2017}
2018
2019Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2020 if (!SelGetUidFunctionDecl)
2021 SynthSelGetUidFunctionDecl();
2022 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2023 // Create a call to sel_registerName("selName").
2024 SmallVector<Expr*, 8> SelExprs;
2025 QualType argType = Context->getPointerType(Context->CharTy);
2026 SelExprs.push_back(StringLiteral::Create(*Context,
2027 Exp->getSelector().getAsString(),
2028 StringLiteral::Ascii, false,
2029 argType, SourceLocation()));
2030 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2031 &SelExprs[0], SelExprs.size());
2032 ReplaceStmt(Exp, SelExp);
2033 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2034 return SelExp;
2035}
2036
2037CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2038 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2039 SourceLocation EndLoc) {
2040 // Get the type, we will need to reference it in a couple spots.
2041 QualType msgSendType = FD->getType();
2042
2043 // Create a reference to the objc_msgSend() declaration.
2044 DeclRefExpr *DRE =
2045 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2046
2047 // Now, we cast the reference to a pointer to the objc_msgSend type.
2048 QualType pToFunc = Context->getPointerType(msgSendType);
2049 ImplicitCastExpr *ICE =
2050 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2051 DRE, 0, VK_RValue);
2052
2053 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2054
2055 CallExpr *Exp =
2056 new (Context) CallExpr(*Context, ICE, args, nargs,
2057 FT->getCallResultType(*Context),
2058 VK_RValue, EndLoc);
2059 return Exp;
2060}
2061
2062static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2063 const char *&startRef, const char *&endRef) {
2064 while (startBuf < endBuf) {
2065 if (*startBuf == '<')
2066 startRef = startBuf; // mark the start.
2067 if (*startBuf == '>') {
2068 if (startRef && *startRef == '<') {
2069 endRef = startBuf; // mark the end.
2070 return true;
2071 }
2072 return false;
2073 }
2074 startBuf++;
2075 }
2076 return false;
2077}
2078
2079static void scanToNextArgument(const char *&argRef) {
2080 int angle = 0;
2081 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2082 if (*argRef == '<')
2083 angle++;
2084 else if (*argRef == '>')
2085 angle--;
2086 argRef++;
2087 }
2088 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2089}
2090
2091bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2092 if (T->isObjCQualifiedIdType())
2093 return true;
2094 if (const PointerType *PT = T->getAs<PointerType>()) {
2095 if (PT->getPointeeType()->isObjCQualifiedIdType())
2096 return true;
2097 }
2098 if (T->isObjCObjectPointerType()) {
2099 T = T->getPointeeType();
2100 return T->isObjCQualifiedInterfaceType();
2101 }
2102 if (T->isArrayType()) {
2103 QualType ElemTy = Context->getBaseElementType(T);
2104 return needToScanForQualifiers(ElemTy);
2105 }
2106 return false;
2107}
2108
2109void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2110 QualType Type = E->getType();
2111 if (needToScanForQualifiers(Type)) {
2112 SourceLocation Loc, EndLoc;
2113
2114 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2115 Loc = ECE->getLParenLoc();
2116 EndLoc = ECE->getRParenLoc();
2117 } else {
2118 Loc = E->getLocStart();
2119 EndLoc = E->getLocEnd();
2120 }
2121 // This will defend against trying to rewrite synthesized expressions.
2122 if (Loc.isInvalid() || EndLoc.isInvalid())
2123 return;
2124
2125 const char *startBuf = SM->getCharacterData(Loc);
2126 const char *endBuf = SM->getCharacterData(EndLoc);
2127 const char *startRef = 0, *endRef = 0;
2128 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2129 // Get the locations of the startRef, endRef.
2130 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2131 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2132 // Comment out the protocol references.
2133 InsertText(LessLoc, "/*");
2134 InsertText(GreaterLoc, "*/");
2135 }
2136 }
2137}
2138
2139void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2140 SourceLocation Loc;
2141 QualType Type;
2142 const FunctionProtoType *proto = 0;
2143 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2144 Loc = VD->getLocation();
2145 Type = VD->getType();
2146 }
2147 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2148 Loc = FD->getLocation();
2149 // Check for ObjC 'id' and class types that have been adorned with protocol
2150 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2151 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2152 assert(funcType && "missing function type");
2153 proto = dyn_cast<FunctionProtoType>(funcType);
2154 if (!proto)
2155 return;
2156 Type = proto->getResultType();
2157 }
2158 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2159 Loc = FD->getLocation();
2160 Type = FD->getType();
2161 }
2162 else
2163 return;
2164
2165 if (needToScanForQualifiers(Type)) {
2166 // Since types are unique, we need to scan the buffer.
2167
2168 const char *endBuf = SM->getCharacterData(Loc);
2169 const char *startBuf = endBuf;
2170 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2171 startBuf--; // scan backward (from the decl location) for return type.
2172 const char *startRef = 0, *endRef = 0;
2173 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2174 // Get the locations of the startRef, endRef.
2175 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2176 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2177 // Comment out the protocol references.
2178 InsertText(LessLoc, "/*");
2179 InsertText(GreaterLoc, "*/");
2180 }
2181 }
2182 if (!proto)
2183 return; // most likely, was a variable
2184 // Now check arguments.
2185 const char *startBuf = SM->getCharacterData(Loc);
2186 const char *startFuncBuf = startBuf;
2187 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2188 if (needToScanForQualifiers(proto->getArgType(i))) {
2189 // Since types are unique, we need to scan the buffer.
2190
2191 const char *endBuf = startBuf;
2192 // scan forward (from the decl location) for argument types.
2193 scanToNextArgument(endBuf);
2194 const char *startRef = 0, *endRef = 0;
2195 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2196 // Get the locations of the startRef, endRef.
2197 SourceLocation LessLoc =
2198 Loc.getLocWithOffset(startRef-startFuncBuf);
2199 SourceLocation GreaterLoc =
2200 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2201 // Comment out the protocol references.
2202 InsertText(LessLoc, "/*");
2203 InsertText(GreaterLoc, "*/");
2204 }
2205 startBuf = ++endBuf;
2206 }
2207 else {
2208 // If the function name is derived from a macro expansion, then the
2209 // argument buffer will not follow the name. Need to speak with Chris.
2210 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2211 startBuf++; // scan forward (from the decl location) for argument types.
2212 startBuf++;
2213 }
2214 }
2215}
2216
2217void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2218 QualType QT = ND->getType();
2219 const Type* TypePtr = QT->getAs<Type>();
2220 if (!isa<TypeOfExprType>(TypePtr))
2221 return;
2222 while (isa<TypeOfExprType>(TypePtr)) {
2223 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2224 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2225 TypePtr = QT->getAs<Type>();
2226 }
2227 // FIXME. This will not work for multiple declarators; as in:
2228 // __typeof__(a) b,c,d;
2229 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2230 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2231 const char *startBuf = SM->getCharacterData(DeclLoc);
2232 if (ND->getInit()) {
2233 std::string Name(ND->getNameAsString());
2234 TypeAsString += " " + Name + " = ";
2235 Expr *E = ND->getInit();
2236 SourceLocation startLoc;
2237 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2238 startLoc = ECE->getLParenLoc();
2239 else
2240 startLoc = E->getLocStart();
2241 startLoc = SM->getExpansionLoc(startLoc);
2242 const char *endBuf = SM->getCharacterData(startLoc);
2243 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2244 }
2245 else {
2246 SourceLocation X = ND->getLocEnd();
2247 X = SM->getExpansionLoc(X);
2248 const char *endBuf = SM->getCharacterData(X);
2249 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2250 }
2251}
2252
2253// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2254void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2255 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2256 SmallVector<QualType, 16> ArgTys;
2257 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2258 QualType getFuncType =
2259 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2260 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2261 SourceLocation(),
2262 SourceLocation(),
2263 SelGetUidIdent, getFuncType, 0,
2264 SC_Extern,
2265 SC_None, false);
2266}
2267
2268void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2269 // declared in <objc/objc.h>
2270 if (FD->getIdentifier() &&
2271 FD->getName() == "sel_registerName") {
2272 SelGetUidFunctionDecl = FD;
2273 return;
2274 }
2275 RewriteObjCQualifiedInterfaceTypes(FD);
2276}
2277
2278void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2279 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2280 const char *argPtr = TypeString.c_str();
2281 if (!strchr(argPtr, '^')) {
2282 Str += TypeString;
2283 return;
2284 }
2285 while (*argPtr) {
2286 Str += (*argPtr == '^' ? '*' : *argPtr);
2287 argPtr++;
2288 }
2289}
2290
2291// FIXME. Consolidate this routine with RewriteBlockPointerType.
2292void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2293 ValueDecl *VD) {
2294 QualType Type = VD->getType();
2295 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2296 const char *argPtr = TypeString.c_str();
2297 int paren = 0;
2298 while (*argPtr) {
2299 switch (*argPtr) {
2300 case '(':
2301 Str += *argPtr;
2302 paren++;
2303 break;
2304 case ')':
2305 Str += *argPtr;
2306 paren--;
2307 break;
2308 case '^':
2309 Str += '*';
2310 if (paren == 1)
2311 Str += VD->getNameAsString();
2312 break;
2313 default:
2314 Str += *argPtr;
2315 break;
2316 }
2317 argPtr++;
2318 }
2319}
2320
2321
2322void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2323 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2324 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2325 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2326 if (!proto)
2327 return;
2328 QualType Type = proto->getResultType();
2329 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2330 FdStr += " ";
2331 FdStr += FD->getName();
2332 FdStr += "(";
2333 unsigned numArgs = proto->getNumArgs();
2334 for (unsigned i = 0; i < numArgs; i++) {
2335 QualType ArgType = proto->getArgType(i);
2336 RewriteBlockPointerType(FdStr, ArgType);
2337 if (i+1 < numArgs)
2338 FdStr += ", ";
2339 }
2340 FdStr += ");\n";
2341 InsertText(FunLocStart, FdStr);
2342 CurFunctionDeclToDeclareForBlock = 0;
2343}
2344
2345// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2346void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2347 if (SuperContructorFunctionDecl)
2348 return;
2349 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2350 SmallVector<QualType, 16> ArgTys;
2351 QualType argT = Context->getObjCIdType();
2352 assert(!argT.isNull() && "Can't find 'id' type");
2353 ArgTys.push_back(argT);
2354 ArgTys.push_back(argT);
2355 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2356 &ArgTys[0], ArgTys.size());
2357 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2366void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 argT = Context->getObjCSelType();
2373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2376 &ArgTys[0], ArgTys.size(),
2377 true /*isVariadic*/);
2378 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2379 SourceLocation(),
2380 SourceLocation(),
2381 msgSendIdent, msgSendType, 0,
2382 SC_Extern,
2383 SC_None, false);
2384}
2385
2386// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2387void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2388 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2389 SmallVector<QualType, 16> ArgTys;
2390 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2391 SourceLocation(), SourceLocation(),
2392 &Context->Idents.get("objc_super"));
2393 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2394 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2395 ArgTys.push_back(argT);
2396 argT = Context->getObjCSelType();
2397 assert(!argT.isNull() && "Can't find 'SEL' type");
2398 ArgTys.push_back(argT);
2399 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2400 &ArgTys[0], ArgTys.size(),
2401 true /*isVariadic*/);
2402 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2403 SourceLocation(),
2404 SourceLocation(),
2405 msgSendIdent, msgSendType, 0,
2406 SC_Extern,
2407 SC_None, false);
2408}
2409
2410// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2411void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2412 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2413 SmallVector<QualType, 16> ArgTys;
2414 QualType argT = Context->getObjCIdType();
2415 assert(!argT.isNull() && "Can't find 'id' type");
2416 ArgTys.push_back(argT);
2417 argT = Context->getObjCSelType();
2418 assert(!argT.isNull() && "Can't find 'SEL' type");
2419 ArgTys.push_back(argT);
2420 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2421 &ArgTys[0], ArgTys.size(),
2422 true /*isVariadic*/);
2423 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2424 SourceLocation(),
2425 SourceLocation(),
2426 msgSendIdent, msgSendType, 0,
2427 SC_Extern,
2428 SC_None, false);
2429}
2430
2431// SynthMsgSendSuperStretFunctionDecl -
2432// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2433void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2434 IdentifierInfo *msgSendIdent =
2435 &Context->Idents.get("objc_msgSendSuper_stret");
2436 SmallVector<QualType, 16> ArgTys;
2437 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2438 SourceLocation(), SourceLocation(),
2439 &Context->Idents.get("objc_super"));
2440 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2441 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2442 ArgTys.push_back(argT);
2443 argT = Context->getObjCSelType();
2444 assert(!argT.isNull() && "Can't find 'SEL' type");
2445 ArgTys.push_back(argT);
2446 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2447 &ArgTys[0], ArgTys.size(),
2448 true /*isVariadic*/);
2449 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2450 SourceLocation(),
2451 SourceLocation(),
2452 msgSendIdent, msgSendType, 0,
2453 SC_Extern,
2454 SC_None, false);
2455}
2456
2457// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2458void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 argT = Context->getObjCSelType();
2465 assert(!argT.isNull() && "Can't find 'SEL' type");
2466 ArgTys.push_back(argT);
2467 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2468 &ArgTys[0], ArgTys.size(),
2469 true /*isVariadic*/);
2470 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2471 SourceLocation(),
2472 SourceLocation(),
2473 msgSendIdent, msgSendType, 0,
2474 SC_Extern,
2475 SC_None, false);
2476}
2477
2478// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2479void RewriteModernObjC::SynthGetClassFunctionDecl() {
2480 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2481 SmallVector<QualType, 16> ArgTys;
2482 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2483 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2484 &ArgTys[0], ArgTys.size());
2485 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2486 SourceLocation(),
2487 SourceLocation(),
2488 getClassIdent, getClassType, 0,
2489 SC_Extern,
2490 SC_None, false);
2491}
2492
2493// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2494void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2495 IdentifierInfo *getSuperClassIdent =
2496 &Context->Idents.get("class_getSuperclass");
2497 SmallVector<QualType, 16> ArgTys;
2498 ArgTys.push_back(Context->getObjCClassType());
2499 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2500 &ArgTys[0], ArgTys.size());
2501 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2502 SourceLocation(),
2503 SourceLocation(),
2504 getSuperClassIdent,
2505 getClassType, 0,
2506 SC_Extern,
2507 SC_None,
2508 false);
2509}
2510
2511// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2512void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2513 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2514 SmallVector<QualType, 16> ArgTys;
2515 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2516 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2517 &ArgTys[0], ArgTys.size());
2518 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2519 SourceLocation(),
2520 SourceLocation(),
2521 getClassIdent, getClassType, 0,
2522 SC_Extern,
2523 SC_None, false);
2524}
2525
2526Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2527 QualType strType = getConstantStringStructType();
2528
2529 std::string S = "__NSConstantStringImpl_";
2530
2531 std::string tmpName = InFileName;
2532 unsigned i;
2533 for (i=0; i < tmpName.length(); i++) {
2534 char c = tmpName.at(i);
2535 // replace any non alphanumeric characters with '_'.
2536 if (!isalpha(c) && (c < '0' || c > '9'))
2537 tmpName[i] = '_';
2538 }
2539 S += tmpName;
2540 S += "_";
2541 S += utostr(NumObjCStringLiterals++);
2542
2543 Preamble += "static __NSConstantStringImpl " + S;
2544 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2545 Preamble += "0x000007c8,"; // utf8_str
2546 // The pretty printer for StringLiteral handles escape characters properly.
2547 std::string prettyBufS;
2548 llvm::raw_string_ostream prettyBuf(prettyBufS);
2549 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2550 PrintingPolicy(LangOpts));
2551 Preamble += prettyBuf.str();
2552 Preamble += ",";
2553 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2554
2555 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2556 SourceLocation(), &Context->Idents.get(S),
2557 strType, 0, SC_Static, SC_None);
2558 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2559 SourceLocation());
2560 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2561 Context->getPointerType(DRE->getType()),
2562 VK_RValue, OK_Ordinary,
2563 SourceLocation());
2564 // cast to NSConstantString *
2565 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2566 CK_CPointerToObjCPointerCast, Unop);
2567 ReplaceStmt(Exp, cast);
2568 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2569 return cast;
2570}
2571
2572// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2573QualType RewriteModernObjC::getSuperStructType() {
2574 if (!SuperStructDecl) {
2575 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2576 SourceLocation(), SourceLocation(),
2577 &Context->Idents.get("objc_super"));
2578 QualType FieldTypes[2];
2579
2580 // struct objc_object *receiver;
2581 FieldTypes[0] = Context->getObjCIdType();
2582 // struct objc_class *super;
2583 FieldTypes[1] = Context->getObjCClassType();
2584
2585 // Create fields
2586 for (unsigned i = 0; i < 2; ++i) {
2587 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2588 SourceLocation(),
2589 SourceLocation(), 0,
2590 FieldTypes[i], 0,
2591 /*BitWidth=*/0,
2592 /*Mutable=*/false,
2593 /*HasInit=*/false));
2594 }
2595
2596 SuperStructDecl->completeDefinition();
2597 }
2598 return Context->getTagDeclType(SuperStructDecl);
2599}
2600
2601QualType RewriteModernObjC::getConstantStringStructType() {
2602 if (!ConstantStringDecl) {
2603 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2604 SourceLocation(), SourceLocation(),
2605 &Context->Idents.get("__NSConstantStringImpl"));
2606 QualType FieldTypes[4];
2607
2608 // struct objc_object *receiver;
2609 FieldTypes[0] = Context->getObjCIdType();
2610 // int flags;
2611 FieldTypes[1] = Context->IntTy;
2612 // char *str;
2613 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2614 // long length;
2615 FieldTypes[3] = Context->LongTy;
2616
2617 // Create fields
2618 for (unsigned i = 0; i < 4; ++i) {
2619 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2620 ConstantStringDecl,
2621 SourceLocation(),
2622 SourceLocation(), 0,
2623 FieldTypes[i], 0,
2624 /*BitWidth=*/0,
2625 /*Mutable=*/true,
2626 /*HasInit=*/false));
2627 }
2628
2629 ConstantStringDecl->completeDefinition();
2630 }
2631 return Context->getTagDeclType(ConstantStringDecl);
2632}
2633
2634Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2635 SourceLocation StartLoc,
2636 SourceLocation EndLoc) {
2637 if (!SelGetUidFunctionDecl)
2638 SynthSelGetUidFunctionDecl();
2639 if (!MsgSendFunctionDecl)
2640 SynthMsgSendFunctionDecl();
2641 if (!MsgSendSuperFunctionDecl)
2642 SynthMsgSendSuperFunctionDecl();
2643 if (!MsgSendStretFunctionDecl)
2644 SynthMsgSendStretFunctionDecl();
2645 if (!MsgSendSuperStretFunctionDecl)
2646 SynthMsgSendSuperStretFunctionDecl();
2647 if (!MsgSendFpretFunctionDecl)
2648 SynthMsgSendFpretFunctionDecl();
2649 if (!GetClassFunctionDecl)
2650 SynthGetClassFunctionDecl();
2651 if (!GetSuperClassFunctionDecl)
2652 SynthGetSuperClassFunctionDecl();
2653 if (!GetMetaClassFunctionDecl)
2654 SynthGetMetaClassFunctionDecl();
2655
2656 // default to objc_msgSend().
2657 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2658 // May need to use objc_msgSend_stret() as well.
2659 FunctionDecl *MsgSendStretFlavor = 0;
2660 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2661 QualType resultType = mDecl->getResultType();
2662 if (resultType->isRecordType())
2663 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2664 else if (resultType->isRealFloatingType())
2665 MsgSendFlavor = MsgSendFpretFunctionDecl;
2666 }
2667
2668 // Synthesize a call to objc_msgSend().
2669 SmallVector<Expr*, 8> MsgExprs;
2670 switch (Exp->getReceiverKind()) {
2671 case ObjCMessageExpr::SuperClass: {
2672 MsgSendFlavor = MsgSendSuperFunctionDecl;
2673 if (MsgSendStretFlavor)
2674 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2675 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2676
2677 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2678
2679 SmallVector<Expr*, 4> InitExprs;
2680
2681 // set the receiver to self, the first argument to all methods.
2682 InitExprs.push_back(
2683 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2684 CK_BitCast,
2685 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2686 Context->getObjCIdType(),
2687 VK_RValue,
2688 SourceLocation()))
2689 ); // set the 'receiver'.
2690
2691 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2692 SmallVector<Expr*, 8> ClsExprs;
2693 QualType argType = Context->getPointerType(Context->CharTy);
2694 ClsExprs.push_back(StringLiteral::Create(*Context,
2695 ClassDecl->getIdentifier()->getName(),
2696 StringLiteral::Ascii, false,
2697 argType, SourceLocation()));
2698 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2699 &ClsExprs[0],
2700 ClsExprs.size(),
2701 StartLoc,
2702 EndLoc);
2703 // (Class)objc_getClass("CurrentClass")
2704 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2705 Context->getObjCClassType(),
2706 CK_BitCast, Cls);
2707 ClsExprs.clear();
2708 ClsExprs.push_back(ArgExpr);
2709 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2710 &ClsExprs[0], ClsExprs.size(),
2711 StartLoc, EndLoc);
2712
2713 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2714 // To turn off a warning, type-cast to 'id'
2715 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2716 NoTypeInfoCStyleCastExpr(Context,
2717 Context->getObjCIdType(),
2718 CK_BitCast, Cls));
2719 // struct objc_super
2720 QualType superType = getSuperStructType();
2721 Expr *SuperRep;
2722
2723 if (LangOpts.MicrosoftExt) {
2724 SynthSuperContructorFunctionDecl();
2725 // Simulate a contructor call...
2726 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2727 superType, VK_LValue,
2728 SourceLocation());
2729 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2730 InitExprs.size(),
2731 superType, VK_LValue,
2732 SourceLocation());
2733 // The code for super is a little tricky to prevent collision with
2734 // the structure definition in the header. The rewriter has it's own
2735 // internal definition (__rw_objc_super) that is uses. This is why
2736 // we need the cast below. For example:
2737 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2738 //
2739 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2740 Context->getPointerType(SuperRep->getType()),
2741 VK_RValue, OK_Ordinary,
2742 SourceLocation());
2743 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2744 Context->getPointerType(superType),
2745 CK_BitCast, SuperRep);
2746 } else {
2747 // (struct objc_super) { <exprs from above> }
2748 InitListExpr *ILE =
2749 new (Context) InitListExpr(*Context, SourceLocation(),
2750 &InitExprs[0], InitExprs.size(),
2751 SourceLocation());
2752 TypeSourceInfo *superTInfo
2753 = Context->getTrivialTypeSourceInfo(superType);
2754 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2755 superType, VK_LValue,
2756 ILE, false);
2757 // struct objc_super *
2758 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2759 Context->getPointerType(SuperRep->getType()),
2760 VK_RValue, OK_Ordinary,
2761 SourceLocation());
2762 }
2763 MsgExprs.push_back(SuperRep);
2764 break;
2765 }
2766
2767 case ObjCMessageExpr::Class: {
2768 SmallVector<Expr*, 8> ClsExprs;
2769 QualType argType = Context->getPointerType(Context->CharTy);
2770 ObjCInterfaceDecl *Class
2771 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2772 IdentifierInfo *clsName = Class->getIdentifier();
2773 ClsExprs.push_back(StringLiteral::Create(*Context,
2774 clsName->getName(),
2775 StringLiteral::Ascii, false,
2776 argType, SourceLocation()));
2777 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2778 &ClsExprs[0],
2779 ClsExprs.size(),
2780 StartLoc, EndLoc);
2781 MsgExprs.push_back(Cls);
2782 break;
2783 }
2784
2785 case ObjCMessageExpr::SuperInstance:{
2786 MsgSendFlavor = MsgSendSuperFunctionDecl;
2787 if (MsgSendStretFlavor)
2788 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2789 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2790 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2791 SmallVector<Expr*, 4> InitExprs;
2792
2793 InitExprs.push_back(
2794 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2795 CK_BitCast,
2796 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2797 Context->getObjCIdType(),
2798 VK_RValue, SourceLocation()))
2799 ); // set the 'receiver'.
2800
2801 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2802 SmallVector<Expr*, 8> ClsExprs;
2803 QualType argType = Context->getPointerType(Context->CharTy);
2804 ClsExprs.push_back(StringLiteral::Create(*Context,
2805 ClassDecl->getIdentifier()->getName(),
2806 StringLiteral::Ascii, false, argType,
2807 SourceLocation()));
2808 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2809 &ClsExprs[0],
2810 ClsExprs.size(),
2811 StartLoc, EndLoc);
2812 // (Class)objc_getClass("CurrentClass")
2813 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2814 Context->getObjCClassType(),
2815 CK_BitCast, Cls);
2816 ClsExprs.clear();
2817 ClsExprs.push_back(ArgExpr);
2818 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2819 &ClsExprs[0], ClsExprs.size(),
2820 StartLoc, EndLoc);
2821
2822 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2823 // To turn off a warning, type-cast to 'id'
2824 InitExprs.push_back(
2825 // set 'super class', using class_getSuperclass().
2826 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2827 CK_BitCast, Cls));
2828 // struct objc_super
2829 QualType superType = getSuperStructType();
2830 Expr *SuperRep;
2831
2832 if (LangOpts.MicrosoftExt) {
2833 SynthSuperContructorFunctionDecl();
2834 // Simulate a contructor call...
2835 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2836 superType, VK_LValue,
2837 SourceLocation());
2838 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2839 InitExprs.size(),
2840 superType, VK_LValue, SourceLocation());
2841 // The code for super is a little tricky to prevent collision with
2842 // the structure definition in the header. The rewriter has it's own
2843 // internal definition (__rw_objc_super) that is uses. This is why
2844 // we need the cast below. For example:
2845 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2846 //
2847 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2848 Context->getPointerType(SuperRep->getType()),
2849 VK_RValue, OK_Ordinary,
2850 SourceLocation());
2851 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2852 Context->getPointerType(superType),
2853 CK_BitCast, SuperRep);
2854 } else {
2855 // (struct objc_super) { <exprs from above> }
2856 InitListExpr *ILE =
2857 new (Context) InitListExpr(*Context, SourceLocation(),
2858 &InitExprs[0], InitExprs.size(),
2859 SourceLocation());
2860 TypeSourceInfo *superTInfo
2861 = Context->getTrivialTypeSourceInfo(superType);
2862 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2863 superType, VK_RValue, ILE,
2864 false);
2865 }
2866 MsgExprs.push_back(SuperRep);
2867 break;
2868 }
2869
2870 case ObjCMessageExpr::Instance: {
2871 // Remove all type-casts because it may contain objc-style types; e.g.
2872 // Foo<Proto> *.
2873 Expr *recExpr = Exp->getInstanceReceiver();
2874 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2875 recExpr = CE->getSubExpr();
2876 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2877 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2878 ? CK_BlockPointerToObjCPointerCast
2879 : CK_CPointerToObjCPointerCast;
2880
2881 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2882 CK, recExpr);
2883 MsgExprs.push_back(recExpr);
2884 break;
2885 }
2886 }
2887
2888 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2889 SmallVector<Expr*, 8> SelExprs;
2890 QualType argType = Context->getPointerType(Context->CharTy);
2891 SelExprs.push_back(StringLiteral::Create(*Context,
2892 Exp->getSelector().getAsString(),
2893 StringLiteral::Ascii, false,
2894 argType, SourceLocation()));
2895 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2896 &SelExprs[0], SelExprs.size(),
2897 StartLoc,
2898 EndLoc);
2899 MsgExprs.push_back(SelExp);
2900
2901 // Now push any user supplied arguments.
2902 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2903 Expr *userExpr = Exp->getArg(i);
2904 // Make all implicit casts explicit...ICE comes in handy:-)
2905 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2906 // Reuse the ICE type, it is exactly what the doctor ordered.
2907 QualType type = ICE->getType();
2908 if (needToScanForQualifiers(type))
2909 type = Context->getObjCIdType();
2910 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2911 (void)convertBlockPointerToFunctionPointer(type);
2912 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2913 CastKind CK;
2914 if (SubExpr->getType()->isIntegralType(*Context) &&
2915 type->isBooleanType()) {
2916 CK = CK_IntegralToBoolean;
2917 } else if (type->isObjCObjectPointerType()) {
2918 if (SubExpr->getType()->isBlockPointerType()) {
2919 CK = CK_BlockPointerToObjCPointerCast;
2920 } else if (SubExpr->getType()->isPointerType()) {
2921 CK = CK_CPointerToObjCPointerCast;
2922 } else {
2923 CK = CK_BitCast;
2924 }
2925 } else {
2926 CK = CK_BitCast;
2927 }
2928
2929 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2930 }
2931 // Make id<P...> cast into an 'id' cast.
2932 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2933 if (CE->getType()->isObjCQualifiedIdType()) {
2934 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2935 userExpr = CE->getSubExpr();
2936 CastKind CK;
2937 if (userExpr->getType()->isIntegralType(*Context)) {
2938 CK = CK_IntegralToPointer;
2939 } else if (userExpr->getType()->isBlockPointerType()) {
2940 CK = CK_BlockPointerToObjCPointerCast;
2941 } else if (userExpr->getType()->isPointerType()) {
2942 CK = CK_CPointerToObjCPointerCast;
2943 } else {
2944 CK = CK_BitCast;
2945 }
2946 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2947 CK, userExpr);
2948 }
2949 }
2950 MsgExprs.push_back(userExpr);
2951 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2952 // out the argument in the original expression (since we aren't deleting
2953 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2954 //Exp->setArg(i, 0);
2955 }
2956 // Generate the funky cast.
2957 CastExpr *cast;
2958 SmallVector<QualType, 8> ArgTypes;
2959 QualType returnType;
2960
2961 // Push 'id' and 'SEL', the 2 implicit arguments.
2962 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2963 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2964 else
2965 ArgTypes.push_back(Context->getObjCIdType());
2966 ArgTypes.push_back(Context->getObjCSelType());
2967 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2968 // Push any user argument types.
2969 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2970 E = OMD->param_end(); PI != E; ++PI) {
2971 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2972 ? Context->getObjCIdType()
2973 : (*PI)->getType();
2974 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2975 (void)convertBlockPointerToFunctionPointer(t);
2976 ArgTypes.push_back(t);
2977 }
2978 returnType = Exp->getType();
2979 convertToUnqualifiedObjCType(returnType);
2980 (void)convertBlockPointerToFunctionPointer(returnType);
2981 } else {
2982 returnType = Context->getObjCIdType();
2983 }
2984 // Get the type, we will need to reference it in a couple spots.
2985 QualType msgSendType = MsgSendFlavor->getType();
2986
2987 // Create a reference to the objc_msgSend() declaration.
2988 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2989 VK_LValue, SourceLocation());
2990
2991 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2992 // If we don't do this cast, we get the following bizarre warning/note:
2993 // xx.m:13: warning: function called through a non-compatible type
2994 // xx.m:13: note: if this code is reached, the program will abort
2995 cast = NoTypeInfoCStyleCastExpr(Context,
2996 Context->getPointerType(Context->VoidTy),
2997 CK_BitCast, DRE);
2998
2999 // Now do the "normal" pointer to function cast.
3000 QualType castType =
3001 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3002 // If we don't have a method decl, force a variadic cast.
3003 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3004 castType = Context->getPointerType(castType);
3005 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3006 cast);
3007
3008 // Don't forget the parens to enforce the proper binding.
3009 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3010
3011 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3012 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3013 MsgExprs.size(),
3014 FT->getResultType(), VK_RValue,
3015 EndLoc);
3016 Stmt *ReplacingStmt = CE;
3017 if (MsgSendStretFlavor) {
3018 // We have the method which returns a struct/union. Must also generate
3019 // call to objc_msgSend_stret and hang both varieties on a conditional
3020 // expression which dictate which one to envoke depending on size of
3021 // method's return type.
3022
3023 // Create a reference to the objc_msgSend_stret() declaration.
3024 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3025 VK_LValue, SourceLocation());
3026 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3027 cast = NoTypeInfoCStyleCastExpr(Context,
3028 Context->getPointerType(Context->VoidTy),
3029 CK_BitCast, STDRE);
3030 // Now do the "normal" pointer to function cast.
3031 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3032 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3033 castType = Context->getPointerType(castType);
3034 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3035 cast);
3036
3037 // Don't forget the parens to enforce the proper binding.
3038 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3039
3040 FT = msgSendType->getAs<FunctionType>();
3041 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3042 MsgExprs.size(),
3043 FT->getResultType(), VK_RValue,
3044 SourceLocation());
3045
3046 // Build sizeof(returnType)
3047 UnaryExprOrTypeTraitExpr *sizeofExpr =
3048 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3049 Context->getTrivialTypeSourceInfo(returnType),
3050 Context->getSizeType(), SourceLocation(),
3051 SourceLocation());
3052 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3053 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3054 // For X86 it is more complicated and some kind of target specific routine
3055 // is needed to decide what to do.
3056 unsigned IntSize =
3057 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3058 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3059 llvm::APInt(IntSize, 8),
3060 Context->IntTy,
3061 SourceLocation());
3062 BinaryOperator *lessThanExpr =
3063 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3064 VK_RValue, OK_Ordinary, SourceLocation());
3065 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3066 ConditionalOperator *CondExpr =
3067 new (Context) ConditionalOperator(lessThanExpr,
3068 SourceLocation(), CE,
3069 SourceLocation(), STCE,
3070 returnType, VK_RValue, OK_Ordinary);
3071 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3072 CondExpr);
3073 }
3074 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3075 return ReplacingStmt;
3076}
3077
3078Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3079 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3080 Exp->getLocEnd());
3081
3082 // Now do the actual rewrite.
3083 ReplaceStmt(Exp, ReplacingStmt);
3084
3085 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3086 return ReplacingStmt;
3087}
3088
3089// typedef struct objc_object Protocol;
3090QualType RewriteModernObjC::getProtocolType() {
3091 if (!ProtocolTypeDecl) {
3092 TypeSourceInfo *TInfo
3093 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3094 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3095 SourceLocation(), SourceLocation(),
3096 &Context->Idents.get("Protocol"),
3097 TInfo);
3098 }
3099 return Context->getTypeDeclType(ProtocolTypeDecl);
3100}
3101
3102/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3103/// a synthesized/forward data reference (to the protocol's metadata).
3104/// The forward references (and metadata) are generated in
3105/// RewriteModernObjC::HandleTranslationUnit().
3106Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3107 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3108 IdentifierInfo *ID = &Context->Idents.get(Name);
3109 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3110 SourceLocation(), ID, getProtocolType(), 0,
3111 SC_Extern, SC_None);
3112 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3113 SourceLocation());
3114 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3115 Context->getPointerType(DRE->getType()),
3116 VK_RValue, OK_Ordinary, SourceLocation());
3117 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3118 CK_BitCast,
3119 DerefExpr);
3120 ReplaceStmt(Exp, castExpr);
3121 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3122 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3123 return castExpr;
3124
3125}
3126
3127bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3128 const char *endBuf) {
3129 while (startBuf < endBuf) {
3130 if (*startBuf == '#') {
3131 // Skip whitespace.
3132 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3133 ;
3134 if (!strncmp(startBuf, "if", strlen("if")) ||
3135 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3136 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3137 !strncmp(startBuf, "define", strlen("define")) ||
3138 !strncmp(startBuf, "undef", strlen("undef")) ||
3139 !strncmp(startBuf, "else", strlen("else")) ||
3140 !strncmp(startBuf, "elif", strlen("elif")) ||
3141 !strncmp(startBuf, "endif", strlen("endif")) ||
3142 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3143 !strncmp(startBuf, "include", strlen("include")) ||
3144 !strncmp(startBuf, "import", strlen("import")) ||
3145 !strncmp(startBuf, "include_next", strlen("include_next")))
3146 return true;
3147 }
3148 startBuf++;
3149 }
3150 return false;
3151}
3152
3153/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3154/// an objective-c class with ivars.
3155void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3156 std::string &Result) {
3157 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3158 assert(CDecl->getName() != "" &&
3159 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003160 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003161 SmallVector<ObjCIvarDecl *, 8> IVars;
3162 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3163 IVD; IVD = IVD->getNextIvar()) {
3164 // Ignore unnamed bit-fields.
3165 if (!IVD->getDeclName())
3166 continue;
3167 IVars.push_back(IVD);
3168 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003169 SourceLocation LocStart = CDecl->getLocStart();
3170 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003171
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172 const char *startBuf = SM->getCharacterData(LocStart);
3173 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003174
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003175 // If no ivars and no root or if its root, directly or indirectly,
3176 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003177 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003178 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3179 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3180 ReplaceText(LocStart, endBuf-startBuf, Result);
3181 return;
3182 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003183
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003184 Result += "\nstruct ";
3185 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003186 Result += "_IMPL {\n";
3187
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003188 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003189 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3190 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3191 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003192 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003193
3194 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3195 ObjCIvarDecl *IvarDecl = IVars[i];
3196 QualType Type = IvarDecl->getType();
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003197 std::string Name = IvarDecl->getNameAsString();
3198
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003199 Result += "\t";
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003200 convertObjCTypeToCStyleType(Type);
3201
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003202 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3203 Result += Name;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003204 if (IvarDecl->isBitField()) {
3205 Result += " : "; Result += utostr(IvarDecl->getBitWidthValue(*Context));
3206 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003207 Result += ";\n";
3208 }
3209 Result += "};\n";
3210 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3211 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003212 // Mark this struct as having been generated.
3213 if (!ObjCSynthesizedStructs.insert(CDecl))
3214 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003215}
3216
3217//===----------------------------------------------------------------------===//
3218// Meta Data Emission
3219//===----------------------------------------------------------------------===//
3220
3221
3222/// RewriteImplementations - This routine rewrites all method implementations
3223/// and emits meta-data.
3224
3225void RewriteModernObjC::RewriteImplementations() {
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003226
3227 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
3228 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
3229 // Write struct declaration for the class matching its ivar declarations.
3230 // Note that for modern abi, this is postponed until the end of TU
3231 // because class extensions and the implementation might declare their own
3232 // private ivars.
3233 RewriteInterfaceDecl(CDecl);
3234 }
3235
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003236 int ClsDefCount = ClassImplementation.size();
3237 int CatDefCount = CategoryImplementation.size();
3238
3239 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003240 for (int i = 0; i < ClsDefCount; i++) {
3241 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3242 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3243 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003244 assert(false &&
3245 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003246 RewriteImplementationDecl(OIMP);
3247 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003248
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003249 for (int i = 0; i < CatDefCount; i++) {
3250 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3251 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3252 if (CDecl->isImplicitInterfaceDecl())
3253 assert(false &&
3254 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003255 RewriteImplementationDecl(CIMP);
3256 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003257}
3258
3259void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3260 const std::string &Name,
3261 ValueDecl *VD, bool def) {
3262 assert(BlockByRefDeclNo.count(VD) &&
3263 "RewriteByRefString: ByRef decl missing");
3264 if (def)
3265 ResultStr += "struct ";
3266 ResultStr += "__Block_byref_" + Name +
3267 "_" + utostr(BlockByRefDeclNo[VD]) ;
3268}
3269
3270static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3271 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3272 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3273 return false;
3274}
3275
3276std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3277 StringRef funcName,
3278 std::string Tag) {
3279 const FunctionType *AFT = CE->getFunctionType();
3280 QualType RT = AFT->getResultType();
3281 std::string StructRef = "struct " + Tag;
3282 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3283 funcName.str() + "_" + "block_func_" + utostr(i);
3284
3285 BlockDecl *BD = CE->getBlockDecl();
3286
3287 if (isa<FunctionNoProtoType>(AFT)) {
3288 // No user-supplied arguments. Still need to pass in a pointer to the
3289 // block (to reference imported block decl refs).
3290 S += "(" + StructRef + " *__cself)";
3291 } else if (BD->param_empty()) {
3292 S += "(" + StructRef + " *__cself)";
3293 } else {
3294 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3295 assert(FT && "SynthesizeBlockFunc: No function proto");
3296 S += '(';
3297 // first add the implicit argument.
3298 S += StructRef + " *__cself, ";
3299 std::string ParamStr;
3300 for (BlockDecl::param_iterator AI = BD->param_begin(),
3301 E = BD->param_end(); AI != E; ++AI) {
3302 if (AI != BD->param_begin()) S += ", ";
3303 ParamStr = (*AI)->getNameAsString();
3304 QualType QT = (*AI)->getType();
3305 if (convertBlockPointerToFunctionPointer(QT))
3306 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3307 else
3308 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3309 S += ParamStr;
3310 }
3311 if (FT->isVariadic()) {
3312 if (!BD->param_empty()) S += ", ";
3313 S += "...";
3314 }
3315 S += ')';
3316 }
3317 S += " {\n";
3318
3319 // Create local declarations to avoid rewriting all closure decl ref exprs.
3320 // First, emit a declaration for all "by ref" decls.
3321 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3322 E = BlockByRefDecls.end(); I != E; ++I) {
3323 S += " ";
3324 std::string Name = (*I)->getNameAsString();
3325 std::string TypeString;
3326 RewriteByRefString(TypeString, Name, (*I));
3327 TypeString += " *";
3328 Name = TypeString + Name;
3329 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3330 }
3331 // Next, emit a declaration for all "by copy" declarations.
3332 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3333 E = BlockByCopyDecls.end(); I != E; ++I) {
3334 S += " ";
3335 // Handle nested closure invocation. For example:
3336 //
3337 // void (^myImportedClosure)(void);
3338 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3339 //
3340 // void (^anotherClosure)(void);
3341 // anotherClosure = ^(void) {
3342 // myImportedClosure(); // import and invoke the closure
3343 // };
3344 //
3345 if (isTopLevelBlockPointerType((*I)->getType())) {
3346 RewriteBlockPointerTypeVariable(S, (*I));
3347 S += " = (";
3348 RewriteBlockPointerType(S, (*I)->getType());
3349 S += ")";
3350 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3351 }
3352 else {
3353 std::string Name = (*I)->getNameAsString();
3354 QualType QT = (*I)->getType();
3355 if (HasLocalVariableExternalStorage(*I))
3356 QT = Context->getPointerType(QT);
3357 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3358 S += Name + " = __cself->" +
3359 (*I)->getNameAsString() + "; // bound by copy\n";
3360 }
3361 }
3362 std::string RewrittenStr = RewrittenBlockExprs[CE];
3363 const char *cstr = RewrittenStr.c_str();
3364 while (*cstr++ != '{') ;
3365 S += cstr;
3366 S += "\n";
3367 return S;
3368}
3369
3370std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3371 StringRef funcName,
3372 std::string Tag) {
3373 std::string StructRef = "struct " + Tag;
3374 std::string S = "static void __";
3375
3376 S += funcName;
3377 S += "_block_copy_" + utostr(i);
3378 S += "(" + StructRef;
3379 S += "*dst, " + StructRef;
3380 S += "*src) {";
3381 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3382 E = ImportedBlockDecls.end(); I != E; ++I) {
3383 ValueDecl *VD = (*I);
3384 S += "_Block_object_assign((void*)&dst->";
3385 S += (*I)->getNameAsString();
3386 S += ", (void*)src->";
3387 S += (*I)->getNameAsString();
3388 if (BlockByRefDeclsPtrSet.count((*I)))
3389 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3390 else if (VD->getType()->isBlockPointerType())
3391 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3392 else
3393 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3394 }
3395 S += "}\n";
3396
3397 S += "\nstatic void __";
3398 S += funcName;
3399 S += "_block_dispose_" + utostr(i);
3400 S += "(" + StructRef;
3401 S += "*src) {";
3402 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3403 E = ImportedBlockDecls.end(); I != E; ++I) {
3404 ValueDecl *VD = (*I);
3405 S += "_Block_object_dispose((void*)src->";
3406 S += (*I)->getNameAsString();
3407 if (BlockByRefDeclsPtrSet.count((*I)))
3408 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3409 else if (VD->getType()->isBlockPointerType())
3410 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3411 else
3412 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3413 }
3414 S += "}\n";
3415 return S;
3416}
3417
3418std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3419 std::string Desc) {
3420 std::string S = "\nstruct " + Tag;
3421 std::string Constructor = " " + Tag;
3422
3423 S += " {\n struct __block_impl impl;\n";
3424 S += " struct " + Desc;
3425 S += "* Desc;\n";
3426
3427 Constructor += "(void *fp, "; // Invoke function pointer.
3428 Constructor += "struct " + Desc; // Descriptor pointer.
3429 Constructor += " *desc";
3430
3431 if (BlockDeclRefs.size()) {
3432 // Output all "by copy" declarations.
3433 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3434 E = BlockByCopyDecls.end(); I != E; ++I) {
3435 S += " ";
3436 std::string FieldName = (*I)->getNameAsString();
3437 std::string ArgName = "_" + FieldName;
3438 // Handle nested closure invocation. For example:
3439 //
3440 // void (^myImportedBlock)(void);
3441 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3442 //
3443 // void (^anotherBlock)(void);
3444 // anotherBlock = ^(void) {
3445 // myImportedBlock(); // import and invoke the closure
3446 // };
3447 //
3448 if (isTopLevelBlockPointerType((*I)->getType())) {
3449 S += "struct __block_impl *";
3450 Constructor += ", void *" + ArgName;
3451 } else {
3452 QualType QT = (*I)->getType();
3453 if (HasLocalVariableExternalStorage(*I))
3454 QT = Context->getPointerType(QT);
3455 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3456 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3457 Constructor += ", " + ArgName;
3458 }
3459 S += FieldName + ";\n";
3460 }
3461 // Output all "by ref" declarations.
3462 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3463 E = BlockByRefDecls.end(); I != E; ++I) {
3464 S += " ";
3465 std::string FieldName = (*I)->getNameAsString();
3466 std::string ArgName = "_" + FieldName;
3467 {
3468 std::string TypeString;
3469 RewriteByRefString(TypeString, FieldName, (*I));
3470 TypeString += " *";
3471 FieldName = TypeString + FieldName;
3472 ArgName = TypeString + ArgName;
3473 Constructor += ", " + ArgName;
3474 }
3475 S += FieldName + "; // by ref\n";
3476 }
3477 // Finish writing the constructor.
3478 Constructor += ", int flags=0)";
3479 // Initialize all "by copy" arguments.
3480 bool firsTime = true;
3481 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3482 E = BlockByCopyDecls.end(); I != E; ++I) {
3483 std::string Name = (*I)->getNameAsString();
3484 if (firsTime) {
3485 Constructor += " : ";
3486 firsTime = false;
3487 }
3488 else
3489 Constructor += ", ";
3490 if (isTopLevelBlockPointerType((*I)->getType()))
3491 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3492 else
3493 Constructor += Name + "(_" + Name + ")";
3494 }
3495 // Initialize all "by ref" arguments.
3496 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3497 E = BlockByRefDecls.end(); I != E; ++I) {
3498 std::string Name = (*I)->getNameAsString();
3499 if (firsTime) {
3500 Constructor += " : ";
3501 firsTime = false;
3502 }
3503 else
3504 Constructor += ", ";
3505 Constructor += Name + "(_" + Name + "->__forwarding)";
3506 }
3507
3508 Constructor += " {\n";
3509 if (GlobalVarDecl)
3510 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3511 else
3512 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3513 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3514
3515 Constructor += " Desc = desc;\n";
3516 } else {
3517 // Finish writing the constructor.
3518 Constructor += ", int flags=0) {\n";
3519 if (GlobalVarDecl)
3520 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3521 else
3522 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3523 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3524 Constructor += " Desc = desc;\n";
3525 }
3526 Constructor += " ";
3527 Constructor += "}\n";
3528 S += Constructor;
3529 S += "};\n";
3530 return S;
3531}
3532
3533std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3534 std::string ImplTag, int i,
3535 StringRef FunName,
3536 unsigned hasCopy) {
3537 std::string S = "\nstatic struct " + DescTag;
3538
3539 S += " {\n unsigned long reserved;\n";
3540 S += " unsigned long Block_size;\n";
3541 if (hasCopy) {
3542 S += " void (*copy)(struct ";
3543 S += ImplTag; S += "*, struct ";
3544 S += ImplTag; S += "*);\n";
3545
3546 S += " void (*dispose)(struct ";
3547 S += ImplTag; S += "*);\n";
3548 }
3549 S += "} ";
3550
3551 S += DescTag + "_DATA = { 0, sizeof(struct ";
3552 S += ImplTag + ")";
3553 if (hasCopy) {
3554 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3555 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3556 }
3557 S += "};\n";
3558 return S;
3559}
3560
3561void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3562 StringRef FunName) {
3563 // Insert declaration for the function in which block literal is used.
3564 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3565 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3566 bool RewriteSC = (GlobalVarDecl &&
3567 !Blocks.empty() &&
3568 GlobalVarDecl->getStorageClass() == SC_Static &&
3569 GlobalVarDecl->getType().getCVRQualifiers());
3570 if (RewriteSC) {
3571 std::string SC(" void __");
3572 SC += GlobalVarDecl->getNameAsString();
3573 SC += "() {}";
3574 InsertText(FunLocStart, SC);
3575 }
3576
3577 // Insert closures that were part of the function.
3578 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3579 CollectBlockDeclRefInfo(Blocks[i]);
3580 // Need to copy-in the inner copied-in variables not actually used in this
3581 // block.
3582 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3583 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3584 ValueDecl *VD = Exp->getDecl();
3585 BlockDeclRefs.push_back(Exp);
3586 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3587 BlockByCopyDeclsPtrSet.insert(VD);
3588 BlockByCopyDecls.push_back(VD);
3589 }
3590 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3591 BlockByRefDeclsPtrSet.insert(VD);
3592 BlockByRefDecls.push_back(VD);
3593 }
3594 // imported objects in the inner blocks not used in the outer
3595 // blocks must be copied/disposed in the outer block as well.
3596 if (Exp->isByRef() ||
3597 VD->getType()->isObjCObjectPointerType() ||
3598 VD->getType()->isBlockPointerType())
3599 ImportedBlockDecls.insert(VD);
3600 }
3601
3602 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3603 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3604
3605 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3606
3607 InsertText(FunLocStart, CI);
3608
3609 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3610
3611 InsertText(FunLocStart, CF);
3612
3613 if (ImportedBlockDecls.size()) {
3614 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3615 InsertText(FunLocStart, HF);
3616 }
3617 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3618 ImportedBlockDecls.size() > 0);
3619 InsertText(FunLocStart, BD);
3620
3621 BlockDeclRefs.clear();
3622 BlockByRefDecls.clear();
3623 BlockByRefDeclsPtrSet.clear();
3624 BlockByCopyDecls.clear();
3625 BlockByCopyDeclsPtrSet.clear();
3626 ImportedBlockDecls.clear();
3627 }
3628 if (RewriteSC) {
3629 // Must insert any 'const/volatile/static here. Since it has been
3630 // removed as result of rewriting of block literals.
3631 std::string SC;
3632 if (GlobalVarDecl->getStorageClass() == SC_Static)
3633 SC = "static ";
3634 if (GlobalVarDecl->getType().isConstQualified())
3635 SC += "const ";
3636 if (GlobalVarDecl->getType().isVolatileQualified())
3637 SC += "volatile ";
3638 if (GlobalVarDecl->getType().isRestrictQualified())
3639 SC += "restrict ";
3640 InsertText(FunLocStart, SC);
3641 }
3642
3643 Blocks.clear();
3644 InnerDeclRefsCount.clear();
3645 InnerDeclRefs.clear();
3646 RewrittenBlockExprs.clear();
3647}
3648
3649void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3650 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3651 StringRef FuncName = FD->getName();
3652
3653 SynthesizeBlockLiterals(FunLocStart, FuncName);
3654}
3655
3656static void BuildUniqueMethodName(std::string &Name,
3657 ObjCMethodDecl *MD) {
3658 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3659 Name = IFace->getName();
3660 Name += "__" + MD->getSelector().getAsString();
3661 // Convert colons to underscores.
3662 std::string::size_type loc = 0;
3663 while ((loc = Name.find(":", loc)) != std::string::npos)
3664 Name.replace(loc, 1, "_");
3665}
3666
3667void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3668 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3669 //SourceLocation FunLocStart = MD->getLocStart();
3670 SourceLocation FunLocStart = MD->getLocStart();
3671 std::string FuncName;
3672 BuildUniqueMethodName(FuncName, MD);
3673 SynthesizeBlockLiterals(FunLocStart, FuncName);
3674}
3675
3676void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3677 for (Stmt::child_range CI = S->children(); CI; ++CI)
3678 if (*CI) {
3679 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3680 GetBlockDeclRefExprs(CBE->getBody());
3681 else
3682 GetBlockDeclRefExprs(*CI);
3683 }
3684 // Handle specific things.
3685 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3686 // FIXME: Handle enums.
3687 if (!isa<FunctionDecl>(CDRE->getDecl()))
3688 BlockDeclRefs.push_back(CDRE);
3689 }
3690 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3691 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3692 BlockDeclRefExpr *BDRE =
3693 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3694 DRE->getType(),
3695 VK_LValue, DRE->getLocation(), false);
3696 BlockDeclRefs.push_back(BDRE);
3697 }
3698
3699 return;
3700}
3701
3702void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3703 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3704 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3705 for (Stmt::child_range CI = S->children(); CI; ++CI)
3706 if (*CI) {
3707 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3708 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3709 GetInnerBlockDeclRefExprs(CBE->getBody(),
3710 InnerBlockDeclRefs,
3711 InnerContexts);
3712 }
3713 else
3714 GetInnerBlockDeclRefExprs(*CI,
3715 InnerBlockDeclRefs,
3716 InnerContexts);
3717
3718 }
3719 // Handle specific things.
3720 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3721 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3722 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3723 InnerBlockDeclRefs.push_back(CDRE);
3724 }
3725 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3726 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3727 if (Var->isFunctionOrMethodVarDecl())
3728 ImportedLocalExternalDecls.insert(Var);
3729 }
3730
3731 return;
3732}
3733
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003734/// convertObjCTypeToCStyleType - This routine converts such objc types
3735/// as qualified objects, and blocks to their closest c/c++ types that
3736/// it can. It returns true if input type was modified.
3737bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3738 QualType oldT = T;
3739 convertBlockPointerToFunctionPointer(T);
3740 if (T->isFunctionPointerType()) {
3741 QualType PointeeTy;
3742 if (const PointerType* PT = T->getAs<PointerType>()) {
3743 PointeeTy = PT->getPointeeType();
3744 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3745 T = convertFunctionTypeOfBlocks(FT);
3746 T = Context->getPointerType(T);
3747 }
3748 }
3749 }
3750
3751 convertToUnqualifiedObjCType(T);
3752 return T != oldT;
3753}
3754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003755/// convertFunctionTypeOfBlocks - This routine converts a function type
3756/// whose result type may be a block pointer or whose argument type(s)
3757/// might be block pointers to an equivalent function type replacing
3758/// all block pointers to function pointers.
3759QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3760 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3761 // FTP will be null for closures that don't take arguments.
3762 // Generate a funky cast.
3763 SmallVector<QualType, 8> ArgTypes;
3764 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003765 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003766
3767 if (FTP) {
3768 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3769 E = FTP->arg_type_end(); I && (I != E); ++I) {
3770 QualType t = *I;
3771 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003772 if (convertObjCTypeToCStyleType(t))
3773 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003774 ArgTypes.push_back(t);
3775 }
3776 }
3777 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003778 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003779 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3780 else FuncType = QualType(FT, 0);
3781 return FuncType;
3782}
3783
3784Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3785 // Navigate to relevant type information.
3786 const BlockPointerType *CPT = 0;
3787
3788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3789 CPT = DRE->getType()->getAs<BlockPointerType>();
3790 } else if (const BlockDeclRefExpr *CDRE =
3791 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3792 CPT = CDRE->getType()->getAs<BlockPointerType>();
3793 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3794 CPT = MExpr->getType()->getAs<BlockPointerType>();
3795 }
3796 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3797 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3798 }
3799 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3800 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3801 else if (const ConditionalOperator *CEXPR =
3802 dyn_cast<ConditionalOperator>(BlockExp)) {
3803 Expr *LHSExp = CEXPR->getLHS();
3804 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3805 Expr *RHSExp = CEXPR->getRHS();
3806 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3807 Expr *CONDExp = CEXPR->getCond();
3808 ConditionalOperator *CondExpr =
3809 new (Context) ConditionalOperator(CONDExp,
3810 SourceLocation(), cast<Expr>(LHSStmt),
3811 SourceLocation(), cast<Expr>(RHSStmt),
3812 Exp->getType(), VK_RValue, OK_Ordinary);
3813 return CondExpr;
3814 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3815 CPT = IRE->getType()->getAs<BlockPointerType>();
3816 } else if (const PseudoObjectExpr *POE
3817 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3818 CPT = POE->getType()->castAs<BlockPointerType>();
3819 } else {
3820 assert(1 && "RewriteBlockClass: Bad type");
3821 }
3822 assert(CPT && "RewriteBlockClass: Bad type");
3823 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3824 assert(FT && "RewriteBlockClass: Bad type");
3825 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3826 // FTP will be null for closures that don't take arguments.
3827
3828 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3829 SourceLocation(), SourceLocation(),
3830 &Context->Idents.get("__block_impl"));
3831 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3832
3833 // Generate a funky cast.
3834 SmallVector<QualType, 8> ArgTypes;
3835
3836 // Push the block argument type.
3837 ArgTypes.push_back(PtrBlock);
3838 if (FTP) {
3839 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3840 E = FTP->arg_type_end(); I && (I != E); ++I) {
3841 QualType t = *I;
3842 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3843 if (!convertBlockPointerToFunctionPointer(t))
3844 convertToUnqualifiedObjCType(t);
3845 ArgTypes.push_back(t);
3846 }
3847 }
3848 // Now do the pointer to function cast.
3849 QualType PtrToFuncCastType
3850 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3851
3852 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3853
3854 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3855 CK_BitCast,
3856 const_cast<Expr*>(BlockExp));
3857 // Don't forget the parens to enforce the proper binding.
3858 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3859 BlkCast);
3860 //PE->dump();
3861
3862 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3863 SourceLocation(),
3864 &Context->Idents.get("FuncPtr"),
3865 Context->VoidPtrTy, 0,
3866 /*BitWidth=*/0, /*Mutable=*/true,
3867 /*HasInit=*/false);
3868 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3869 FD->getType(), VK_LValue,
3870 OK_Ordinary);
3871
3872
3873 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3874 CK_BitCast, ME);
3875 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3876
3877 SmallVector<Expr*, 8> BlkExprs;
3878 // Add the implicit argument.
3879 BlkExprs.push_back(BlkCast);
3880 // Add the user arguments.
3881 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3882 E = Exp->arg_end(); I != E; ++I) {
3883 BlkExprs.push_back(*I);
3884 }
3885 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3886 BlkExprs.size(),
3887 Exp->getType(), VK_RValue,
3888 SourceLocation());
3889 return CE;
3890}
3891
3892// We need to return the rewritten expression to handle cases where the
3893// BlockDeclRefExpr is embedded in another expression being rewritten.
3894// For example:
3895//
3896// int main() {
3897// __block Foo *f;
3898// __block int i;
3899//
3900// void (^myblock)() = ^() {
3901// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3902// i = 77;
3903// };
3904//}
3905Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3906 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3907 // for each DeclRefExp where BYREFVAR is name of the variable.
3908 ValueDecl *VD;
3909 bool isArrow = true;
3910 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3911 VD = BDRE->getDecl();
3912 else {
3913 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3914 isArrow = false;
3915 }
3916
3917 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3918 SourceLocation(),
3919 &Context->Idents.get("__forwarding"),
3920 Context->VoidPtrTy, 0,
3921 /*BitWidth=*/0, /*Mutable=*/true,
3922 /*HasInit=*/false);
3923 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3924 FD, SourceLocation(),
3925 FD->getType(), VK_LValue,
3926 OK_Ordinary);
3927
3928 StringRef Name = VD->getName();
3929 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3930 &Context->Idents.get(Name),
3931 Context->VoidPtrTy, 0,
3932 /*BitWidth=*/0, /*Mutable=*/true,
3933 /*HasInit=*/false);
3934 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3935 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3936
3937
3938
3939 // Need parens to enforce precedence.
3940 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3941 DeclRefExp->getExprLoc(),
3942 ME);
3943 ReplaceStmt(DeclRefExp, PE);
3944 return PE;
3945}
3946
3947// Rewrites the imported local variable V with external storage
3948// (static, extern, etc.) as *V
3949//
3950Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3951 ValueDecl *VD = DRE->getDecl();
3952 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3953 if (!ImportedLocalExternalDecls.count(Var))
3954 return DRE;
3955 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3956 VK_LValue, OK_Ordinary,
3957 DRE->getLocation());
3958 // Need parens to enforce precedence.
3959 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3960 Exp);
3961 ReplaceStmt(DRE, PE);
3962 return PE;
3963}
3964
3965void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3966 SourceLocation LocStart = CE->getLParenLoc();
3967 SourceLocation LocEnd = CE->getRParenLoc();
3968
3969 // Need to avoid trying to rewrite synthesized casts.
3970 if (LocStart.isInvalid())
3971 return;
3972 // Need to avoid trying to rewrite casts contained in macros.
3973 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3974 return;
3975
3976 const char *startBuf = SM->getCharacterData(LocStart);
3977 const char *endBuf = SM->getCharacterData(LocEnd);
3978 QualType QT = CE->getType();
3979 const Type* TypePtr = QT->getAs<Type>();
3980 if (isa<TypeOfExprType>(TypePtr)) {
3981 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3982 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3983 std::string TypeAsString = "(";
3984 RewriteBlockPointerType(TypeAsString, QT);
3985 TypeAsString += ")";
3986 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3987 return;
3988 }
3989 // advance the location to startArgList.
3990 const char *argPtr = startBuf;
3991
3992 while (*argPtr++ && (argPtr < endBuf)) {
3993 switch (*argPtr) {
3994 case '^':
3995 // Replace the '^' with '*'.
3996 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3997 ReplaceText(LocStart, 1, "*");
3998 break;
3999 }
4000 }
4001 return;
4002}
4003
4004void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4005 SourceLocation DeclLoc = FD->getLocation();
4006 unsigned parenCount = 0;
4007
4008 // We have 1 or more arguments that have closure pointers.
4009 const char *startBuf = SM->getCharacterData(DeclLoc);
4010 const char *startArgList = strchr(startBuf, '(');
4011
4012 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4013
4014 parenCount++;
4015 // advance the location to startArgList.
4016 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4017 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4018
4019 const char *argPtr = startArgList;
4020
4021 while (*argPtr++ && parenCount) {
4022 switch (*argPtr) {
4023 case '^':
4024 // Replace the '^' with '*'.
4025 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4026 ReplaceText(DeclLoc, 1, "*");
4027 break;
4028 case '(':
4029 parenCount++;
4030 break;
4031 case ')':
4032 parenCount--;
4033 break;
4034 }
4035 }
4036 return;
4037}
4038
4039bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4040 const FunctionProtoType *FTP;
4041 const PointerType *PT = QT->getAs<PointerType>();
4042 if (PT) {
4043 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4044 } else {
4045 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4046 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4047 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4048 }
4049 if (FTP) {
4050 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4051 E = FTP->arg_type_end(); I != E; ++I)
4052 if (isTopLevelBlockPointerType(*I))
4053 return true;
4054 }
4055 return false;
4056}
4057
4058bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4059 const FunctionProtoType *FTP;
4060 const PointerType *PT = QT->getAs<PointerType>();
4061 if (PT) {
4062 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4063 } else {
4064 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4065 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4066 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4067 }
4068 if (FTP) {
4069 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4070 E = FTP->arg_type_end(); I != E; ++I) {
4071 if ((*I)->isObjCQualifiedIdType())
4072 return true;
4073 if ((*I)->isObjCObjectPointerType() &&
4074 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4075 return true;
4076 }
4077
4078 }
4079 return false;
4080}
4081
4082void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4083 const char *&RParen) {
4084 const char *argPtr = strchr(Name, '(');
4085 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4086
4087 LParen = argPtr; // output the start.
4088 argPtr++; // skip past the left paren.
4089 unsigned parenCount = 1;
4090
4091 while (*argPtr && parenCount) {
4092 switch (*argPtr) {
4093 case '(': parenCount++; break;
4094 case ')': parenCount--; break;
4095 default: break;
4096 }
4097 if (parenCount) argPtr++;
4098 }
4099 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4100 RParen = argPtr; // output the end
4101}
4102
4103void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4105 RewriteBlockPointerFunctionArgs(FD);
4106 return;
4107 }
4108 // Handle Variables and Typedefs.
4109 SourceLocation DeclLoc = ND->getLocation();
4110 QualType DeclT;
4111 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4112 DeclT = VD->getType();
4113 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4114 DeclT = TDD->getUnderlyingType();
4115 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4116 DeclT = FD->getType();
4117 else
4118 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4119
4120 const char *startBuf = SM->getCharacterData(DeclLoc);
4121 const char *endBuf = startBuf;
4122 // scan backward (from the decl location) for the end of the previous decl.
4123 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4124 startBuf--;
4125 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4126 std::string buf;
4127 unsigned OrigLength=0;
4128 // *startBuf != '^' if we are dealing with a pointer to function that
4129 // may take block argument types (which will be handled below).
4130 if (*startBuf == '^') {
4131 // Replace the '^' with '*', computing a negative offset.
4132 buf = '*';
4133 startBuf++;
4134 OrigLength++;
4135 }
4136 while (*startBuf != ')') {
4137 buf += *startBuf;
4138 startBuf++;
4139 OrigLength++;
4140 }
4141 buf += ')';
4142 OrigLength++;
4143
4144 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4145 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4146 // Replace the '^' with '*' for arguments.
4147 // Replace id<P> with id/*<>*/
4148 DeclLoc = ND->getLocation();
4149 startBuf = SM->getCharacterData(DeclLoc);
4150 const char *argListBegin, *argListEnd;
4151 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4152 while (argListBegin < argListEnd) {
4153 if (*argListBegin == '^')
4154 buf += '*';
4155 else if (*argListBegin == '<') {
4156 buf += "/*";
4157 buf += *argListBegin++;
4158 OrigLength++;;
4159 while (*argListBegin != '>') {
4160 buf += *argListBegin++;
4161 OrigLength++;
4162 }
4163 buf += *argListBegin;
4164 buf += "*/";
4165 }
4166 else
4167 buf += *argListBegin;
4168 argListBegin++;
4169 OrigLength++;
4170 }
4171 buf += ')';
4172 OrigLength++;
4173 }
4174 ReplaceText(Start, OrigLength, buf);
4175
4176 return;
4177}
4178
4179
4180/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4181/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4182/// struct Block_byref_id_object *src) {
4183/// _Block_object_assign (&_dest->object, _src->object,
4184/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4185/// [|BLOCK_FIELD_IS_WEAK]) // object
4186/// _Block_object_assign(&_dest->object, _src->object,
4187/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4188/// [|BLOCK_FIELD_IS_WEAK]) // block
4189/// }
4190/// And:
4191/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4192/// _Block_object_dispose(_src->object,
4193/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4194/// [|BLOCK_FIELD_IS_WEAK]) // object
4195/// _Block_object_dispose(_src->object,
4196/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4197/// [|BLOCK_FIELD_IS_WEAK]) // block
4198/// }
4199
4200std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4201 int flag) {
4202 std::string S;
4203 if (CopyDestroyCache.count(flag))
4204 return S;
4205 CopyDestroyCache.insert(flag);
4206 S = "static void __Block_byref_id_object_copy_";
4207 S += utostr(flag);
4208 S += "(void *dst, void *src) {\n";
4209
4210 // offset into the object pointer is computed as:
4211 // void * + void* + int + int + void* + void *
4212 unsigned IntSize =
4213 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4214 unsigned VoidPtrSize =
4215 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4216
4217 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4218 S += " _Block_object_assign((char*)dst + ";
4219 S += utostr(offset);
4220 S += ", *(void * *) ((char*)src + ";
4221 S += utostr(offset);
4222 S += "), ";
4223 S += utostr(flag);
4224 S += ");\n}\n";
4225
4226 S += "static void __Block_byref_id_object_dispose_";
4227 S += utostr(flag);
4228 S += "(void *src) {\n";
4229 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4230 S += utostr(offset);
4231 S += "), ";
4232 S += utostr(flag);
4233 S += ");\n}\n";
4234 return S;
4235}
4236
4237/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4238/// the declaration into:
4239/// struct __Block_byref_ND {
4240/// void *__isa; // NULL for everything except __weak pointers
4241/// struct __Block_byref_ND *__forwarding;
4242/// int32_t __flags;
4243/// int32_t __size;
4244/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4245/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4246/// typex ND;
4247/// };
4248///
4249/// It then replaces declaration of ND variable with:
4250/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4251/// __size=sizeof(struct __Block_byref_ND),
4252/// ND=initializer-if-any};
4253///
4254///
4255void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4256 // Insert declaration for the function in which block literal is
4257 // used.
4258 if (CurFunctionDeclToDeclareForBlock)
4259 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4260 int flag = 0;
4261 int isa = 0;
4262 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4263 if (DeclLoc.isInvalid())
4264 // If type location is missing, it is because of missing type (a warning).
4265 // Use variable's location which is good for this case.
4266 DeclLoc = ND->getLocation();
4267 const char *startBuf = SM->getCharacterData(DeclLoc);
4268 SourceLocation X = ND->getLocEnd();
4269 X = SM->getExpansionLoc(X);
4270 const char *endBuf = SM->getCharacterData(X);
4271 std::string Name(ND->getNameAsString());
4272 std::string ByrefType;
4273 RewriteByRefString(ByrefType, Name, ND, true);
4274 ByrefType += " {\n";
4275 ByrefType += " void *__isa;\n";
4276 RewriteByRefString(ByrefType, Name, ND);
4277 ByrefType += " *__forwarding;\n";
4278 ByrefType += " int __flags;\n";
4279 ByrefType += " int __size;\n";
4280 // Add void *__Block_byref_id_object_copy;
4281 // void *__Block_byref_id_object_dispose; if needed.
4282 QualType Ty = ND->getType();
4283 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4284 if (HasCopyAndDispose) {
4285 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4286 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4287 }
4288
4289 QualType T = Ty;
4290 (void)convertBlockPointerToFunctionPointer(T);
4291 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4292
4293 ByrefType += " " + Name + ";\n";
4294 ByrefType += "};\n";
4295 // Insert this type in global scope. It is needed by helper function.
4296 SourceLocation FunLocStart;
4297 if (CurFunctionDef)
4298 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4299 else {
4300 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4301 FunLocStart = CurMethodDef->getLocStart();
4302 }
4303 InsertText(FunLocStart, ByrefType);
4304 if (Ty.isObjCGCWeak()) {
4305 flag |= BLOCK_FIELD_IS_WEAK;
4306 isa = 1;
4307 }
4308
4309 if (HasCopyAndDispose) {
4310 flag = BLOCK_BYREF_CALLER;
4311 QualType Ty = ND->getType();
4312 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4313 if (Ty->isBlockPointerType())
4314 flag |= BLOCK_FIELD_IS_BLOCK;
4315 else
4316 flag |= BLOCK_FIELD_IS_OBJECT;
4317 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4318 if (!HF.empty())
4319 InsertText(FunLocStart, HF);
4320 }
4321
4322 // struct __Block_byref_ND ND =
4323 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4324 // initializer-if-any};
4325 bool hasInit = (ND->getInit() != 0);
4326 unsigned flags = 0;
4327 if (HasCopyAndDispose)
4328 flags |= BLOCK_HAS_COPY_DISPOSE;
4329 Name = ND->getNameAsString();
4330 ByrefType.clear();
4331 RewriteByRefString(ByrefType, Name, ND);
4332 std::string ForwardingCastType("(");
4333 ForwardingCastType += ByrefType + " *)";
4334 if (!hasInit) {
4335 ByrefType += " " + Name + " = {(void*)";
4336 ByrefType += utostr(isa);
4337 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4338 ByrefType += utostr(flags);
4339 ByrefType += ", ";
4340 ByrefType += "sizeof(";
4341 RewriteByRefString(ByrefType, Name, ND);
4342 ByrefType += ")";
4343 if (HasCopyAndDispose) {
4344 ByrefType += ", __Block_byref_id_object_copy_";
4345 ByrefType += utostr(flag);
4346 ByrefType += ", __Block_byref_id_object_dispose_";
4347 ByrefType += utostr(flag);
4348 }
4349 ByrefType += "};\n";
4350 unsigned nameSize = Name.size();
4351 // for block or function pointer declaration. Name is aleady
4352 // part of the declaration.
4353 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4354 nameSize = 1;
4355 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4356 }
4357 else {
4358 SourceLocation startLoc;
4359 Expr *E = ND->getInit();
4360 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4361 startLoc = ECE->getLParenLoc();
4362 else
4363 startLoc = E->getLocStart();
4364 startLoc = SM->getExpansionLoc(startLoc);
4365 endBuf = SM->getCharacterData(startLoc);
4366 ByrefType += " " + Name;
4367 ByrefType += " = {(void*)";
4368 ByrefType += utostr(isa);
4369 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4370 ByrefType += utostr(flags);
4371 ByrefType += ", ";
4372 ByrefType += "sizeof(";
4373 RewriteByRefString(ByrefType, Name, ND);
4374 ByrefType += "), ";
4375 if (HasCopyAndDispose) {
4376 ByrefType += "__Block_byref_id_object_copy_";
4377 ByrefType += utostr(flag);
4378 ByrefType += ", __Block_byref_id_object_dispose_";
4379 ByrefType += utostr(flag);
4380 ByrefType += ", ";
4381 }
4382 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4383
4384 // Complete the newly synthesized compound expression by inserting a right
4385 // curly brace before the end of the declaration.
4386 // FIXME: This approach avoids rewriting the initializer expression. It
4387 // also assumes there is only one declarator. For example, the following
4388 // isn't currently supported by this routine (in general):
4389 //
4390 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4391 //
4392 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4393 const char *semiBuf = strchr(startInitializerBuf, ';');
4394 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4395 SourceLocation semiLoc =
4396 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4397
4398 InsertText(semiLoc, "}");
4399 }
4400 return;
4401}
4402
4403void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4404 // Add initializers for any closure decl refs.
4405 GetBlockDeclRefExprs(Exp->getBody());
4406 if (BlockDeclRefs.size()) {
4407 // Unique all "by copy" declarations.
4408 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4409 if (!BlockDeclRefs[i]->isByRef()) {
4410 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4411 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4412 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4413 }
4414 }
4415 // Unique all "by ref" declarations.
4416 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4417 if (BlockDeclRefs[i]->isByRef()) {
4418 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4419 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4420 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4421 }
4422 }
4423 // Find any imported blocks...they will need special attention.
4424 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4425 if (BlockDeclRefs[i]->isByRef() ||
4426 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4427 BlockDeclRefs[i]->getType()->isBlockPointerType())
4428 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4429 }
4430}
4431
4432FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4433 IdentifierInfo *ID = &Context->Idents.get(name);
4434 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4435 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4436 SourceLocation(), ID, FType, 0, SC_Extern,
4437 SC_None, false, false);
4438}
4439
4440Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4441 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4442 const BlockDecl *block = Exp->getBlockDecl();
4443 Blocks.push_back(Exp);
4444
4445 CollectBlockDeclRefInfo(Exp);
4446
4447 // Add inner imported variables now used in current block.
4448 int countOfInnerDecls = 0;
4449 if (!InnerBlockDeclRefs.empty()) {
4450 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4451 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4452 ValueDecl *VD = Exp->getDecl();
4453 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4454 // We need to save the copied-in variables in nested
4455 // blocks because it is needed at the end for some of the API generations.
4456 // See SynthesizeBlockLiterals routine.
4457 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4458 BlockDeclRefs.push_back(Exp);
4459 BlockByCopyDeclsPtrSet.insert(VD);
4460 BlockByCopyDecls.push_back(VD);
4461 }
4462 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4463 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4464 BlockDeclRefs.push_back(Exp);
4465 BlockByRefDeclsPtrSet.insert(VD);
4466 BlockByRefDecls.push_back(VD);
4467 }
4468 }
4469 // Find any imported blocks...they will need special attention.
4470 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4471 if (InnerBlockDeclRefs[i]->isByRef() ||
4472 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4473 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4474 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4475 }
4476 InnerDeclRefsCount.push_back(countOfInnerDecls);
4477
4478 std::string FuncName;
4479
4480 if (CurFunctionDef)
4481 FuncName = CurFunctionDef->getNameAsString();
4482 else if (CurMethodDef)
4483 BuildUniqueMethodName(FuncName, CurMethodDef);
4484 else if (GlobalVarDecl)
4485 FuncName = std::string(GlobalVarDecl->getNameAsString());
4486
4487 std::string BlockNumber = utostr(Blocks.size()-1);
4488
4489 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4490 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4491
4492 // Get a pointer to the function type so we can cast appropriately.
4493 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4494 QualType FType = Context->getPointerType(BFT);
4495
4496 FunctionDecl *FD;
4497 Expr *NewRep;
4498
4499 // Simulate a contructor call...
4500 FD = SynthBlockInitFunctionDecl(Tag);
4501 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4502 SourceLocation());
4503
4504 SmallVector<Expr*, 4> InitExprs;
4505
4506 // Initialize the block function.
4507 FD = SynthBlockInitFunctionDecl(Func);
4508 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4509 SourceLocation());
4510 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4511 CK_BitCast, Arg);
4512 InitExprs.push_back(castExpr);
4513
4514 // Initialize the block descriptor.
4515 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4516
4517 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4518 SourceLocation(), SourceLocation(),
4519 &Context->Idents.get(DescData.c_str()),
4520 Context->VoidPtrTy, 0,
4521 SC_Static, SC_None);
4522 UnaryOperator *DescRefExpr =
4523 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4524 Context->VoidPtrTy,
4525 VK_LValue,
4526 SourceLocation()),
4527 UO_AddrOf,
4528 Context->getPointerType(Context->VoidPtrTy),
4529 VK_RValue, OK_Ordinary,
4530 SourceLocation());
4531 InitExprs.push_back(DescRefExpr);
4532
4533 // Add initializers for any closure decl refs.
4534 if (BlockDeclRefs.size()) {
4535 Expr *Exp;
4536 // Output all "by copy" declarations.
4537 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4538 E = BlockByCopyDecls.end(); I != E; ++I) {
4539 if (isObjCType((*I)->getType())) {
4540 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4541 FD = SynthBlockInitFunctionDecl((*I)->getName());
4542 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4543 SourceLocation());
4544 if (HasLocalVariableExternalStorage(*I)) {
4545 QualType QT = (*I)->getType();
4546 QT = Context->getPointerType(QT);
4547 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4548 OK_Ordinary, SourceLocation());
4549 }
4550 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4551 FD = SynthBlockInitFunctionDecl((*I)->getName());
4552 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4553 SourceLocation());
4554 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4555 CK_BitCast, Arg);
4556 } else {
4557 FD = SynthBlockInitFunctionDecl((*I)->getName());
4558 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4559 SourceLocation());
4560 if (HasLocalVariableExternalStorage(*I)) {
4561 QualType QT = (*I)->getType();
4562 QT = Context->getPointerType(QT);
4563 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4564 OK_Ordinary, SourceLocation());
4565 }
4566
4567 }
4568 InitExprs.push_back(Exp);
4569 }
4570 // Output all "by ref" declarations.
4571 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4572 E = BlockByRefDecls.end(); I != E; ++I) {
4573 ValueDecl *ND = (*I);
4574 std::string Name(ND->getNameAsString());
4575 std::string RecName;
4576 RewriteByRefString(RecName, Name, ND, true);
4577 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4578 + sizeof("struct"));
4579 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4580 SourceLocation(), SourceLocation(),
4581 II);
4582 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4583 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4584
4585 FD = SynthBlockInitFunctionDecl((*I)->getName());
4586 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4587 SourceLocation());
4588 bool isNestedCapturedVar = false;
4589 if (block)
4590 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4591 ce = block->capture_end(); ci != ce; ++ci) {
4592 const VarDecl *variable = ci->getVariable();
4593 if (variable == ND && ci->isNested()) {
4594 assert (ci->isByRef() &&
4595 "SynthBlockInitExpr - captured block variable is not byref");
4596 isNestedCapturedVar = true;
4597 break;
4598 }
4599 }
4600 // captured nested byref variable has its address passed. Do not take
4601 // its address again.
4602 if (!isNestedCapturedVar)
4603 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4604 Context->getPointerType(Exp->getType()),
4605 VK_RValue, OK_Ordinary, SourceLocation());
4606 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4607 InitExprs.push_back(Exp);
4608 }
4609 }
4610 if (ImportedBlockDecls.size()) {
4611 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4612 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4613 unsigned IntSize =
4614 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4615 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4616 Context->IntTy, SourceLocation());
4617 InitExprs.push_back(FlagExp);
4618 }
4619 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4620 FType, VK_LValue, SourceLocation());
4621 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4622 Context->getPointerType(NewRep->getType()),
4623 VK_RValue, OK_Ordinary, SourceLocation());
4624 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4625 NewRep);
4626 BlockDeclRefs.clear();
4627 BlockByRefDecls.clear();
4628 BlockByRefDeclsPtrSet.clear();
4629 BlockByCopyDecls.clear();
4630 BlockByCopyDeclsPtrSet.clear();
4631 ImportedBlockDecls.clear();
4632 return NewRep;
4633}
4634
4635bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4636 if (const ObjCForCollectionStmt * CS =
4637 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4638 return CS->getElement() == DS;
4639 return false;
4640}
4641
4642//===----------------------------------------------------------------------===//
4643// Function Body / Expression rewriting
4644//===----------------------------------------------------------------------===//
4645
4646Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4647 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4648 isa<DoStmt>(S) || isa<ForStmt>(S))
4649 Stmts.push_back(S);
4650 else if (isa<ObjCForCollectionStmt>(S)) {
4651 Stmts.push_back(S);
4652 ObjCBcLabelNo.push_back(++BcLabelCount);
4653 }
4654
4655 // Pseudo-object operations and ivar references need special
4656 // treatment because we're going to recursively rewrite them.
4657 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4658 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4659 return RewritePropertyOrImplicitSetter(PseudoOp);
4660 } else {
4661 return RewritePropertyOrImplicitGetter(PseudoOp);
4662 }
4663 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4664 return RewriteObjCIvarRefExpr(IvarRefExpr);
4665 }
4666
4667 SourceRange OrigStmtRange = S->getSourceRange();
4668
4669 // Perform a bottom up rewrite of all children.
4670 for (Stmt::child_range CI = S->children(); CI; ++CI)
4671 if (*CI) {
4672 Stmt *childStmt = (*CI);
4673 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4674 if (newStmt) {
4675 *CI = newStmt;
4676 }
4677 }
4678
4679 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4680 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4681 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4682 InnerContexts.insert(BE->getBlockDecl());
4683 ImportedLocalExternalDecls.clear();
4684 GetInnerBlockDeclRefExprs(BE->getBody(),
4685 InnerBlockDeclRefs, InnerContexts);
4686 // Rewrite the block body in place.
4687 Stmt *SaveCurrentBody = CurrentBody;
4688 CurrentBody = BE->getBody();
4689 PropParentMap = 0;
4690 // block literal on rhs of a property-dot-sytax assignment
4691 // must be replaced by its synthesize ast so getRewrittenText
4692 // works as expected. In this case, what actually ends up on RHS
4693 // is the blockTranscribed which is the helper function for the
4694 // block literal; as in: self.c = ^() {[ace ARR];};
4695 bool saveDisableReplaceStmt = DisableReplaceStmt;
4696 DisableReplaceStmt = false;
4697 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4698 DisableReplaceStmt = saveDisableReplaceStmt;
4699 CurrentBody = SaveCurrentBody;
4700 PropParentMap = 0;
4701 ImportedLocalExternalDecls.clear();
4702 // Now we snarf the rewritten text and stash it away for later use.
4703 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4704 RewrittenBlockExprs[BE] = Str;
4705
4706 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4707
4708 //blockTranscribed->dump();
4709 ReplaceStmt(S, blockTranscribed);
4710 return blockTranscribed;
4711 }
4712 // Handle specific things.
4713 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4714 return RewriteAtEncode(AtEncode);
4715
4716 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4717 return RewriteAtSelector(AtSelector);
4718
4719 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4720 return RewriteObjCStringLiteral(AtString);
4721
4722 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4723#if 0
4724 // Before we rewrite it, put the original message expression in a comment.
4725 SourceLocation startLoc = MessExpr->getLocStart();
4726 SourceLocation endLoc = MessExpr->getLocEnd();
4727
4728 const char *startBuf = SM->getCharacterData(startLoc);
4729 const char *endBuf = SM->getCharacterData(endLoc);
4730
4731 std::string messString;
4732 messString += "// ";
4733 messString.append(startBuf, endBuf-startBuf+1);
4734 messString += "\n";
4735
4736 // FIXME: Missing definition of
4737 // InsertText(clang::SourceLocation, char const*, unsigned int).
4738 // InsertText(startLoc, messString.c_str(), messString.size());
4739 // Tried this, but it didn't work either...
4740 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4741#endif
4742 return RewriteMessageExpr(MessExpr);
4743 }
4744
4745 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4746 return RewriteObjCTryStmt(StmtTry);
4747
4748 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4749 return RewriteObjCSynchronizedStmt(StmtTry);
4750
4751 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4752 return RewriteObjCThrowStmt(StmtThrow);
4753
4754 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4755 return RewriteObjCProtocolExpr(ProtocolExp);
4756
4757 if (ObjCForCollectionStmt *StmtForCollection =
4758 dyn_cast<ObjCForCollectionStmt>(S))
4759 return RewriteObjCForCollectionStmt(StmtForCollection,
4760 OrigStmtRange.getEnd());
4761 if (BreakStmt *StmtBreakStmt =
4762 dyn_cast<BreakStmt>(S))
4763 return RewriteBreakStmt(StmtBreakStmt);
4764 if (ContinueStmt *StmtContinueStmt =
4765 dyn_cast<ContinueStmt>(S))
4766 return RewriteContinueStmt(StmtContinueStmt);
4767
4768 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4769 // and cast exprs.
4770 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4771 // FIXME: What we're doing here is modifying the type-specifier that
4772 // precedes the first Decl. In the future the DeclGroup should have
4773 // a separate type-specifier that we can rewrite.
4774 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4775 // the context of an ObjCForCollectionStmt. For example:
4776 // NSArray *someArray;
4777 // for (id <FooProtocol> index in someArray) ;
4778 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4779 // and it depends on the original text locations/positions.
4780 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4781 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4782
4783 // Blocks rewrite rules.
4784 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4785 DI != DE; ++DI) {
4786 Decl *SD = *DI;
4787 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4788 if (isTopLevelBlockPointerType(ND->getType()))
4789 RewriteBlockPointerDecl(ND);
4790 else if (ND->getType()->isFunctionPointerType())
4791 CheckFunctionPointerDecl(ND->getType(), ND);
4792 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4793 if (VD->hasAttr<BlocksAttr>()) {
4794 static unsigned uniqueByrefDeclCount = 0;
4795 assert(!BlockByRefDeclNo.count(ND) &&
4796 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4797 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4798 RewriteByRefVar(VD);
4799 }
4800 else
4801 RewriteTypeOfDecl(VD);
4802 }
4803 }
4804 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4805 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4806 RewriteBlockPointerDecl(TD);
4807 else if (TD->getUnderlyingType()->isFunctionPointerType())
4808 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4809 }
4810 }
4811 }
4812
4813 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4814 RewriteObjCQualifiedInterfaceTypes(CE);
4815
4816 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4817 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4818 assert(!Stmts.empty() && "Statement stack is empty");
4819 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4820 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4821 && "Statement stack mismatch");
4822 Stmts.pop_back();
4823 }
4824 // Handle blocks rewriting.
4825 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4826 if (BDRE->isByRef())
4827 return RewriteBlockDeclRefExpr(BDRE);
4828 }
4829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4830 ValueDecl *VD = DRE->getDecl();
4831 if (VD->hasAttr<BlocksAttr>())
4832 return RewriteBlockDeclRefExpr(DRE);
4833 if (HasLocalVariableExternalStorage(VD))
4834 return RewriteLocalVariableExternalStorage(DRE);
4835 }
4836
4837 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4838 if (CE->getCallee()->getType()->isBlockPointerType()) {
4839 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4840 ReplaceStmt(S, BlockCall);
4841 return BlockCall;
4842 }
4843 }
4844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4845 RewriteCastExpr(CE);
4846 }
4847#if 0
4848 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4849 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4850 ICE->getSubExpr(),
4851 SourceLocation());
4852 // Get the new text.
4853 std::string SStr;
4854 llvm::raw_string_ostream Buf(SStr);
4855 Replacement->printPretty(Buf, *Context);
4856 const std::string &Str = Buf.str();
4857
4858 printf("CAST = %s\n", &Str[0]);
4859 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4860 delete S;
4861 return Replacement;
4862 }
4863#endif
4864 // Return this stmt unmodified.
4865 return S;
4866}
4867
4868void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4869 for (RecordDecl::field_iterator i = RD->field_begin(),
4870 e = RD->field_end(); i != e; ++i) {
4871 FieldDecl *FD = *i;
4872 if (isTopLevelBlockPointerType(FD->getType()))
4873 RewriteBlockPointerDecl(FD);
4874 if (FD->getType()->isObjCQualifiedIdType() ||
4875 FD->getType()->isObjCQualifiedInterfaceType())
4876 RewriteObjCQualifiedInterfaceTypes(FD);
4877 }
4878}
4879
4880/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4881/// main file of the input.
4882void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4883 switch (D->getKind()) {
4884 case Decl::Function: {
4885 FunctionDecl *FD = cast<FunctionDecl>(D);
4886 if (FD->isOverloadedOperator())
4887 return;
4888
4889 // Since function prototypes don't have ParmDecl's, we check the function
4890 // prototype. This enables us to rewrite function declarations and
4891 // definitions using the same code.
4892 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4893
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004894 if (!FD->isThisDeclarationADefinition())
4895 break;
4896
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004897 // FIXME: If this should support Obj-C++, support CXXTryStmt
4898 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4899 CurFunctionDef = FD;
4900 CurFunctionDeclToDeclareForBlock = FD;
4901 CurrentBody = Body;
4902 Body =
4903 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4904 FD->setBody(Body);
4905 CurrentBody = 0;
4906 if (PropParentMap) {
4907 delete PropParentMap;
4908 PropParentMap = 0;
4909 }
4910 // This synthesizes and inserts the block "impl" struct, invoke function,
4911 // and any copy/dispose helper functions.
4912 InsertBlockLiteralsWithinFunction(FD);
4913 CurFunctionDef = 0;
4914 CurFunctionDeclToDeclareForBlock = 0;
4915 }
4916 break;
4917 }
4918 case Decl::ObjCMethod: {
4919 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4920 if (CompoundStmt *Body = MD->getCompoundBody()) {
4921 CurMethodDef = MD;
4922 CurrentBody = Body;
4923 Body =
4924 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4925 MD->setBody(Body);
4926 CurrentBody = 0;
4927 if (PropParentMap) {
4928 delete PropParentMap;
4929 PropParentMap = 0;
4930 }
4931 InsertBlockLiteralsWithinMethod(MD);
4932 CurMethodDef = 0;
4933 }
4934 break;
4935 }
4936 case Decl::ObjCImplementation: {
4937 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4938 ClassImplementation.push_back(CI);
4939 break;
4940 }
4941 case Decl::ObjCCategoryImpl: {
4942 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4943 CategoryImplementation.push_back(CI);
4944 break;
4945 }
4946 case Decl::Var: {
4947 VarDecl *VD = cast<VarDecl>(D);
4948 RewriteObjCQualifiedInterfaceTypes(VD);
4949 if (isTopLevelBlockPointerType(VD->getType()))
4950 RewriteBlockPointerDecl(VD);
4951 else if (VD->getType()->isFunctionPointerType()) {
4952 CheckFunctionPointerDecl(VD->getType(), VD);
4953 if (VD->getInit()) {
4954 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4955 RewriteCastExpr(CE);
4956 }
4957 }
4958 } else if (VD->getType()->isRecordType()) {
4959 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4960 if (RD->isCompleteDefinition())
4961 RewriteRecordBody(RD);
4962 }
4963 if (VD->getInit()) {
4964 GlobalVarDecl = VD;
4965 CurrentBody = VD->getInit();
4966 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4967 CurrentBody = 0;
4968 if (PropParentMap) {
4969 delete PropParentMap;
4970 PropParentMap = 0;
4971 }
4972 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4973 GlobalVarDecl = 0;
4974
4975 // This is needed for blocks.
4976 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4977 RewriteCastExpr(CE);
4978 }
4979 }
4980 break;
4981 }
4982 case Decl::TypeAlias:
4983 case Decl::Typedef: {
4984 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4985 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4986 RewriteBlockPointerDecl(TD);
4987 else if (TD->getUnderlyingType()->isFunctionPointerType())
4988 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4989 }
4990 break;
4991 }
4992 case Decl::CXXRecord:
4993 case Decl::Record: {
4994 RecordDecl *RD = cast<RecordDecl>(D);
4995 if (RD->isCompleteDefinition())
4996 RewriteRecordBody(RD);
4997 break;
4998 }
4999 default:
5000 break;
5001 }
5002 // Nothing yet.
5003}
5004
5005void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5006 if (Diags.hasErrorOccurred())
5007 return;
5008
5009 RewriteInclude();
5010
5011 // Here's a great place to add any extra declarations that may be needed.
5012 // Write out meta data for each @protocol(<expr>).
5013 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5014 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005015 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005016
5017 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5018 if (ClassImplementation.size() || CategoryImplementation.size())
5019 RewriteImplementations();
5020
5021 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5022 // we are done.
5023 if (const RewriteBuffer *RewriteBuf =
5024 Rewrite.getRewriteBufferFor(MainFileID)) {
5025 //printf("Changed:\n");
5026 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5027 } else {
5028 llvm::errs() << "No changes\n";
5029 }
5030
5031 if (ClassImplementation.size() || CategoryImplementation.size() ||
5032 ProtocolExprDecls.size()) {
5033 // Rewrite Objective-c meta data*
5034 std::string ResultStr;
5035 RewriteMetaDataIntoBuffer(ResultStr);
5036 // Emit metadata.
5037 *OutFile << ResultStr;
5038 }
5039 OutFile->flush();
5040}
5041
5042void RewriteModernObjC::Initialize(ASTContext &context) {
5043 InitializeCommon(context);
5044
5045 // declaring objc_selector outside the parameter list removes a silly
5046 // scope related warning...
5047 if (IsHeader)
5048 Preamble = "#pragma once\n";
5049 Preamble += "struct objc_selector; struct objc_class;\n";
5050 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5051 Preamble += "struct objc_object *superClass; ";
5052 if (LangOpts.MicrosoftExt) {
5053 // Add a constructor for creating temporary objects.
5054 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5055 ": ";
5056 Preamble += "object(o), superClass(s) {} ";
5057 }
5058 Preamble += "};\n";
5059 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5060 Preamble += "typedef struct objc_object Protocol;\n";
5061 Preamble += "#define _REWRITER_typedef_Protocol\n";
5062 Preamble += "#endif\n";
5063 if (LangOpts.MicrosoftExt) {
5064 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5065 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5066 } else
5067 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5069 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5071 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5073 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5075 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5077 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5078 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5079 Preamble += "(const char *);\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5081 Preamble += "(struct objc_class *);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5083 Preamble += "(const char *);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5087 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5089 Preamble += "(struct objc_class *, struct objc_object *);\n";
5090 // @synchronized hooks.
5091 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5093 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5094 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5095 Preamble += "struct __objcFastEnumerationState {\n\t";
5096 Preamble += "unsigned long state;\n\t";
5097 Preamble += "void **itemsPtr;\n\t";
5098 Preamble += "unsigned long *mutationsPtr;\n\t";
5099 Preamble += "unsigned long extra[5];\n};\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5101 Preamble += "#define __FASTENUMERATIONSTATE\n";
5102 Preamble += "#endif\n";
5103 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5104 Preamble += "struct __NSConstantStringImpl {\n";
5105 Preamble += " int *isa;\n";
5106 Preamble += " int flags;\n";
5107 Preamble += " char *str;\n";
5108 Preamble += " long length;\n";
5109 Preamble += "};\n";
5110 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5111 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5112 Preamble += "#else\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5114 Preamble += "#endif\n";
5115 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5116 Preamble += "#endif\n";
5117 // Blocks preamble.
5118 Preamble += "#ifndef BLOCK_IMPL\n";
5119 Preamble += "#define BLOCK_IMPL\n";
5120 Preamble += "struct __block_impl {\n";
5121 Preamble += " void *isa;\n";
5122 Preamble += " int Flags;\n";
5123 Preamble += " int Reserved;\n";
5124 Preamble += " void *FuncPtr;\n";
5125 Preamble += "};\n";
5126 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5127 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) "
5129 "void _Block_object_assign(void *, const void *, const int);\n";
5130 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5131 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5132 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5133 Preamble += "#else\n";
5134 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5135 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5136 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5137 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5138 Preamble += "#endif\n";
5139 Preamble += "#endif\n";
5140 if (LangOpts.MicrosoftExt) {
5141 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5142 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5143 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5144 Preamble += "#define __attribute__(X)\n";
5145 Preamble += "#endif\n";
5146 Preamble += "#define __weak\n";
5147 }
5148 else {
5149 Preamble += "#define __block\n";
5150 Preamble += "#define __weak\n";
5151 }
5152 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5153 // as this avoids warning in any 64bit/32bit compilation model.
5154 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5155}
5156
5157/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5158/// ivar offset.
5159void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5160 std::string &Result) {
5161 if (ivar->isBitField()) {
5162 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5163 // place all bitfields at offset 0.
5164 Result += "0";
5165 } else {
5166 Result += "__OFFSETOFIVAR__(struct ";
5167 Result += ivar->getContainingInterface()->getNameAsString();
5168 if (LangOpts.MicrosoftExt)
5169 Result += "_IMPL";
5170 Result += ", ";
5171 Result += ivar->getNameAsString();
5172 Result += ")";
5173 }
5174}
5175
5176/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5177/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005178/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005179/// char *attributes;
5180/// }
5181
5182/// struct _prop_list_t {
5183/// uint32_t entsize; // sizeof(struct _prop_t)
5184/// uint32_t count_of_properties;
5185/// struct _prop_t prop_list[count_of_properties];
5186/// }
5187
5188/// struct _protocol_t;
5189
5190/// struct _protocol_list_t {
5191/// long protocol_count; // Note, this is 32/64 bit
5192/// struct _protocol_t * protocol_list[protocol_count];
5193/// }
5194
5195/// struct _objc_method {
5196/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005197/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005198/// char *_imp;
5199/// }
5200
5201/// struct _method_list_t {
5202/// uint32_t entsize; // sizeof(struct _objc_method)
5203/// uint32_t method_count;
5204/// struct _objc_method method_list[method_count];
5205/// }
5206
5207/// struct _protocol_t {
5208/// id isa; // NULL
5209/// const char * const protocol_name;
5210/// const struct _protocol_list_t * protocol_list; // super protocols
5211/// const struct method_list_t * const instance_methods;
5212/// const struct method_list_t * const class_methods;
5213/// const struct method_list_t *optionalInstanceMethods;
5214/// const struct method_list_t *optionalClassMethods;
5215/// const struct _prop_list_t * properties;
5216/// const uint32_t size; // sizeof(struct _protocol_t)
5217/// const uint32_t flags; // = 0
5218/// const char ** extendedMethodTypes;
5219/// }
5220
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005221/// struct _ivar_t {
5222/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005223/// const char *name;
5224/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005225/// uint32_t alignment;
5226/// uint32_t size;
5227/// }
5228
5229/// struct _ivar_list_t {
5230/// uint32 entsize; // sizeof(struct _ivar_t)
5231/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005232/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005233/// }
5234
5235/// struct _class_ro_t {
5236/// uint32_t const flags;
5237/// uint32_t const instanceStart;
5238/// uint32_t const instanceSize;
5239/// uint32_t const reserved; // only when building for 64bit targets
5240/// const uint8_t * const ivarLayout;
5241/// const char *const name;
5242/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005243/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005244/// const struct _ivar_list_t *const ivars;
5245/// const uint8_t * const weakIvarLayout;
5246/// const struct _prop_list_t * const properties;
5247/// }
5248
5249/// struct _class_t {
5250/// struct _class_t *isa;
5251/// struct _class_t * const superclass;
5252/// void *cache;
5253/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005254/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005255/// }
5256
5257/// struct _category_t {
5258/// const char * const name;
5259/// struct _class_t *const cls;
5260/// const struct _method_list_t * const instance_methods;
5261/// const struct _method_list_t * const class_methods;
5262/// const struct _protocol_list_t * const protocols;
5263/// const struct _prop_list_t * const properties;
5264/// }
5265
5266/// MessageRefTy - LLVM for:
5267/// struct _message_ref_t {
5268/// IMP messenger;
5269/// SEL name;
5270/// };
5271
5272/// SuperMessageRefTy - LLVM for:
5273/// struct _super_message_ref_t {
5274/// SUPER_IMP messenger;
5275/// SEL name;
5276/// };
5277
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005278static void WriteModernMetadataDeclarations(std::string &Result) {
5279 static bool meta_data_declared = false;
5280 if (meta_data_declared)
5281 return;
5282
5283 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005284 Result += "\tconst char *name;\n";
5285 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005286 Result += "};\n";
5287
5288 Result += "\nstruct _protocol_t;\n";
5289
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005290 Result += "\nstruct _objc_method {\n";
5291 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005292 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005293 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005294 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005295
5296 Result += "\nstruct _protocol_t {\n";
5297 Result += "\tvoid * isa; // NULL\n";
5298 Result += "\tconst char * const protocol_name;\n";
5299 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5300 Result += "\tconst struct method_list_t * const instance_methods;\n";
5301 Result += "\tconst struct method_list_t * const class_methods;\n";
5302 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5303 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5304 Result += "\tconst struct _prop_list_t * properties;\n";
5305 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5306 Result += "\tconst unsigned int flags; // = 0\n";
5307 Result += "\tconst char ** extendedMethodTypes;\n";
5308 Result += "};\n";
5309
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005310 Result += "\nstruct _ivar_t {\n";
5311 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005312 Result += "\tconst char *name;\n";
5313 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005314 Result += "\tunsigned int alignment;\n";
5315 Result += "\tunsigned int size;\n";
5316 Result += "};\n";
5317
5318 Result += "\nstruct _class_ro_t {\n";
5319 Result += "\tunsigned int const flags;\n";
5320 Result += "\tunsigned int instanceStart;\n";
5321 Result += "\tunsigned int const instanceSize;\n";
5322 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5323 Result += "\tconst unsigned char * const ivarLayout;\n";
5324 Result += "\tconst char *const name;\n";
5325 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5326 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5327 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5328 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5329 Result += "\tconst struct _prop_list_t *const properties;\n";
5330 Result += "};\n";
5331
5332 Result += "\nstruct _class_t {\n";
5333 Result += "\tstruct _class_t *isa;\n";
5334 Result += "\tstruct _class_t *const superclass;\n";
5335 Result += "\tvoid *cache;\n";
5336 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005337 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005338 Result += "};\n";
5339
5340 Result += "\nstruct _category_t {\n";
5341 Result += "\tconst char * const name;\n";
5342 Result += "\tstruct _class_t *const cls;\n";
5343 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5344 Result += "\tconst struct _method_list_t *const class_methods;\n";
5345 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5346 Result += "\tconst struct _prop_list_t *const properties;\n";
5347 Result += "};\n";
5348
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005349 Result += "extern void *_objc_empty_cache;\n";
5350 Result += "extern void *_objc_empty_vtable;\n";
5351
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005352 meta_data_declared = true;
5353}
5354
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005355static void Write_protocol_list_t_TypeDecl(std::string &Result,
5356 long super_protocol_count) {
5357 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5358 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5359 Result += "\tstruct _protocol_t *super_protocols[";
5360 Result += utostr(super_protocol_count); Result += "];\n";
5361 Result += "}";
5362}
5363
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005364static void Write_method_list_t_TypeDecl(std::string &Result,
5365 unsigned int method_count) {
5366 Result += "struct /*_method_list_t*/"; Result += " {\n";
5367 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5368 Result += "\tunsigned int method_count;\n";
5369 Result += "\tstruct _objc_method method_list[";
5370 Result += utostr(method_count); Result += "];\n";
5371 Result += "}";
5372}
5373
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005374static void Write__prop_list_t_TypeDecl(std::string &Result,
5375 unsigned int property_count) {
5376 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5377 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5378 Result += "\tunsigned int count_of_properties;\n";
5379 Result += "\tstruct _prop_t prop_list[";
5380 Result += utostr(property_count); Result += "];\n";
5381 Result += "}";
5382}
5383
Fariborz Jahanianae932952012-02-10 20:47:10 +00005384static void Write__ivar_list_t_TypeDecl(std::string &Result,
5385 unsigned int ivar_count) {
5386 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5387 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5388 Result += "\tunsigned int count;\n";
5389 Result += "\tstruct _ivar_t ivar_list[";
5390 Result += utostr(ivar_count); Result += "];\n";
5391 Result += "}";
5392}
5393
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005394static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5395 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5396 StringRef VarName,
5397 StringRef ProtocolName) {
5398 if (SuperProtocols.size() > 0) {
5399 Result += "\nstatic ";
5400 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5401 Result += " "; Result += VarName;
5402 Result += ProtocolName;
5403 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5404 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5405 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5406 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5407 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5408 Result += SuperPD->getNameAsString();
5409 if (i == e-1)
5410 Result += "\n};\n";
5411 else
5412 Result += ",\n";
5413 }
5414 }
5415}
5416
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005417static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5418 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005419 ArrayRef<ObjCMethodDecl *> Methods,
5420 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005421 StringRef TopLevelDeclName,
5422 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005423 if (Methods.size() > 0) {
5424 Result += "\nstatic ";
5425 Write_method_list_t_TypeDecl(Result, Methods.size());
5426 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005427 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005428 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5429 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5430 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5431 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5432 ObjCMethodDecl *MD = Methods[i];
5433 if (i == 0)
5434 Result += "\t{{(struct objc_selector *)\"";
5435 else
5436 Result += "\t{(struct objc_selector *)\"";
5437 Result += (MD)->getSelector().getAsString(); Result += "\"";
5438 Result += ", ";
5439 std::string MethodTypeString;
5440 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5441 Result += "\""; Result += MethodTypeString; Result += "\"";
5442 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005443 if (!MethodImpl)
5444 Result += "0";
5445 else {
5446 Result += "(void *)";
5447 Result += RewriteObj.MethodInternalNames[MD];
5448 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005449 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005450 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005451 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005452 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005453 }
5454 Result += "};\n";
5455 }
5456}
5457
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005458static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005459 ASTContext *Context, std::string &Result,
5460 ArrayRef<ObjCPropertyDecl *> Properties,
5461 const Decl *Container,
5462 StringRef VarName,
5463 StringRef ProtocolName) {
5464 if (Properties.size() > 0) {
5465 Result += "\nstatic ";
5466 Write__prop_list_t_TypeDecl(Result, Properties.size());
5467 Result += " "; Result += VarName;
5468 Result += ProtocolName;
5469 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5470 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5471 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5472 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5473 ObjCPropertyDecl *PropDecl = Properties[i];
5474 if (i == 0)
5475 Result += "\t{{\"";
5476 else
5477 Result += "\t{\"";
5478 Result += PropDecl->getName(); Result += "\",";
5479 std::string PropertyTypeString, QuotePropertyTypeString;
5480 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5481 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5482 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5483 if (i == e-1)
5484 Result += "}}\n";
5485 else
5486 Result += "},\n";
5487 }
5488 Result += "};\n";
5489 }
5490}
5491
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005492// Metadata flags
5493enum MetaDataDlags {
5494 CLS = 0x0,
5495 CLS_META = 0x1,
5496 CLS_ROOT = 0x2,
5497 OBJC2_CLS_HIDDEN = 0x10,
5498 CLS_EXCEPTION = 0x20,
5499
5500 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5501 CLS_HAS_IVAR_RELEASER = 0x40,
5502 /// class was compiled with -fobjc-arr
5503 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5504};
5505
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005506static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5507 unsigned int flags,
5508 const std::string &InstanceStart,
5509 const std::string &InstanceSize,
5510 ArrayRef<ObjCMethodDecl *>baseMethods,
5511 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5512 ArrayRef<ObjCIvarDecl *>ivars,
5513 ArrayRef<ObjCPropertyDecl *>Properties,
5514 StringRef VarName,
5515 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005516 Result += "\nstatic struct _class_ro_t ";
5517 Result += VarName; Result += ClassName;
5518 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5519 Result += "\t";
5520 Result += llvm::utostr(flags); Result += ", ";
5521 Result += InstanceStart; Result += ", ";
5522 Result += InstanceSize; Result += ", \n";
5523 Result += "\t";
5524 // uint32_t const reserved; // only when building for 64bit targets
5525 Result += "(unsigned int)0, \n\t";
5526 // const uint8_t * const ivarLayout;
5527 Result += "0, \n\t";
5528 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005529 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005530 if (baseMethods.size() > 0) {
5531 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005532 if (metaclass)
5533 Result += "_OBJC_$_CLASS_METHODS_";
5534 else
5535 Result += "_OBJC_$_INSTANCE_METHODS_";
5536 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005537 Result += ",\n\t";
5538 }
5539 else
5540 Result += "0, \n\t";
5541
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005542 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005543 Result += "(const struct _objc_protocol_list *)&";
5544 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5545 Result += ",\n\t";
5546 }
5547 else
5548 Result += "0, \n\t";
5549
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005550 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005551 Result += "(const struct _ivar_list_t *)&";
5552 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5553 Result += ",\n\t";
5554 }
5555 else
5556 Result += "0, \n\t";
5557
5558 // weakIvarLayout
5559 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005560 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005561 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005562 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005563 Result += ",\n";
5564 }
5565 else
5566 Result += "0, \n";
5567
5568 Result += "};\n";
5569}
5570
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005571static void Write_class_t(ASTContext *Context, std::string &Result,
5572 StringRef VarName,
5573 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005574
5575 if (metadata && !CDecl->getSuperClass()) {
5576 // Need to handle a case of use of forward declaration.
5577 Result += "\nextern struct _class_t OBJC_CLASS_$_";
5578 Result += CDecl->getNameAsString();
5579 Result += ";\n";
5580 }
5581 // Also, for possibility of 'super' metadata class not having been defined yet.
5582 if (CDecl->getSuperClass()) {
5583 Result += "\nextern struct _class_t "; Result += VarName;
5584 Result += CDecl->getSuperClass()->getNameAsString();
5585 Result += ";\n";
5586 }
5587
5588 Result += "\nstruct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
5589 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5590 Result += "\t";
5591 if (metadata) {
5592 if (CDecl->getSuperClass()) {
5593 Result += "&"; Result += VarName;
5594 Result += CDecl->getSuperClass()->getNameAsString();
5595 Result += ",\n\t";
5596 Result += "&"; Result += VarName;
5597 Result += CDecl->getSuperClass()->getNameAsString();
5598 Result += ",\n\t";
5599 }
5600 else {
5601 Result += "&"; Result += VarName;
5602 Result += CDecl->getNameAsString();
5603 Result += ",\n\t";
5604 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5605 Result += ",\n\t";
5606 }
5607 }
5608 else {
5609 Result += "&OBJC_METACLASS_$_";
5610 Result += CDecl->getNameAsString();
5611 Result += ",\n\t";
5612 if (CDecl->getSuperClass()) {
5613 Result += "&"; Result += VarName;
5614 Result += CDecl->getSuperClass()->getNameAsString();
5615 Result += ",\n\t";
5616 }
5617 else
5618 Result += "0,\n\t";
5619 }
5620 Result += "(void *)&_objc_empty_cache,\n\t";
5621 Result += "(void *)&_objc_empty_vtable,\n\t";
5622 if (metadata)
5623 Result += "&_OBJC_METACLASS_RO_$_";
5624 else
5625 Result += "&_OBJC_CLASS_RO_$_";
5626 Result += CDecl->getNameAsString();
5627 Result += ",\n};\n";
5628}
5629
Fariborz Jahanian61186122012-02-17 18:40:41 +00005630static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5631 std::string &Result,
5632 StringRef CatName,
5633 StringRef ClassName,
5634 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5635 ArrayRef<ObjCMethodDecl *> ClassMethods,
5636 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5637 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005638 // must declare an extern class object in case this class is not implemented
5639 // in this TU.
5640 Result += "\nextern struct _class_t ";
5641 Result += "OBJC_CLASS_$_"; Result += ClassName;
5642 Result += ";\n";
5643
Fariborz Jahanian61186122012-02-17 18:40:41 +00005644 Result += "\nstatic struct _category_t ";
5645 Result += "_OBJC_$_CATEGORY_";
5646 Result += ClassName; Result += "_$_"; Result += CatName;
5647 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5648 Result += "{\n";
5649 Result += "\t\""; Result += ClassName; Result += "\",\n";
5650 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5651 Result += ",\n";
5652 if (InstanceMethods.size() > 0) {
5653 Result += "\t(const struct _method_list_t *)&";
5654 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5655 Result += ClassName; Result += "_$_"; Result += CatName;
5656 Result += ",\n";
5657 }
5658 else
5659 Result += "\t0,\n";
5660
5661 if (ClassMethods.size() > 0) {
5662 Result += "\t(const struct _method_list_t *)&";
5663 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5664 Result += ClassName; Result += "_$_"; Result += CatName;
5665 Result += ",\n";
5666 }
5667 else
5668 Result += "\t0,\n";
5669
5670 if (RefedProtocols.size() > 0) {
5671 Result += "\t(const struct _protocol_list_t *)&";
5672 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5673 Result += ClassName; Result += "_$_"; Result += CatName;
5674 Result += ",\n";
5675 }
5676 else
5677 Result += "\t0,\n";
5678
5679 if (ClassProperties.size() > 0) {
5680 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5681 Result += ClassName; Result += "_$_"; Result += CatName;
5682 Result += ",\n";
5683 }
5684 else
5685 Result += "\t0,\n";
5686
5687 Result += "};\n";
5688}
5689
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005690static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5691 ASTContext *Context, std::string &Result,
5692 ArrayRef<ObjCMethodDecl *> Methods,
5693 StringRef VarName,
5694 StringRef ProtocolName) {
5695 if (Methods.size() == 0)
5696 return;
5697
5698 Result += "\nstatic const char *";
5699 Result += VarName; Result += ProtocolName;
5700 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5701 Result += "{\n";
5702 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5703 ObjCMethodDecl *MD = Methods[i];
5704 std::string MethodTypeString, QuoteMethodTypeString;
5705 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5706 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5707 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5708 if (i == e-1)
5709 Result += "\n};\n";
5710 else {
5711 Result += ",\n";
5712 }
5713 }
5714}
5715
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005716static void Write_IvarOffsetVar(std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005717 ArrayRef<ObjCIvarDecl *> Ivars,
5718 StringRef VarName,
5719 StringRef ClassName) {
5720 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5721 // this is what happens:
5722 /**
5723 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5724 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5725 Class->getVisibility() == HiddenVisibility)
5726 Visibility shoud be: HiddenVisibility;
5727 else
5728 Visibility shoud be: DefaultVisibility;
5729 */
5730
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005731 Result += "\n";
5732 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5733 ObjCIvarDecl *IvarDecl = Ivars[i];
5734 Result += "unsigned long int "; Result += VarName;
5735 Result += ClassName; Result += "_";
5736 Result += IvarDecl->getName();
5737 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5738 Result += " = ";
5739 if (IvarDecl->isBitField()) {
5740 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5741 // place all bitfields at offset 0.
5742 Result += "0;\n";
5743 }
5744 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005745 Result += "__OFFSETOFIVAR__(struct ";
5746 Result += ClassName;
5747 Result += "_IMPL, ";
5748 Result += IvarDecl->getName(); Result += ");\n";
5749 }
5750 }
5751}
5752
Fariborz Jahanianae932952012-02-10 20:47:10 +00005753static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5754 ASTContext *Context, std::string &Result,
5755 ArrayRef<ObjCIvarDecl *> Ivars,
5756 StringRef VarName,
5757 StringRef ClassName) {
5758 if (Ivars.size() > 0) {
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005759 Write_IvarOffsetVar(Result, Ivars, "OBJC_IVAR_$_", ClassName);
5760
Fariborz Jahanianae932952012-02-10 20:47:10 +00005761 Result += "\nstatic ";
5762 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5763 Result += " "; Result += VarName;
5764 Result += ClassName;
5765 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5766 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5767 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5768 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5769 ObjCIvarDecl *IvarDecl = Ivars[i];
5770 if (i == 0)
5771 Result += "\t{{";
5772 else
5773 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005774
5775 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5776 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5777 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005778
5779 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5780 std::string IvarTypeString, QuoteIvarTypeString;
5781 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5782 IvarDecl);
5783 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5784 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5785
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005786 // FIXME. this alignment represents the host alignment and need be changed to
5787 // represent the target alignment.
5788 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5789 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005790 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005791 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5792 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005793 if (i == e-1)
5794 Result += "}}\n";
5795 else
5796 Result += "},\n";
5797 }
5798 Result += "};\n";
5799 }
5800}
5801
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005802/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005803void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5804 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005805
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005806 // Do not synthesize the protocol more than once.
5807 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5808 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005809 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005810
5811 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5812 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005813 // Must write out all protocol definitions in current qualifier list,
5814 // and in their nested qualifiers before writing out current definition.
5815 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5816 E = PDecl->protocol_end(); I != E; ++I)
5817 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005818
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005819 // Construct method lists.
5820 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5821 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5822 for (ObjCProtocolDecl::instmeth_iterator
5823 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5824 I != E; ++I) {
5825 ObjCMethodDecl *MD = *I;
5826 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5827 OptInstanceMethods.push_back(MD);
5828 } else {
5829 InstanceMethods.push_back(MD);
5830 }
5831 }
5832
5833 for (ObjCProtocolDecl::classmeth_iterator
5834 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5835 I != E; ++I) {
5836 ObjCMethodDecl *MD = *I;
5837 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5838 OptClassMethods.push_back(MD);
5839 } else {
5840 ClassMethods.push_back(MD);
5841 }
5842 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005843 std::vector<ObjCMethodDecl *> AllMethods;
5844 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5845 AllMethods.push_back(InstanceMethods[i]);
5846 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5847 AllMethods.push_back(ClassMethods[i]);
5848 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5849 AllMethods.push_back(OptInstanceMethods[i]);
5850 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5851 AllMethods.push_back(OptClassMethods[i]);
5852
5853 Write__extendedMethodTypes_initializer(*this, Context, Result,
5854 AllMethods,
5855 "_OBJC_PROTOCOL_METHOD_TYPES_",
5856 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005857 // Protocol's super protocol list
5858 std::vector<ObjCProtocolDecl *> SuperProtocols;
5859 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5860 E = PDecl->protocol_end(); I != E; ++I)
5861 SuperProtocols.push_back(*I);
5862
5863 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5864 "_OBJC_PROTOCOL_REFS_",
5865 PDecl->getNameAsString());
5866
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005867 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005868 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005869 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005870
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005871 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005872 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005873 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005874
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005875 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005876 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005877 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005878
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005879 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005880 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005881 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005882
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005883 // Protocol's property metadata.
5884 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5885 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5886 E = PDecl->prop_end(); I != E; ++I)
5887 ProtocolProperties.push_back(*I);
5888
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005889 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005890 /* Container */0,
5891 "_OBJC_PROTOCOL_PROPERTIES_",
5892 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005893
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005894 // Writer out root metadata for current protocol: struct _protocol_t
5895 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005896 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005897 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5898 Result += "\t0,\n"; // id is; is null
5899 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005900 if (SuperProtocols.size() > 0) {
5901 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5902 Result += PDecl->getNameAsString(); Result += ",\n";
5903 }
5904 else
5905 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005906 if (InstanceMethods.size() > 0) {
5907 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5908 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005909 }
5910 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005911 Result += "\t0,\n";
5912
5913 if (ClassMethods.size() > 0) {
5914 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5915 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005916 }
5917 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005918 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005919
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005920 if (OptInstanceMethods.size() > 0) {
5921 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5922 Result += PDecl->getNameAsString(); Result += ",\n";
5923 }
5924 else
5925 Result += "\t0,\n";
5926
5927 if (OptClassMethods.size() > 0) {
5928 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5929 Result += PDecl->getNameAsString(); Result += ",\n";
5930 }
5931 else
5932 Result += "\t0,\n";
5933
5934 if (ProtocolProperties.size() > 0) {
5935 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5936 Result += PDecl->getNameAsString(); Result += ",\n";
5937 }
5938 else
5939 Result += "\t0,\n";
5940
5941 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5942 Result += "\t0,\n";
5943
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005944 if (AllMethods.size() > 0) {
5945 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5946 Result += PDecl->getNameAsString();
5947 Result += "\n};\n";
5948 }
5949 else
5950 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005951
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005952 // Mark this protocol as having been generated.
5953 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5954 llvm_unreachable("protocol already synthesized");
5955
5956}
5957
5958void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5959 const ObjCList<ObjCProtocolDecl> &Protocols,
5960 StringRef prefix, StringRef ClassName,
5961 std::string &Result) {
5962 if (Protocols.empty()) return;
5963
5964 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005965 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005966
5967 // Output the top lovel protocol meta-data for the class.
5968 /* struct _objc_protocol_list {
5969 struct _objc_protocol_list *next;
5970 int protocol_count;
5971 struct _objc_protocol *class_protocols[];
5972 }
5973 */
5974 Result += "\nstatic struct {\n";
5975 Result += "\tstruct _objc_protocol_list *next;\n";
5976 Result += "\tint protocol_count;\n";
5977 Result += "\tstruct _objc_protocol *class_protocols[";
5978 Result += utostr(Protocols.size());
5979 Result += "];\n} _OBJC_";
5980 Result += prefix;
5981 Result += "_PROTOCOLS_";
5982 Result += ClassName;
5983 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5984 "{\n\t0, ";
5985 Result += utostr(Protocols.size());
5986 Result += "\n";
5987
5988 Result += "\t,{&_OBJC_PROTOCOL_";
5989 Result += Protocols[0]->getNameAsString();
5990 Result += " \n";
5991
5992 for (unsigned i = 1; i != Protocols.size(); i++) {
5993 Result += "\t ,&_OBJC_PROTOCOL_";
5994 Result += Protocols[i]->getNameAsString();
5995 Result += "\n";
5996 }
5997 Result += "\t }\n};\n";
5998}
5999
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006000/// hasObjCExceptionAttribute - Return true if this class or any super
6001/// class has the __objc_exception__ attribute.
6002/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6003static bool hasObjCExceptionAttribute(ASTContext &Context,
6004 const ObjCInterfaceDecl *OID) {
6005 if (OID->hasAttr<ObjCExceptionAttr>())
6006 return true;
6007 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6008 return hasObjCExceptionAttribute(Context, Super);
6009 return false;
6010}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006011
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006012void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6013 std::string &Result) {
6014 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6015
6016 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006017 if (CDecl->isImplicitInterfaceDecl())
6018 assert(false &&
6019 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006020
Fariborz Jahanianae932952012-02-10 20:47:10 +00006021 WriteModernMetadataDeclarations(Result);
6022 SmallVector<ObjCIvarDecl *, 8> IVars;
6023
6024 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6025 IVD; IVD = IVD->getNextIvar()) {
6026 // Ignore unnamed bit-fields.
6027 if (!IVD->getDeclName())
6028 continue;
6029 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006030 }
6031
Fariborz Jahanianae932952012-02-10 20:47:10 +00006032 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006033 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006034 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006035
6036 // Build _objc_method_list for class's instance methods if needed
6037 SmallVector<ObjCMethodDecl *, 32>
6038 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6039
6040 // If any of our property implementations have associated getters or
6041 // setters, produce metadata for them as well.
6042 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6043 PropEnd = IDecl->propimpl_end();
6044 Prop != PropEnd; ++Prop) {
6045 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6046 continue;
6047 if (!(*Prop)->getPropertyIvarDecl())
6048 continue;
6049 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6050 if (!PD)
6051 continue;
6052 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6053 if (!Getter->isDefined())
6054 InstanceMethods.push_back(Getter);
6055 if (PD->isReadOnly())
6056 continue;
6057 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6058 if (!Setter->isDefined())
6059 InstanceMethods.push_back(Setter);
6060 }
6061
6062 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6063 "_OBJC_$_INSTANCE_METHODS_",
6064 IDecl->getNameAsString(), true);
6065
6066 SmallVector<ObjCMethodDecl *, 32>
6067 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6068
6069 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6070 "_OBJC_$_CLASS_METHODS_",
6071 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006072
6073 // Protocols referenced in class declaration?
6074 // Protocol's super protocol list
6075 std::vector<ObjCProtocolDecl *> RefedProtocols;
6076 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6077 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6078 E = Protocols.end();
6079 I != E; ++I) {
6080 RefedProtocols.push_back(*I);
6081 // Must write out all protocol definitions in current qualifier list,
6082 // and in their nested qualifiers before writing out current definition.
6083 RewriteObjCProtocolMetaData(*I, Result);
6084 }
6085
6086 Write_protocol_list_initializer(Context, Result,
6087 RefedProtocols,
6088 "_OBJC_CLASS_PROTOCOLS_$_",
6089 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006090
6091 // Protocol's property metadata.
6092 std::vector<ObjCPropertyDecl *> ClassProperties;
6093 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6094 E = CDecl->prop_end(); I != E; ++I)
6095 ClassProperties.push_back(*I);
6096
6097 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6098 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006099 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006100 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006101
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006102
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006103 // Data for initializing _class_ro_t metaclass meta-data
6104 uint32_t flags = CLS_META;
6105 std::string InstanceSize;
6106 std::string InstanceStart;
6107
6108
6109 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6110 if (classIsHidden)
6111 flags |= OBJC2_CLS_HIDDEN;
6112
6113 if (!CDecl->getSuperClass())
6114 // class is root
6115 flags |= CLS_ROOT;
6116 InstanceSize = "sizeof(struct _class_t)";
6117 InstanceStart = InstanceSize;
6118 Write__class_ro_t_initializer(Context, Result, flags,
6119 InstanceStart, InstanceSize,
6120 ClassMethods,
6121 0,
6122 0,
6123 0,
6124 "_OBJC_METACLASS_RO_$_",
6125 CDecl->getNameAsString());
6126
6127
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006128 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006129 flags = CLS;
6130 if (classIsHidden)
6131 flags |= OBJC2_CLS_HIDDEN;
6132
6133 if (hasObjCExceptionAttribute(*Context, CDecl))
6134 flags |= CLS_EXCEPTION;
6135
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006136 if (!CDecl->getSuperClass())
6137 // class is root
6138 flags |= CLS_ROOT;
6139
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006140 InstanceSize.clear();
6141 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006142 if (!ObjCSynthesizedStructs.count(CDecl)) {
6143 InstanceSize = "0";
6144 InstanceStart = "0";
6145 }
6146 else {
6147 InstanceSize = "sizeof(struct ";
6148 InstanceSize += CDecl->getNameAsString();
6149 InstanceSize += "_IMPL)";
6150
6151 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6152 if (IVD) {
6153 InstanceStart += "__OFFSETOFIVAR__(struct ";
6154 InstanceStart += CDecl->getNameAsString();
6155 InstanceStart += "_IMPL, ";
6156 InstanceStart += IVD->getNameAsString();
6157 InstanceStart += ")";
6158 }
6159 else
6160 InstanceStart = InstanceSize;
6161 }
6162 Write__class_ro_t_initializer(Context, Result, flags,
6163 InstanceStart, InstanceSize,
6164 InstanceMethods,
6165 RefedProtocols,
6166 IVars,
6167 ClassProperties,
6168 "_OBJC_CLASS_RO_$_",
6169 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006170
6171 Write_class_t(Context, Result,
6172 "OBJC_METACLASS_$_",
6173 CDecl, /*metaclass*/true);
6174
6175 Write_class_t(Context, Result,
6176 "OBJC_CLASS_$_",
6177 CDecl, /*metaclass*/false);
6178
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006179}
6180
6181void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6182 int ClsDefCount = ClassImplementation.size();
6183 int CatDefCount = CategoryImplementation.size();
6184
6185 // For each implemented class, write out all its meta data.
6186 for (int i = 0; i < ClsDefCount; i++)
6187 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6188
6189 // For each implemented category, write out all its meta data.
6190 for (int i = 0; i < CatDefCount; i++)
6191 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6192
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006193 if (ClsDefCount > 0) {
6194 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6195 Result += llvm::utostr(ClsDefCount); Result += "]";
6196 Result +=
6197 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6198 "regular,no_dead_strip\")))= {\n";
6199 for (int i = 0; i < ClsDefCount; i++) {
6200 Result += "\t&OBJC_CLASS_$_";
6201 Result += ClassImplementation[i]->getNameAsString();
6202 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006203 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006204 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006205 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006206
6207 if (CatDefCount > 0) {
6208 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6209 Result += llvm::utostr(CatDefCount); Result += "]";
6210 Result +=
6211 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6212 "regular,no_dead_strip\")))= {\n";
6213 for (int i = 0; i < CatDefCount; i++) {
6214 Result += "\t&_OBJC_$_CATEGORY_";
6215 Result +=
6216 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6217 Result += "_$_";
6218 Result += CategoryImplementation[i]->getNameAsString();
6219 Result += ",\n";
6220 }
6221 Result += "};\n";
6222 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006223}
6224
6225/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6226/// implementation.
6227void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6228 std::string &Result) {
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006229 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006230 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6231 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006232 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006233 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6234 CDecl = CDecl->getNextClassCategory())
6235 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6236 break;
6237
6238 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006239 FullCategoryName += "_$_";
6240 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006241
6242 // Build _objc_method_list for class's instance methods if needed
6243 SmallVector<ObjCMethodDecl *, 32>
6244 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6245
6246 // If any of our property implementations have associated getters or
6247 // setters, produce metadata for them as well.
6248 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6249 PropEnd = IDecl->propimpl_end();
6250 Prop != PropEnd; ++Prop) {
6251 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6252 continue;
6253 if (!(*Prop)->getPropertyIvarDecl())
6254 continue;
6255 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6256 if (!PD)
6257 continue;
6258 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6259 InstanceMethods.push_back(Getter);
6260 if (PD->isReadOnly())
6261 continue;
6262 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6263 InstanceMethods.push_back(Setter);
6264 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006265
Fariborz Jahanian61186122012-02-17 18:40:41 +00006266 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6267 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6268 FullCategoryName, true);
6269
6270 SmallVector<ObjCMethodDecl *, 32>
6271 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6272
6273 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6274 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6275 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006276
6277 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006278 // Protocol's super protocol list
6279 std::vector<ObjCProtocolDecl *> RefedProtocols;
6280 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6281 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6282 E = Protocols.end();
6283 I != E; ++I) {
6284 RefedProtocols.push_back(*I);
6285 // Must write out all protocol definitions in current qualifier list,
6286 // and in their nested qualifiers before writing out current definition.
6287 RewriteObjCProtocolMetaData(*I, Result);
6288 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006289
Fariborz Jahanian61186122012-02-17 18:40:41 +00006290 Write_protocol_list_initializer(Context, Result,
6291 RefedProtocols,
6292 "_OBJC_CATEGORY_PROTOCOLS_$_",
6293 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006294
Fariborz Jahanian61186122012-02-17 18:40:41 +00006295 // Protocol's property metadata.
6296 std::vector<ObjCPropertyDecl *> ClassProperties;
6297 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6298 E = CDecl->prop_end(); I != E; ++I)
6299 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006300
Fariborz Jahanian61186122012-02-17 18:40:41 +00006301 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6302 /* Container */0,
6303 "_OBJC_$_PROP_LIST_",
6304 FullCategoryName);
6305
6306 Write_category_t(*this, Context, Result,
6307 CDecl->getNameAsString(),
6308 ClassDecl->getNameAsString(),
6309 InstanceMethods,
6310 ClassMethods,
6311 RefedProtocols,
6312 ClassProperties);
6313
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006314}
6315
6316// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6317/// class methods.
6318template<typename MethodIterator>
6319void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6320 MethodIterator MethodEnd,
6321 bool IsInstanceMethod,
6322 StringRef prefix,
6323 StringRef ClassName,
6324 std::string &Result) {
6325 if (MethodBegin == MethodEnd) return;
6326
6327 if (!objc_impl_method) {
6328 /* struct _objc_method {
6329 SEL _cmd;
6330 char *method_types;
6331 void *_imp;
6332 }
6333 */
6334 Result += "\nstruct _objc_method {\n";
6335 Result += "\tSEL _cmd;\n";
6336 Result += "\tchar *method_types;\n";
6337 Result += "\tvoid *_imp;\n";
6338 Result += "};\n";
6339
6340 objc_impl_method = true;
6341 }
6342
6343 // Build _objc_method_list for class's methods if needed
6344
6345 /* struct {
6346 struct _objc_method_list *next_method;
6347 int method_count;
6348 struct _objc_method method_list[];
6349 }
6350 */
6351 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6352 Result += "\nstatic struct {\n";
6353 Result += "\tstruct _objc_method_list *next_method;\n";
6354 Result += "\tint method_count;\n";
6355 Result += "\tstruct _objc_method method_list[";
6356 Result += utostr(NumMethods);
6357 Result += "];\n} _OBJC_";
6358 Result += prefix;
6359 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6360 Result += "_METHODS_";
6361 Result += ClassName;
6362 Result += " __attribute__ ((used, section (\"__OBJC, __";
6363 Result += IsInstanceMethod ? "inst" : "cls";
6364 Result += "_meth\")))= ";
6365 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6366
6367 Result += "\t,{{(SEL)\"";
6368 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6369 std::string MethodTypeString;
6370 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6371 Result += "\", \"";
6372 Result += MethodTypeString;
6373 Result += "\", (void *)";
6374 Result += MethodInternalNames[*MethodBegin];
6375 Result += "}\n";
6376 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6377 Result += "\t ,{(SEL)\"";
6378 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6379 std::string MethodTypeString;
6380 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6381 Result += "\", \"";
6382 Result += MethodTypeString;
6383 Result += "\", (void *)";
6384 Result += MethodInternalNames[*MethodBegin];
6385 Result += "}\n";
6386 }
6387 Result += "\t }\n};\n";
6388}
6389
6390Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6391 SourceRange OldRange = IV->getSourceRange();
6392 Expr *BaseExpr = IV->getBase();
6393
6394 // Rewrite the base, but without actually doing replaces.
6395 {
6396 DisableReplaceStmtScope S(*this);
6397 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6398 IV->setBase(BaseExpr);
6399 }
6400
6401 ObjCIvarDecl *D = IV->getDecl();
6402
6403 Expr *Replacement = IV;
6404 if (CurMethodDef) {
6405 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6406 const ObjCInterfaceType *iFaceDecl =
6407 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6408 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6409 // lookup which class implements the instance variable.
6410 ObjCInterfaceDecl *clsDeclared = 0;
6411 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6412 clsDeclared);
6413 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6414
6415 // Synthesize an explicit cast to gain access to the ivar.
6416 std::string RecName = clsDeclared->getIdentifier()->getName();
6417 RecName += "_IMPL";
6418 IdentifierInfo *II = &Context->Idents.get(RecName);
6419 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6420 SourceLocation(), SourceLocation(),
6421 II);
6422 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6423 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6424 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6425 CK_BitCast,
6426 IV->getBase());
6427 // Don't forget the parens to enforce the proper binding.
6428 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6429 OldRange.getEnd(),
6430 castExpr);
6431 if (IV->isFreeIvar() &&
6432 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6433 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6434 IV->getLocation(),
6435 D->getType(),
6436 VK_LValue, OK_Ordinary);
6437 Replacement = ME;
6438 } else {
6439 IV->setBase(PE);
6440 }
6441 }
6442 } else { // we are outside a method.
6443 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6444
6445 // Explicit ivar refs need to have a cast inserted.
6446 // FIXME: consider sharing some of this code with the code above.
6447 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6448 const ObjCInterfaceType *iFaceDecl =
6449 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6450 // lookup which class implements the instance variable.
6451 ObjCInterfaceDecl *clsDeclared = 0;
6452 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6453 clsDeclared);
6454 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6455
6456 // Synthesize an explicit cast to gain access to the ivar.
6457 std::string RecName = clsDeclared->getIdentifier()->getName();
6458 RecName += "_IMPL";
6459 IdentifierInfo *II = &Context->Idents.get(RecName);
6460 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6461 SourceLocation(), SourceLocation(),
6462 II);
6463 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6464 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6465 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6466 CK_BitCast,
6467 IV->getBase());
6468 // Don't forget the parens to enforce the proper binding.
6469 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6470 IV->getBase()->getLocEnd(), castExpr);
6471 // Cannot delete IV->getBase(), since PE points to it.
6472 // Replace the old base with the cast. This is important when doing
6473 // embedded rewrites. For example, [newInv->_container addObject:0].
6474 IV->setBase(PE);
6475 }
6476 }
6477
6478 ReplaceStmtWithRange(IV, Replacement, OldRange);
6479 return Replacement;
6480}
6481