Bug Summary

File:tools/clang/lib/ARCMigrate/ObjCMT.cpp
Warning:line 983, column 33
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ObjCMT.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/ARCMigrate -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/ARCMigrate -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp

1//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
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#include "Transforms.h"
11#include "clang/ARCMigrate/ARCMT.h"
12#include "clang/ARCMigrate/ARCMTActions.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/NSAPI.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/Basic/FileManager.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/EditedSource.h"
23#include "clang/Edit/EditsReceiver.h"
24#include "clang/Edit/Rewriters.h"
25#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/MultiplexConsumer.h"
27#include "clang/Lex/PPConditionalDirectiveRecord.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Rewrite/Core/Rewriter.h"
30#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
31#include "llvm/ADT/SmallString.h"
32#include "llvm/ADT/StringSet.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/YAMLParser.h"
36
37using namespace clang;
38using namespace arcmt;
39using namespace ento::objc_retain;
40
41namespace {
42
43class ObjCMigrateASTConsumer : public ASTConsumer {
44 enum CF_BRIDGING_KIND {
45 CF_BRIDGING_NONE,
46 CF_BRIDGING_ENABLE,
47 CF_BRIDGING_MAY_INCLUDE
48 };
49
50 void migrateDecl(Decl *D);
51 void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
52 void migrateProtocolConformance(ASTContext &Ctx,
53 const ObjCImplementationDecl *ImpDecl);
54 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
55 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
56 const TypedefDecl *TypedefDcl);
57 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
58 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
59 ObjCMethodDecl *OM);
60 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
61 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
62 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
63 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
64 ObjCMethodDecl *OM,
65 ObjCInstanceTypeFamily OIT_Family = OIT_None);
66
67 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
68 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
69 const FunctionDecl *FuncDecl, bool ResultAnnotated);
70 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
71 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
72
73 void AnnotateImplicitBridging(ASTContext &Ctx);
74
75 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
76 const FunctionDecl *FuncDecl);
77
78 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
79
80 void migrateAddMethodAnnotation(ASTContext &Ctx,
81 const ObjCMethodDecl *MethodDecl);
82
83 void inferDesignatedInitializers(ASTContext &Ctx,
84 const ObjCImplementationDecl *ImplD);
85
86 bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
87
88public:
89 std::string MigrateDir;
90 unsigned ASTMigrateActions;
91 FileID FileId;
92 const TypedefDecl *NSIntegerTypedefed;
93 const TypedefDecl *NSUIntegerTypedefed;
94 std::unique_ptr<NSAPI> NSAPIObj;
95 std::unique_ptr<edit::EditedSource> Editor;
96 FileRemapper &Remapper;
97 FileManager &FileMgr;
98 const PPConditionalDirectiveRecord *PPRec;
99 Preprocessor &PP;
100 bool IsOutputFile;
101 bool FoundationIncluded;
102 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
103 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
104 llvm::StringSet<> WhiteListFilenames;
105
106 ObjCMigrateASTConsumer(StringRef migrateDir,
107 unsigned astMigrateActions,
108 FileRemapper &remapper,
109 FileManager &fileMgr,
110 const PPConditionalDirectiveRecord *PPRec,
111 Preprocessor &PP,
112 bool isOutputFile,
113 ArrayRef<std::string> WhiteList)
114 : MigrateDir(migrateDir),
115 ASTMigrateActions(astMigrateActions),
116 NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
117 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
118 IsOutputFile(isOutputFile),
119 FoundationIncluded(false){
120
121 // FIXME: StringSet should have insert(iter, iter) to use here.
122 for (const std::string &Val : WhiteList)
123 WhiteListFilenames.insert(Val);
124 }
125
126protected:
127 void Initialize(ASTContext &Context) override {
128 NSAPIObj.reset(new NSAPI(Context));
129 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
130 Context.getLangOpts(),
131 PPRec));
132 }
133
134 bool HandleTopLevelDecl(DeclGroupRef DG) override {
135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
136 migrateDecl(*I);
137 return true;
138 }
139 void HandleInterestingDecl(DeclGroupRef DG) override {
140 // Ignore decls from the PCH.
141 }
142 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
143 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
144 }
145
146 void HandleTranslationUnit(ASTContext &Ctx) override;
147
148 bool canModifyFile(StringRef Path) {
149 if (WhiteListFilenames.empty())
150 return true;
151 return WhiteListFilenames.find(llvm::sys::path::filename(Path))
152 != WhiteListFilenames.end();
153 }
154 bool canModifyFile(const FileEntry *FE) {
155 if (!FE)
156 return false;
157 return canModifyFile(FE->getName());
158 }
159 bool canModifyFile(FileID FID) {
160 if (FID.isInvalid())
161 return false;
162 return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
163 }
164
165 bool canModify(const Decl *D) {
166 if (!D)
167 return false;
168 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
169 return canModify(CatImpl->getCategoryDecl());
170 if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
171 return canModify(Impl->getClassInterface());
172 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
173 return canModify(cast<Decl>(MD->getDeclContext()));
174
175 FileID FID = PP.getSourceManager().getFileID(D->getLocation());
176 return canModifyFile(FID);
177 }
178};
179
180} // end anonymous namespace
181
182ObjCMigrateAction::ObjCMigrateAction(
183 std::unique_ptr<FrontendAction> WrappedAction,
184 StringRef migrateDir,
185 unsigned migrateAction)
186 : WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir),
187 ObjCMigAction(migrateAction),
188 CompInst(nullptr) {
189 if (MigrateDir.empty())
190 MigrateDir = "."; // user current directory if none is given.
191}
192
193std::unique_ptr<ASTConsumer>
194ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
195 PPConditionalDirectiveRecord *
196 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
1
Memory is allocated
197 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
2
Calling '~unique_ptr'
7
Returning from '~unique_ptr'
198 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
199 Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
200 Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
8
Calling 'make_unique'
201 MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
202 CompInst->getPreprocessor(), false, None));
203 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
204}
205
206bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
207 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
208 /*ignoreIfFilesChanges=*/true);
209 CompInst = &CI;
210 CI.getDiagnostics().setIgnoreAllWarnings(true);
211 return true;
212}
213
214namespace {
215 // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
216 bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
217 const Expr* Expr = FullExpr->IgnoreImpCasts();
218 return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
219 isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
220 isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
221 isa<CXXTypeidExpr>(Expr) ||
222 isa<CXXUnresolvedConstructExpr>(Expr) ||
223 isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
224 isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
225 isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
226 isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
227 }
228
229 /// \brief - Rewrite message expression for Objective-C setter and getters into
230 /// property-dot syntax.
231 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
232 Preprocessor &PP,
233 const NSAPI &NS, edit::Commit &commit,
234 const ParentMap *PMap) {
235 if (!Msg || Msg->isImplicit() ||
236 (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
237 Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
238 return false;
239 if (const Expr *Receiver = Msg->getInstanceReceiver())
240 if (Receiver->getType()->isObjCBuiltinType())
241 return false;
242
243 const ObjCMethodDecl *Method = Msg->getMethodDecl();
244 if (!Method)
245 return false;
246 if (!Method->isPropertyAccessor())
247 return false;
248
249 const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
250 if (!Prop)
251 return false;
252
253 SourceRange MsgRange = Msg->getSourceRange();
254 bool ReceiverIsSuper =
255 (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
256 // for 'super' receiver is nullptr.
257 const Expr *receiver = Msg->getInstanceReceiver();
258 bool NeedsParen =
259 ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
260 bool IsGetter = (Msg->getNumArgs() == 0);
261 if (IsGetter) {
262 // Find space location range between receiver expression and getter method.
263 SourceLocation BegLoc =
264 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
265 BegLoc = PP.getLocForEndOfToken(BegLoc);
266 SourceLocation EndLoc = Msg->getSelectorLoc(0);
267 SourceRange SpaceRange(BegLoc, EndLoc);
268 std::string PropertyDotString;
269 // rewrite getter method expression into: receiver.property or
270 // (receiver).property
271 if (NeedsParen) {
272 commit.insertBefore(receiver->getLocStart(), "(");
273 PropertyDotString = ").";
274 }
275 else
276 PropertyDotString = ".";
277 PropertyDotString += Prop->getName();
278 commit.replace(SpaceRange, PropertyDotString);
279
280 // remove '[' ']'
281 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
282 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
283 } else {
284 if (NeedsParen)
285 commit.insertWrap("(", receiver->getSourceRange(), ")");
286 std::string PropertyDotString = ".";
287 PropertyDotString += Prop->getName();
288 PropertyDotString += " =";
289 const Expr*const* Args = Msg->getArgs();
290 const Expr *RHS = Args[0];
291 if (!RHS)
292 return false;
293 SourceLocation BegLoc =
294 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
295 BegLoc = PP.getLocForEndOfToken(BegLoc);
296 SourceLocation EndLoc = RHS->getLocStart();
297 EndLoc = EndLoc.getLocWithOffset(-1);
298 const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
299 // Add a space after '=' if there is no space between RHS and '='
300 if (colon && colon[0] == ':')
301 PropertyDotString += " ";
302 SourceRange Range(BegLoc, EndLoc);
303 commit.replace(Range, PropertyDotString);
304 // remove '[' ']'
305 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
306 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
307 }
308 return true;
309 }
310
311class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
312 ObjCMigrateASTConsumer &Consumer;
313 ParentMap &PMap;
314
315public:
316 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
317 : Consumer(consumer), PMap(PMap) { }
318
319 bool shouldVisitTemplateInstantiations() const { return false; }
320 bool shouldWalkTypesOfTypeLocs() const { return false; }
321
322 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
323 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
324 edit::Commit commit(*Consumer.Editor);
325 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
326 Consumer.Editor->commit(commit);
327 }
328
329 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
330 edit::Commit commit(*Consumer.Editor);
331 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
332 Consumer.Editor->commit(commit);
333 }
334
335 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
336 edit::Commit commit(*Consumer.Editor);
337 rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
338 commit, &PMap);
339 Consumer.Editor->commit(commit);
340 }
341
342 return true;
343 }
344
345 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
346 // Do depth first; we want to rewrite the subexpressions first so that if
347 // we have to move expressions we will move them already rewritten.
348 for (Stmt *SubStmt : E->children())
349 if (!TraverseStmt(SubStmt))
350 return false;
351
352 return WalkUpFromObjCMessageExpr(E);
353 }
354};
355
356class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
357 ObjCMigrateASTConsumer &Consumer;
358 std::unique_ptr<ParentMap> PMap;
359
360public:
361 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
362
363 bool shouldVisitTemplateInstantiations() const { return false; }
364 bool shouldWalkTypesOfTypeLocs() const { return false; }
365
366 bool TraverseStmt(Stmt *S) {
367 PMap.reset(new ParentMap(S));
368 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
369 return true;
370 }
371};
372} // end anonymous namespace
373
374void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
375 if (!D)
376 return;
377 if (isa<ObjCMethodDecl>(D))
378 return; // Wait for the ObjC container declaration.
379
380 BodyMigrator(*this).TraverseDecl(D);
381}
382
383static void append_attr(std::string &PropertyString, const char *attr,
384 bool &LParenAdded) {
385 if (!LParenAdded) {
386 PropertyString += "(";
387 LParenAdded = true;
388 }
389 else
390 PropertyString += ", ";
391 PropertyString += attr;
392}
393
394static
395void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
396 const std::string& TypeString,
397 const char *name) {
398 const char *argPtr = TypeString.c_str();
399 int paren = 0;
400 while (*argPtr) {
401 switch (*argPtr) {
402 case '(':
403 PropertyString += *argPtr;
404 paren++;
405 break;
406 case ')':
407 PropertyString += *argPtr;
408 paren--;
409 break;
410 case '^':
411 case '*':
412 PropertyString += (*argPtr);
413 if (paren == 1) {
414 PropertyString += name;
415 name = "";
416 }
417 break;
418 default:
419 PropertyString += *argPtr;
420 break;
421 }
422 argPtr++;
423 }
424}
425
426static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
427 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
428 bool RetainableObject = ArgType->isObjCRetainableType();
429 if (RetainableObject &&
430 (propertyLifetime == Qualifiers::OCL_Strong
431 || propertyLifetime == Qualifiers::OCL_None)) {
432 if (const ObjCObjectPointerType *ObjPtrTy =
433 ArgType->getAs<ObjCObjectPointerType>()) {
434 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
435 if (IDecl &&
436 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
437 return "copy";
438 else
439 return "strong";
440 }
441 else if (ArgType->isBlockPointerType())
442 return "copy";
443 } else if (propertyLifetime == Qualifiers::OCL_Weak)
444 // TODO. More precise determination of 'weak' attribute requires
445 // looking into setter's implementation for backing weak ivar.
446 return "weak";
447 else if (RetainableObject)
448 return ArgType->isBlockPointerType() ? "copy" : "strong";
449 return nullptr;
450}
451
452static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
453 const ObjCMethodDecl *Setter,
454 const NSAPI &NS, edit::Commit &commit,
455 unsigned LengthOfPrefix,
456 bool Atomic, bool UseNsIosOnlyMacro,
457 bool AvailabilityArgsMatch) {
458 ASTContext &Context = NS.getASTContext();
459 bool LParenAdded = false;
460 std::string PropertyString = "@property ";
461 if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
462 PropertyString += "(NS_NONATOMIC_IOSONLY";
463 LParenAdded = true;
464 } else if (!Atomic) {
465 PropertyString += "(nonatomic";
466 LParenAdded = true;
467 }
468
469 std::string PropertyNameString = Getter->getNameAsString();
470 StringRef PropertyName(PropertyNameString);
471 if (LengthOfPrefix > 0) {
472 if (!LParenAdded) {
473 PropertyString += "(getter=";
474 LParenAdded = true;
475 }
476 else
477 PropertyString += ", getter=";
478 PropertyString += PropertyNameString;
479 }
480 // Property with no setter may be suggested as a 'readonly' property.
481 if (!Setter)
482 append_attr(PropertyString, "readonly", LParenAdded);
483
484
485 // Short circuit 'delegate' properties that contain the name "delegate" or
486 // "dataSource", or have exact name "target" to have 'assign' attribute.
487 if (PropertyName.equals("target") ||
488 (PropertyName.find("delegate") != StringRef::npos) ||
489 (PropertyName.find("dataSource") != StringRef::npos)) {
490 QualType QT = Getter->getReturnType();
491 if (!QT->isRealType())
492 append_attr(PropertyString, "assign", LParenAdded);
493 } else if (!Setter) {
494 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
495 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
496 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
497 } else {
498 const ParmVarDecl *argDecl = *Setter->param_begin();
499 QualType ArgType = Context.getCanonicalType(argDecl->getType());
500 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
501 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
502 }
503 if (LParenAdded)
504 PropertyString += ')';
505 QualType RT = Getter->getReturnType();
506 if (!isa<TypedefType>(RT)) {
507 // strip off any ARC lifetime qualifier.
508 QualType CanResultTy = Context.getCanonicalType(RT);
509 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
510 Qualifiers Qs = CanResultTy.getQualifiers();
511 Qs.removeObjCLifetime();
512 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
513 }
514 }
515 PropertyString += " ";
516 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
517 SubPolicy.SuppressStrongLifetime = true;
518 SubPolicy.SuppressLifetimeQualifiers = true;
519 std::string TypeString = RT.getAsString(SubPolicy);
520 if (LengthOfPrefix > 0) {
521 // property name must strip off "is" and lower case the first character
522 // after that; e.g. isContinuous will become continuous.
523 StringRef PropertyNameStringRef(PropertyNameString);
524 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
525 PropertyNameString = PropertyNameStringRef;
526 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
527 PropertyNameString.size() > 1 &&
528 isUppercase(PropertyNameString[1]));
529 if (!NoLowering)
530 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
531 }
532 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
533 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
534 TypeString,
535 PropertyNameString.c_str());
536 else {
537 char LastChar = TypeString[TypeString.size()-1];
538 PropertyString += TypeString;
539 if (LastChar != '*')
540 PropertyString += ' ';
541 PropertyString += PropertyNameString;
542 }
543 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
544 Selector GetterSelector = Getter->getSelector();
545
546 SourceLocation EndGetterSelectorLoc =
547 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
548 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
549 EndGetterSelectorLoc),
550 PropertyString);
551 if (Setter && AvailabilityArgsMatch) {
552 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
553 // Get location past ';'
554 EndLoc = EndLoc.getLocWithOffset(1);
555 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
556 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
557 // It is trying to remove the setter method decl. line entirely.
558 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
559 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
560 }
561}
562
563static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
564 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
565 StringRef Name = CatDecl->getName();
566 return Name.endswith("Deprecated");
567 }
568 return false;
569}
570
571void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
572 ObjCContainerDecl *D) {
573 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
574 return;
575
576 for (auto *Method : D->methods()) {
577 if (Method->isDeprecated())
578 continue;
579 bool PropertyInferred = migrateProperty(Ctx, D, Method);
580 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
581 // the getter method as it ends up on the property itself which we don't want
582 // to do unless -objcmt-returns-innerpointer-property option is on.
583 if (!PropertyInferred ||
584 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
585 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
586 migrateNsReturnsInnerPointer(Ctx, Method);
587 }
588 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
589 return;
590
591 for (auto *Prop : D->instance_properties()) {
592 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
593 !Prop->isDeprecated())
594 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
595 }
596}
597
598static bool
599ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
600 const ObjCImplementationDecl *ImpDecl,
601 const ObjCInterfaceDecl *IDecl,
602 ObjCProtocolDecl *Protocol) {
603 // In auto-synthesis, protocol properties are not synthesized. So,
604 // a conforming protocol must have its required properties declared
605 // in class interface.
606 bool HasAtleastOneRequiredProperty = false;
607 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
608 for (const auto *Property : PDecl->instance_properties()) {
609 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
610 continue;
611 HasAtleastOneRequiredProperty = true;
612 DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
613 if (R.size() == 0) {
614 // Relax the rule and look into class's implementation for a synthesize
615 // or dynamic declaration. Class is implementing a property coming from
616 // another protocol. This still makes the target protocol as conforming.
617 if (!ImpDecl->FindPropertyImplDecl(
618 Property->getDeclName().getAsIdentifierInfo(),
619 Property->getQueryKind()))
620 return false;
621 }
622 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
623 if ((ClassProperty->getPropertyAttributes()
624 != Property->getPropertyAttributes()) ||
625 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
626 return false;
627 }
628 else
629 return false;
630 }
631
632 // At this point, all required properties in this protocol conform to those
633 // declared in the class.
634 // Check that class implements the required methods of the protocol too.
635 bool HasAtleastOneRequiredMethod = false;
636 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
637 if (PDecl->meth_begin() == PDecl->meth_end())
638 return HasAtleastOneRequiredProperty;
639 for (const auto *MD : PDecl->methods()) {
640 if (MD->isImplicit())
641 continue;
642 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
643 continue;
644 DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
645 if (R.size() == 0)
646 return false;
647 bool match = false;
648 HasAtleastOneRequiredMethod = true;
649 for (unsigned I = 0, N = R.size(); I != N; ++I)
650 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
651 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
652 match = true;
653 break;
654 }
655 if (!match)
656 return false;
657 }
658 }
659 return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
660}
661
662static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
663 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
664 const NSAPI &NS, edit::Commit &commit) {
665 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
666 std::string ClassString;
667 SourceLocation EndLoc =
668 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
669
670 if (Protocols.empty()) {
671 ClassString = '<';
672 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
673 ClassString += ConformingProtocols[i]->getNameAsString();
674 if (i != (e-1))
675 ClassString += ", ";
676 }
677 ClassString += "> ";
678 }
679 else {
680 ClassString = ", ";
681 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
682 ClassString += ConformingProtocols[i]->getNameAsString();
683 if (i != (e-1))
684 ClassString += ", ";
685 }
686 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
687 EndLoc = *PL;
688 }
689
690 commit.insertAfterToken(EndLoc, ClassString);
691 return true;
692}
693
694static StringRef GetUnsignedName(StringRef NSIntegerName) {
695 StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
696 .Case("int8_t", "uint8_t")
697 .Case("int16_t", "uint16_t")
698 .Case("int32_t", "uint32_t")
699 .Case("NSInteger", "NSUInteger")
700 .Case("int64_t", "uint64_t")
701 .Default(NSIntegerName);
702 return UnsignedName;
703}
704
705static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
706 const TypedefDecl *TypedefDcl,
707 const NSAPI &NS, edit::Commit &commit,
708 StringRef NSIntegerName,
709 bool NSOptions) {
710 std::string ClassString;
711 if (NSOptions) {
712 ClassString = "typedef NS_OPTIONS(";
713 ClassString += GetUnsignedName(NSIntegerName);
714 }
715 else {
716 ClassString = "typedef NS_ENUM(";
717 ClassString += NSIntegerName;
718 }
719 ClassString += ", ";
720
721 ClassString += TypedefDcl->getIdentifier()->getName();
722 ClassString += ')';
723 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
724 commit.replace(R, ClassString);
725 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
726 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
727 NS.getASTContext(), /*IsDecl*/true);
728 if (EndOfEnumDclLoc.isValid()) {
729 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
730 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
731 }
732 else
733 return false;
734
735 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
736 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
737 NS.getASTContext(), /*IsDecl*/true);
738 if (EndTypedefDclLoc.isValid()) {
739 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
740 commit.remove(TDRange);
741 }
742 else
743 return false;
744
745 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
746 /*IsDecl*/true);
747 if (EndOfEnumDclLoc.isValid()) {
748 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
749 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
750 // It is trying to remove the enum decl. lines entirely.
751 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
752 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
753 return true;
754 }
755 return false;
756}
757
758static void rewriteToNSMacroDecl(ASTContext &Ctx,
759 const EnumDecl *EnumDcl,
760 const TypedefDecl *TypedefDcl,
761 const NSAPI &NS, edit::Commit &commit,
762 bool IsNSIntegerType) {
763 QualType DesignatedEnumType = EnumDcl->getIntegerType();
764 assert(!DesignatedEnumType.isNull()(static_cast <bool> (!DesignatedEnumType.isNull() &&
"rewriteToNSMacroDecl - underlying enum type is null") ? void
(0) : __assert_fail ("!DesignatedEnumType.isNull() && \"rewriteToNSMacroDecl - underlying enum type is null\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 765, __extension__ __PRETTY_FUNCTION__))
765 && "rewriteToNSMacroDecl - underlying enum type is null")(static_cast <bool> (!DesignatedEnumType.isNull() &&
"rewriteToNSMacroDecl - underlying enum type is null") ? void
(0) : __assert_fail ("!DesignatedEnumType.isNull() && \"rewriteToNSMacroDecl - underlying enum type is null\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 765, __extension__ __PRETTY_FUNCTION__))
;
766
767 PrintingPolicy Policy(Ctx.getPrintingPolicy());
768 std::string TypeString = DesignatedEnumType.getAsString(Policy);
769 std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
770 ClassString += TypeString;
771 ClassString += ", ";
772
773 ClassString += TypedefDcl->getIdentifier()->getName();
774 ClassString += ") ";
775 SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin();
776 if (EndLoc.isInvalid())
777 return;
778 CharSourceRange R = CharSourceRange::getCharRange(EnumDcl->getLocStart(), EndLoc);
779 commit.replace(R, ClassString);
780 // This is to remove spaces between '}' and typedef name.
781 SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
782 StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
783 SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
784
785 commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
786}
787
788static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
789 const EnumDecl *EnumDcl) {
790 bool PowerOfTwo = true;
791 bool AllHexdecimalEnumerator = true;
792 uint64_t MaxPowerOfTwoVal = 0;
793 for (auto Enumerator : EnumDcl->enumerators()) {
794 const Expr *InitExpr = Enumerator->getInitExpr();
795 if (!InitExpr) {
796 PowerOfTwo = false;
797 AllHexdecimalEnumerator = false;
798 continue;
799 }
800 InitExpr = InitExpr->IgnoreParenCasts();
801 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
802 if (BO->isShiftOp() || BO->isBitwiseOp())
803 return true;
804
805 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
806 if (PowerOfTwo && EnumVal) {
807 if (!llvm::isPowerOf2_64(EnumVal))
808 PowerOfTwo = false;
809 else if (EnumVal > MaxPowerOfTwoVal)
810 MaxPowerOfTwoVal = EnumVal;
811 }
812 if (AllHexdecimalEnumerator && EnumVal) {
813 bool FoundHexdecimalEnumerator = false;
814 SourceLocation EndLoc = Enumerator->getLocEnd();
815 Token Tok;
816 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
817 if (Tok.isLiteral() && Tok.getLength() > 2) {
818 if (const char *StringLit = Tok.getLiteralData())
819 FoundHexdecimalEnumerator =
820 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
821 }
822 if (!FoundHexdecimalEnumerator)
823 AllHexdecimalEnumerator = false;
824 }
825 }
826 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
827}
828
829void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
830 const ObjCImplementationDecl *ImpDecl) {
831 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
832 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
833 return;
834 // Find all implicit conforming protocols for this class
835 // and make them explicit.
836 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
837 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
838 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
839
840 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
841 if (!ExplicitProtocols.count(ProtDecl))
842 PotentialImplicitProtocols.push_back(ProtDecl);
843
844 if (PotentialImplicitProtocols.empty())
845 return;
846
847 // go through list of non-optional methods and properties in each protocol
848 // in the PotentialImplicitProtocols list. If class implements every one of the
849 // methods and properties, then this class conforms to this protocol.
850 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
851 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
852 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
853 PotentialImplicitProtocols[i]))
854 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
855
856 if (ConformingProtocols.empty())
857 return;
858
859 // Further reduce number of conforming protocols. If protocol P1 is in the list
860 // protocol P2 (P2<P1>), No need to include P1.
861 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
862 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
863 bool DropIt = false;
864 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
865 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
866 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
867 if (PDecl == TargetPDecl)
868 continue;
869 if (PDecl->lookupProtocolNamed(
870 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
871 DropIt = true;
872 break;
873 }
874 }
875 if (!DropIt)
876 MinimalConformingProtocols.push_back(TargetPDecl);
877 }
878 if (MinimalConformingProtocols.empty())
879 return;
880 edit::Commit commit(*Editor);
881 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
882 *NSAPIObj, commit);
883 Editor->commit(commit);
884}
885
886void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
887 const TypedefDecl *TypedefDcl) {
888
889 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
890 if (NSAPIObj->isObjCNSIntegerType(qt))
891 NSIntegerTypedefed = TypedefDcl;
892 else if (NSAPIObj->isObjCNSUIntegerType(qt))
893 NSUIntegerTypedefed = TypedefDcl;
894}
895
896bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
897 const EnumDecl *EnumDcl,
898 const TypedefDecl *TypedefDcl) {
899 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
900 EnumDcl->isDeprecated())
901 return false;
902 if (!TypedefDcl) {
903 if (NSIntegerTypedefed) {
904 TypedefDcl = NSIntegerTypedefed;
905 NSIntegerTypedefed = nullptr;
906 }
907 else if (NSUIntegerTypedefed) {
908 TypedefDcl = NSUIntegerTypedefed;
909 NSUIntegerTypedefed = nullptr;
910 }
911 else
912 return false;
913 FileID FileIdOfTypedefDcl =
914 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
915 FileID FileIdOfEnumDcl =
916 PP.getSourceManager().getFileID(EnumDcl->getLocation());
917 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
918 return false;
919 }
920 if (TypedefDcl->isDeprecated())
921 return false;
922
923 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
924 StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
925
926 if (NSIntegerName.empty()) {
927 // Also check for typedef enum {...} TD;
928 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
929 if (EnumTy->getDecl() == EnumDcl) {
930 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
931 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
932 return false;
933 edit::Commit commit(*Editor);
934 rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
935 Editor->commit(commit);
936 return true;
937 }
938 }
939 return false;
940 }
941
942 // We may still use NS_OPTIONS based on what we find in the enumertor list.
943 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
944 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
945 return false;
946 edit::Commit commit(*Editor);
947 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
948 commit, NSIntegerName, NSOptions);
949 Editor->commit(commit);
950 return Res;
951}
952
953static void ReplaceWithInstancetype(ASTContext &Ctx,
954 const ObjCMigrateASTConsumer &ASTC,
955 ObjCMethodDecl *OM) {
956 if (OM->getReturnType() == Ctx.getObjCInstanceType())
957 return; // already has instancetype.
958
959 SourceRange R;
960 std::string ClassString;
961 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
962 TypeLoc TL = TSInfo->getTypeLoc();
963 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
964 ClassString = "instancetype";
965 }
966 else {
967 R = SourceRange(OM->getLocStart(), OM->getLocStart());
968 ClassString = OM->isInstanceMethod() ? '-' : '+';
969 ClassString += " (instancetype)";
970 }
971 edit::Commit commit(*ASTC.Editor);
972 commit.replace(R, ClassString);
973 ASTC.Editor->commit(commit);
974}
975
976static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
977 ObjCMethodDecl *OM) {
978 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
979 SourceRange R;
980 std::string ClassString;
981 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
982 TypeLoc TL = TSInfo->getTypeLoc();
983 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
984 ClassString = IDecl->getName();
985 ClassString += "*";
986 }
987 }
988 else {
989 R = SourceRange(OM->getLocStart(), OM->getLocStart());
990 ClassString = "+ (";
991 ClassString += IDecl->getName(); ClassString += "*)";
992 }
993 edit::Commit commit(*ASTC.Editor);
994 commit.replace(R, ClassString);
995 ASTC.Editor->commit(commit);
996}
997
998void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
999 ObjCContainerDecl *CDecl,
1000 ObjCMethodDecl *OM) {
1001 ObjCInstanceTypeFamily OIT_Family =
1002 Selector::getInstTypeMethodFamily(OM->getSelector());
1003
1004 std::string ClassName;
1005 switch (OIT_Family) {
1006 case OIT_None:
1007 migrateFactoryMethod(Ctx, CDecl, OM);
1008 return;
1009 case OIT_Array:
1010 ClassName = "NSArray";
1011 break;
1012 case OIT_Dictionary:
1013 ClassName = "NSDictionary";
1014 break;
1015 case OIT_Singleton:
1016 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
1017 return;
1018 case OIT_Init:
1019 if (OM->getReturnType()->isObjCIdType())
1020 ReplaceWithInstancetype(Ctx, *this, OM);
1021 return;
1022 case OIT_ReturnsSelf:
1023 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1024 return;
1025 }
1026 if (!OM->getReturnType()->isObjCIdType())
1027 return;
1028
1029 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1030 if (!IDecl) {
1031 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1032 IDecl = CatDecl->getClassInterface();
1033 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1034 IDecl = ImpDecl->getClassInterface();
1035 }
1036 if (!IDecl ||
1037 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1038 migrateFactoryMethod(Ctx, CDecl, OM);
1039 return;
1040 }
1041 ReplaceWithInstancetype(Ctx, *this, OM);
1042}
1043
1044static bool TypeIsInnerPointer(QualType T) {
1045 if (!T->isAnyPointerType())
1046 return false;
1047 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
1048 T->isBlockPointerType() || T->isFunctionPointerType() ||
1049 ento::coreFoundation::isCFObjectRef(T))
1050 return false;
1051 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1052 // is not an innter pointer type.
1053 QualType OrigT = T;
1054 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1055 T = TD->getDecl()->getUnderlyingType();
1056 if (OrigT == T || !T->isPointerType())
1057 return true;
1058 const PointerType* PT = T->getAs<PointerType>();
1059 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1060 if (UPointeeT->isRecordType()) {
1061 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1062 if (!RecordTy->getDecl()->isCompleteDefinition())
1063 return false;
1064 }
1065 return true;
1066}
1067
1068/// \brief Check whether the two versions match.
1069static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1070 return (X == Y);
1071}
1072
1073/// AvailabilityAttrsMatch - This routine checks that if comparing two
1074/// availability attributes, all their components match. It returns
1075/// true, if not dealing with availability or when all components of
1076/// availability attributes match. This routine is only called when
1077/// the attributes are of the same kind.
1078static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1079 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1080 if (!AA1)
1081 return true;
1082 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
1083
1084 VersionTuple Introduced1 = AA1->getIntroduced();
1085 VersionTuple Deprecated1 = AA1->getDeprecated();
1086 VersionTuple Obsoleted1 = AA1->getObsoleted();
1087 bool IsUnavailable1 = AA1->getUnavailable();
1088 VersionTuple Introduced2 = AA2->getIntroduced();
1089 VersionTuple Deprecated2 = AA2->getDeprecated();
1090 VersionTuple Obsoleted2 = AA2->getObsoleted();
1091 bool IsUnavailable2 = AA2->getUnavailable();
1092 return (versionsMatch(Introduced1, Introduced2) &&
1093 versionsMatch(Deprecated1, Deprecated2) &&
1094 versionsMatch(Obsoleted1, Obsoleted2) &&
1095 IsUnavailable1 == IsUnavailable2);
1096}
1097
1098static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1099 bool &AvailabilityArgsMatch) {
1100 // This list is very small, so this need not be optimized.
1101 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1102 bool match = false;
1103 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
1104 // Matching attribute kind only. Except for Availability attributes,
1105 // we are not getting into details of the attributes. For all practical purposes
1106 // this is sufficient.
1107 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
1108 if (AvailabilityArgsMatch)
1109 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
1110 match = true;
1111 break;
1112 }
1113 }
1114 if (!match)
1115 return false;
1116 }
1117 return true;
1118}
1119
1120/// AttributesMatch - This routine checks list of attributes for two
1121/// decls. It returns false, if there is a mismatch in kind of
1122/// attributes seen in the decls. It returns true if the two decls
1123/// have list of same kind of attributes. Furthermore, when there
1124/// are availability attributes in the two decls, it sets the
1125/// AvailabilityArgsMatch to false if availability attributes have
1126/// different versions, etc.
1127static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1128 bool &AvailabilityArgsMatch) {
1129 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1130 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1131 return true;
1132 }
1133 AvailabilityArgsMatch = true;
1134 const AttrVec &Attrs1 = Decl1->getAttrs();
1135 const AttrVec &Attrs2 = Decl2->getAttrs();
1136 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1137 if (match && (Attrs2.size() > Attrs1.size()))
1138 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1139 return match;
1140}
1141
1142static bool IsValidIdentifier(ASTContext &Ctx,
1143 const char *Name) {
1144 if (!isIdentifierHead(Name[0]))
1145 return false;
1146 std::string NameString = Name;
1147 NameString[0] = toLowercase(NameString[0]);
1148 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1149 return II->getTokenID() == tok::identifier;
1150}
1151
1152bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
1153 ObjCContainerDecl *D,
1154 ObjCMethodDecl *Method) {
1155 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1156 Method->param_size() != 0)
1157 return false;
1158 // Is this method candidate to be a getter?
1159 QualType GRT = Method->getReturnType();
1160 if (GRT->isVoidType())
1161 return false;
1162
1163 Selector GetterSelector = Method->getSelector();
1164 ObjCInstanceTypeFamily OIT_Family =
1165 Selector::getInstTypeMethodFamily(GetterSelector);
1166
1167 if (OIT_Family != OIT_None)
1168 return false;
1169
1170 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1171 Selector SetterSelector =
1172 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1173 PP.getSelectorTable(),
1174 getterName);
1175 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
1176 unsigned LengthOfPrefix = 0;
1177 if (!SetterMethod) {
1178 // try a different naming convention for getter: isXxxxx
1179 StringRef getterNameString = getterName->getName();
1180 bool IsPrefix = getterNameString.startswith("is");
1181 // Note that we don't want to change an isXXX method of retainable object
1182 // type to property (readonly or otherwise).
1183 if (IsPrefix && GRT->isObjCRetainableType())
1184 return false;
1185 if (IsPrefix || getterNameString.startswith("get")) {
1186 LengthOfPrefix = (IsPrefix ? 2 : 3);
1187 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1188 // Make sure that first character after "is" or "get" prefix can
1189 // start an identifier.
1190 if (!IsValidIdentifier(Ctx, CGetterName))
1191 return false;
1192 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1193 getterName = &Ctx.Idents.get(CGetterName);
1194 SetterSelector =
1195 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1196 PP.getSelectorTable(),
1197 getterName);
1198 SetterMethod = D->getInstanceMethod(SetterSelector);
1199 }
1200 }
1201 }
1202
1203 if (SetterMethod) {
1204 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1205 return false;
1206 bool AvailabilityArgsMatch;
1207 if (SetterMethod->isDeprecated() ||
1208 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
1209 return false;
1210
1211 // Is this a valid setter, matching the target getter?
1212 QualType SRT = SetterMethod->getReturnType();
1213 if (!SRT->isVoidType())
1214 return false;
1215 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1216 QualType ArgType = argDecl->getType();
1217 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
1218 return false;
1219 edit::Commit commit(*Editor);
1220 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
1221 LengthOfPrefix,
1222 (ASTMigrateActions &
1223 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1224 (ASTMigrateActions &
1225 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1226 AvailabilityArgsMatch);
1227 Editor->commit(commit);
1228 return true;
1229 }
1230 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
1231 // Try a non-void method with no argument (and no setter or property of same name
1232 // as a 'readonly' property.
1233 edit::Commit commit(*Editor);
1234 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
1235 LengthOfPrefix,
1236 (ASTMigrateActions &
1237 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1238 (ASTMigrateActions &
1239 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1240 /*AvailabilityArgsMatch*/false);
1241 Editor->commit(commit);
1242 return true;
1243 }
1244 return false;
1245}
1246
1247void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1248 ObjCMethodDecl *OM) {
1249 if (OM->isImplicit() ||
1250 !OM->isInstanceMethod() ||
1251 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
1252 return;
1253
1254 QualType RT = OM->getReturnType();
1255 if (!TypeIsInnerPointer(RT) ||
1256 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1257 return;
1258
1259 edit::Commit commit(*Editor);
1260 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1261 Editor->commit(commit);
1262}
1263
1264void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1265 ObjCPropertyDecl *P) {
1266 QualType T = P->getType();
1267
1268 if (!TypeIsInnerPointer(T) ||
1269 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1270 return;
1271 edit::Commit commit(*Editor);
1272 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1273 Editor->commit(commit);
1274}
1275
1276void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
1277 ObjCContainerDecl *CDecl) {
1278 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
1279 return;
1280
1281 // migrate methods which can have instancetype as their result type.
1282 for (auto *Method : CDecl->methods()) {
1283 if (Method->isDeprecated())
1284 continue;
1285 migrateMethodInstanceType(Ctx, CDecl, Method);
1286 }
1287}
1288
1289void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1290 ObjCContainerDecl *CDecl,
1291 ObjCMethodDecl *OM,
1292 ObjCInstanceTypeFamily OIT_Family) {
1293 if (OM->isInstanceMethod() ||
1294 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1295 !OM->getReturnType()->isObjCIdType())
1296 return;
1297
1298 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1299 // NSYYYNamE with matching names be at least 3 characters long.
1300 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1301 if (!IDecl) {
1302 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1303 IDecl = CatDecl->getClassInterface();
1304 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1305 IDecl = ImpDecl->getClassInterface();
1306 }
1307 if (!IDecl)
1308 return;
1309
1310 std::string StringClassName = IDecl->getName();
1311 StringRef LoweredClassName(StringClassName);
1312 std::string StringLoweredClassName = LoweredClassName.lower();
1313 LoweredClassName = StringLoweredClassName;
1314
1315 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
1316 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1317 if (!MethodIdName)
1318 return;
1319
1320 std::string MethodName = MethodIdName->getName();
1321 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
1322 StringRef STRefMethodName(MethodName);
1323 size_t len = 0;
1324 if (STRefMethodName.startswith("standard"))
1325 len = strlen("standard");
1326 else if (STRefMethodName.startswith("shared"))
1327 len = strlen("shared");
1328 else if (STRefMethodName.startswith("default"))
1329 len = strlen("default");
1330 else
1331 return;
1332 MethodName = STRefMethodName.substr(len);
1333 }
1334 std::string MethodNameSubStr = MethodName.substr(0, 3);
1335 StringRef MethodNamePrefix(MethodNameSubStr);
1336 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1337 MethodNamePrefix = StringLoweredMethodNamePrefix;
1338 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1339 if (Ix == StringRef::npos)
1340 return;
1341 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1342 StringRef LoweredMethodName(MethodName);
1343 std::string StringLoweredMethodName = LoweredMethodName.lower();
1344 LoweredMethodName = StringLoweredMethodName;
1345 if (!LoweredMethodName.startswith(ClassNamePostfix))
1346 return;
1347 if (OIT_Family == OIT_ReturnsSelf)
1348 ReplaceWithClasstype(*this, OM);
1349 else
1350 ReplaceWithInstancetype(Ctx, *this, OM);
1351}
1352
1353static bool IsVoidStarType(QualType Ty) {
1354 if (!Ty->isPointerType())
1355 return false;
1356
1357 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1358 Ty = TD->getDecl()->getUnderlyingType();
1359
1360 // Is the type void*?
1361 const PointerType* PT = Ty->getAs<PointerType>();
1362 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1363 return true;
1364 return IsVoidStarType(PT->getPointeeType());
1365}
1366
1367/// AuditedType - This routine audits the type AT and returns false if it is one of known
1368/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1369/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
1370static bool AuditedType (QualType AT) {
1371 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
1372 return true;
1373 // FIXME. There isn't much we can say about CF pointer type; or is there?
1374 if (ento::coreFoundation::isCFObjectRef(AT) ||
1375 IsVoidStarType(AT) ||
1376 // If an ObjC object is type, assuming that it is not a CF function and
1377 // that it is an un-audited function.
1378 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
1379 return false;
1380 // All other pointers are assumed audited as harmless.
1381 return true;
1382}
1383
1384void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
1385 if (CFFunctionIBCandidates.empty())
1386 return;
1387 if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
1388 CFFunctionIBCandidates.clear();
1389 FileId = FileID();
1390 return;
1391 }
1392 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1393 const Decl *FirstFD = CFFunctionIBCandidates[0];
1394 const Decl *LastFD =
1395 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
1396 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1397 edit::Commit commit(*Editor);
1398 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1399 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1400 SourceLocation EndLoc = LastFD->getLocEnd();
1401 // get location just past end of function location.
1402 EndLoc = PP.getLocForEndOfToken(EndLoc);
1403 if (isa<FunctionDecl>(LastFD)) {
1404 // For Methods, EndLoc points to the ending semcolon. So,
1405 // not of these extra work is needed.
1406 Token Tok;
1407 // get locaiton of token that comes after end of function.
1408 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1409 if (!Failed)
1410 EndLoc = Tok.getLocation();
1411 }
1412 commit.insertAfterToken(EndLoc, PragmaString);
1413 Editor->commit(commit);
1414 FileId = FileID();
1415 CFFunctionIBCandidates.clear();
1416}
1417
1418void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1419 if (Decl->isDeprecated())
1420 return;
1421
1422 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1423 assert(CFFunctionIBCandidates.empty() &&(static_cast <bool> (CFFunctionIBCandidates.empty() &&
"Cannot have audited functions/methods inside user " "provided CF_IMPLICIT_BRIDGING_ENABLE"
) ? void (0) : __assert_fail ("CFFunctionIBCandidates.empty() && \"Cannot have audited functions/methods inside user \" \"provided CF_IMPLICIT_BRIDGING_ENABLE\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1425, __extension__ __PRETTY_FUNCTION__))
1424 "Cannot have audited functions/methods inside user "(static_cast <bool> (CFFunctionIBCandidates.empty() &&
"Cannot have audited functions/methods inside user " "provided CF_IMPLICIT_BRIDGING_ENABLE"
) ? void (0) : __assert_fail ("CFFunctionIBCandidates.empty() && \"Cannot have audited functions/methods inside user \" \"provided CF_IMPLICIT_BRIDGING_ENABLE\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1425, __extension__ __PRETTY_FUNCTION__))
1425 "provided CF_IMPLICIT_BRIDGING_ENABLE")(static_cast <bool> (CFFunctionIBCandidates.empty() &&
"Cannot have audited functions/methods inside user " "provided CF_IMPLICIT_BRIDGING_ENABLE"
) ? void (0) : __assert_fail ("CFFunctionIBCandidates.empty() && \"Cannot have audited functions/methods inside user \" \"provided CF_IMPLICIT_BRIDGING_ENABLE\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1425, __extension__ __PRETTY_FUNCTION__))
;
1426 return;
1427 }
1428
1429 // Finction must be annotated first.
1430 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1431 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1432 if (AuditKind == CF_BRIDGING_ENABLE) {
1433 CFFunctionIBCandidates.push_back(Decl);
1434 if (FileId.isInvalid())
1435 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1436 }
1437 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1438 if (!CFFunctionIBCandidates.empty()) {
1439 CFFunctionIBCandidates.push_back(Decl);
1440 if (FileId.isInvalid())
1441 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1442 }
1443 }
1444 else
1445 AnnotateImplicitBridging(Ctx);
1446 }
1447 else {
1448 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1449 AnnotateImplicitBridging(Ctx);
1450 }
1451}
1452
1453void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1454 const CallEffects &CE,
1455 const FunctionDecl *FuncDecl,
1456 bool ResultAnnotated) {
1457 // Annotate function.
1458 if (!ResultAnnotated) {
1459 RetEffect Ret = CE.getReturnValue();
1460 const char *AnnotationString = nullptr;
1461 if (Ret.getObjKind() == RetEffect::CF) {
1462 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1463 AnnotationString = " CF_RETURNS_RETAINED";
1464 else if (Ret.notOwned() &&
1465 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1466 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1467 }
1468 else if (Ret.getObjKind() == RetEffect::ObjC) {
1469 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1470 AnnotationString = " NS_RETURNS_RETAINED";
1471 }
1472
1473 if (AnnotationString) {
1474 edit::Commit commit(*Editor);
1475 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1476 Editor->commit(commit);
1477 }
1478 }
1479 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1480 unsigned i = 0;
1481 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1482 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1483 const ParmVarDecl *pd = *pi;
1484 ArgEffect AE = AEArgs[i];
1485 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1486 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1487 edit::Commit commit(*Editor);
1488 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1489 Editor->commit(commit);
1490 }
1491 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
1492 NSAPIObj->isMacroDefined("NS_CONSUMED")) {
1493 edit::Commit commit(*Editor);
1494 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1495 Editor->commit(commit);
1496 }
1497 }
1498}
1499
1500ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1501 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1502 ASTContext &Ctx,
1503 const FunctionDecl *FuncDecl) {
1504 if (FuncDecl->hasBody())
1505 return CF_BRIDGING_NONE;
1506
1507 CallEffects CE = CallEffects::getEffect(FuncDecl);
1508 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1509 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1510 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1511 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1512 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1513
1514 // Trivial case of when function is annotated and has no argument.
1515 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1516 return CF_BRIDGING_NONE;
1517
1518 bool ReturnCFAudited = false;
1519 if (!FuncIsReturnAnnotated) {
1520 RetEffect Ret = CE.getReturnValue();
1521 if (Ret.getObjKind() == RetEffect::CF &&
1522 (Ret.isOwned() || Ret.notOwned()))
1523 ReturnCFAudited = true;
1524 else if (!AuditedType(FuncDecl->getReturnType()))
1525 return CF_BRIDGING_NONE;
1526 }
1527
1528 // At this point result type is audited for potential inclusion.
1529 // Now, how about argument types.
1530 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1531 unsigned i = 0;
1532 bool ArgCFAudited = false;
1533 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1534 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1535 const ParmVarDecl *pd = *pi;
1536 ArgEffect AE = AEArgs[i];
1537 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1538 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
1539 ArgCFAudited = true;
1540 else if (AE == IncRef)
1541 ArgCFAudited = true;
1542 }
1543 else {
1544 QualType AT = pd->getType();
1545 if (!AuditedType(AT)) {
1546 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1547 return CF_BRIDGING_NONE;
1548 }
1549 }
1550 }
1551 if (ReturnCFAudited || ArgCFAudited)
1552 return CF_BRIDGING_ENABLE;
1553
1554 return CF_BRIDGING_MAY_INCLUDE;
1555}
1556
1557void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1558 ObjCContainerDecl *CDecl) {
1559 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1560 return;
1561
1562 // migrate methods which can have instancetype as their result type.
1563 for (const auto *Method : CDecl->methods())
1564 migrateCFAnnotation(Ctx, Method);
1565}
1566
1567void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1568 const CallEffects &CE,
1569 const ObjCMethodDecl *MethodDecl,
1570 bool ResultAnnotated) {
1571 // Annotate function.
1572 if (!ResultAnnotated) {
1573 RetEffect Ret = CE.getReturnValue();
1574 const char *AnnotationString = nullptr;
1575 if (Ret.getObjKind() == RetEffect::CF) {
1576 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1577 AnnotationString = " CF_RETURNS_RETAINED";
1578 else if (Ret.notOwned() &&
1579 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1580 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1581 }
1582 else if (Ret.getObjKind() == RetEffect::ObjC) {
1583 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1584 switch (OMF) {
1585 case clang::OMF_alloc:
1586 case clang::OMF_new:
1587 case clang::OMF_copy:
1588 case clang::OMF_init:
1589 case clang::OMF_mutableCopy:
1590 break;
1591
1592 default:
1593 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1594 AnnotationString = " NS_RETURNS_RETAINED";
1595 break;
1596 }
1597 }
1598
1599 if (AnnotationString) {
1600 edit::Commit commit(*Editor);
1601 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1602 Editor->commit(commit);
1603 }
1604 }
1605 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1606 unsigned i = 0;
1607 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1608 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1609 const ParmVarDecl *pd = *pi;
1610 ArgEffect AE = AEArgs[i];
1611 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1612 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1613 edit::Commit commit(*Editor);
1614 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1615 Editor->commit(commit);
1616 }
1617 }
1618}
1619
1620void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1621 ASTContext &Ctx,
1622 const ObjCMethodDecl *MethodDecl) {
1623 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1624 return;
1625
1626 CallEffects CE = CallEffects::getEffect(MethodDecl);
1627 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1628 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1629 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1630 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1631 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1632
1633 if (CE.getReceiver() == DecRefMsg &&
1634 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
1635 MethodDecl->getMethodFamily() != OMF_init &&
1636 MethodDecl->getMethodFamily() != OMF_release &&
1637 NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
1638 edit::Commit commit(*Editor);
1639 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1640 Editor->commit(commit);
1641 }
1642
1643 // Trivial case of when function is annotated and has no argument.
1644 if (MethodIsReturnAnnotated &&
1645 (MethodDecl->param_begin() == MethodDecl->param_end()))
1646 return;
1647
1648 if (!MethodIsReturnAnnotated) {
1649 RetEffect Ret = CE.getReturnValue();
1650 if ((Ret.getObjKind() == RetEffect::CF ||
1651 Ret.getObjKind() == RetEffect::ObjC) &&
1652 (Ret.isOwned() || Ret.notOwned())) {
1653 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1654 return;
1655 } else if (!AuditedType(MethodDecl->getReturnType()))
1656 return;
1657 }
1658
1659 // At this point result type is either annotated or audited.
1660 // Now, how about argument types.
1661 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1662 unsigned i = 0;
1663 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1664 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1665 const ParmVarDecl *pd = *pi;
1666 ArgEffect AE = AEArgs[i];
1667 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
1668 !AuditedType(pd->getType())) {
1669 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1670 return;
1671 }
1672 }
1673}
1674
1675namespace {
1676class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1677public:
1678 bool shouldVisitTemplateInstantiations() const { return false; }
1679 bool shouldWalkTypesOfTypeLocs() const { return false; }
1680
1681 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1682 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1683 if (E->getMethodFamily() == OMF_init)
1684 return false;
1685 }
1686 return true;
1687 }
1688};
1689} // end anonymous namespace
1690
1691static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1692 return !SuperInitChecker().TraverseStmt(MD->getBody());
1693}
1694
1695void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1696 ASTContext &Ctx,
1697 const ObjCImplementationDecl *ImplD) {
1698
1699 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1700 if (!IFace || IFace->hasDesignatedInitializers())
1701 return;
1702 if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
1703 return;
1704
1705 for (const auto *MD : ImplD->instance_methods()) {
1706 if (MD->isDeprecated() ||
1707 MD->getMethodFamily() != OMF_init ||
1708 MD->isDesignatedInitializerForTheInterface())
1709 continue;
1710 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1711 /*isInstance=*/true);
1712 if (!IFaceM)
1713 continue;
1714 if (hasSuperInitCall(MD)) {
1715 edit::Commit commit(*Editor);
1716 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1717 Editor->commit(commit);
1718 }
1719 }
1720}
1721
1722bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1723 SourceLocation Loc) {
1724 if (FoundationIncluded)
1725 return true;
1726 if (Loc.isInvalid())
1727 return false;
1728 auto *nsEnumId = &Ctx.Idents.get("NS_ENUM");
1729 if (PP.getMacroDefinitionAtLoc(nsEnumId, Loc)) {
1730 FoundationIncluded = true;
1731 return true;
1732 }
1733 edit::Commit commit(*Editor);
1734 if (Ctx.getLangOpts().Modules)
1735 commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
1736 else
1737 commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
1738 Editor->commit(commit);
1739 FoundationIncluded = true;
1740 return true;
1741}
1742
1743namespace {
1744
1745class RewritesReceiver : public edit::EditsReceiver {
1746 Rewriter &Rewrite;
1747
1748public:
1749 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1750
1751 void insert(SourceLocation loc, StringRef text) override {
1752 Rewrite.InsertText(loc, text);
1753 }
1754 void replace(CharSourceRange range, StringRef text) override {
1755 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1756 }
1757};
1758
1759class JSONEditWriter : public edit::EditsReceiver {
1760 SourceManager &SourceMgr;
1761 llvm::raw_ostream &OS;
1762
1763public:
1764 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1765 : SourceMgr(SM), OS(OS) {
1766 OS << "[\n";
1767 }
1768 ~JSONEditWriter() override { OS << "]\n"; }
1769
1770private:
1771 struct EntryWriter {
1772 SourceManager &SourceMgr;
1773 llvm::raw_ostream &OS;
1774
1775 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1776 : SourceMgr(SM), OS(OS) {
1777 OS << " {\n";
1778 }
1779 ~EntryWriter() {
1780 OS << " },\n";
1781 }
1782
1783 void writeLoc(SourceLocation Loc) {
1784 FileID FID;
1785 unsigned Offset;
1786 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
1787 assert(FID.isValid())(static_cast <bool> (FID.isValid()) ? void (0) : __assert_fail
("FID.isValid()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1787, __extension__ __PRETTY_FUNCTION__))
;
1788 SmallString<200> Path =
1789 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1790 llvm::sys::fs::make_absolute(Path);
1791 OS << " \"file\": \"";
1792 OS.write_escaped(Path.str()) << "\",\n";
1793 OS << " \"offset\": " << Offset << ",\n";
1794 }
1795
1796 void writeRemove(CharSourceRange Range) {
1797 assert(Range.isCharRange())(static_cast <bool> (Range.isCharRange()) ? void (0) : __assert_fail
("Range.isCharRange()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1797, __extension__ __PRETTY_FUNCTION__))
;
1798 std::pair<FileID, unsigned> Begin =
1799 SourceMgr.getDecomposedLoc(Range.getBegin());
1800 std::pair<FileID, unsigned> End =
1801 SourceMgr.getDecomposedLoc(Range.getEnd());
1802 assert(Begin.first == End.first)(static_cast <bool> (Begin.first == End.first) ? void (
0) : __assert_fail ("Begin.first == End.first", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1802, __extension__ __PRETTY_FUNCTION__))
;
1803 assert(Begin.second <= End.second)(static_cast <bool> (Begin.second <= End.second) ? void
(0) : __assert_fail ("Begin.second <= End.second", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1803, __extension__ __PRETTY_FUNCTION__))
;
1804 unsigned Length = End.second - Begin.second;
1805
1806 OS << " \"remove\": " << Length << ",\n";
1807 }
1808
1809 void writeText(StringRef Text) {
1810 OS << " \"text\": \"";
1811 OS.write_escaped(Text) << "\",\n";
1812 }
1813 };
1814
1815 void insert(SourceLocation Loc, StringRef Text) override {
1816 EntryWriter Writer(SourceMgr, OS);
1817 Writer.writeLoc(Loc);
1818 Writer.writeText(Text);
1819 }
1820
1821 void replace(CharSourceRange Range, StringRef Text) override {
1822 EntryWriter Writer(SourceMgr, OS);
1823 Writer.writeLoc(Range.getBegin());
1824 Writer.writeRemove(Range);
1825 Writer.writeText(Text);
1826 }
1827
1828 void remove(CharSourceRange Range) override {
1829 EntryWriter Writer(SourceMgr, OS);
1830 Writer.writeLoc(Range.getBegin());
1831 Writer.writeRemove(Range);
1832 }
1833};
1834
1835} // end anonymous namespace
1836
1837void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1838
1839 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1840 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
1841 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1842 D != DEnd; ++D) {
1843 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1844 if (FID.isValid())
1845 if (FileId.isValid() && FileId != FID) {
1846 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1847 AnnotateImplicitBridging(Ctx);
1848 }
1849
1850 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1851 if (canModify(CDecl))
1852 migrateObjCContainerDecl(Ctx, CDecl);
1853 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
1854 if (canModify(CatDecl))
1855 migrateObjCContainerDecl(Ctx, CatDecl);
1856 }
1857 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
1858 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
1859 if (canModify(PDecl))
1860 migrateObjCContainerDecl(Ctx, PDecl);
1861 }
1862 else if (const ObjCImplementationDecl *ImpDecl =
1863 dyn_cast<ObjCImplementationDecl>(*D)) {
1864 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1865 canModify(ImpDecl))
1866 migrateProtocolConformance(Ctx, ImpDecl);
1867 }
1868 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1869 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1870 continue;
1871 if (!canModify(ED))
1872 continue;
1873 DeclContext::decl_iterator N = D;
1874 if (++N != DEnd) {
1875 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1876 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1877 D++;
1878 }
1879 else
1880 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
1881 }
1882 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
1883 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1884 continue;
1885 if (!canModify(TD))
1886 continue;
1887 DeclContext::decl_iterator N = D;
1888 if (++N == DEnd)
1889 continue;
1890 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1891 if (canModify(ED)) {
1892 if (++N != DEnd)
1893 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1894 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1895 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1896 ++D; ++D;
1897 CacheObjCNSIntegerTypedefed(TD);
1898 continue;
1899 }
1900 }
1901 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1902 ++D;
1903 continue;
1904 }
1905 }
1906 }
1907 CacheObjCNSIntegerTypedefed(TD);
1908 }
1909 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1910 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1911 canModify(FD))
1912 migrateCFAnnotation(Ctx, FD);
1913 }
1914
1915 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1916 bool CanModify = canModify(CDecl);
1917 // migrate methods which can have instancetype as their result type.
1918 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1919 CanModify)
1920 migrateAllMethodInstaceType(Ctx, CDecl);
1921 // annotate methods with CF annotations.
1922 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1923 CanModify)
1924 migrateARCSafeAnnotation(Ctx, CDecl);
1925 }
1926
1927 if (const ObjCImplementationDecl *
1928 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
1929 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1930 canModify(ImplD))
1931 inferDesignatedInitializers(Ctx, ImplD);
1932 }
1933 }
1934 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1935 AnnotateImplicitBridging(Ctx);
1936 }
1937
1938 if (IsOutputFile) {
1939 std::error_code EC;
1940 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1941 if (EC) {
1942 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1943 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1944 << EC.message();
1945 return;
1946 }
1947
1948 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1949 Editor->applyRewrites(Writer);
1950 return;
1951 }
1952
1953 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1954 RewritesReceiver Rec(rewriter);
1955 Editor->applyRewrites(Rec);
1956
1957 for (Rewriter::buffer_iterator
1958 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1959 FileID FID = I->first;
1960 RewriteBuffer &buf = I->second;
1961 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1962 assert(file)(static_cast <bool> (file) ? void (0) : __assert_fail (
"file", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 1962, __extension__ __PRETTY_FUNCTION__))
;
1963 SmallString<512> newText;
1964 llvm::raw_svector_ostream vecOS(newText);
1965 buf.write(vecOS);
1966 std::unique_ptr<llvm::MemoryBuffer> memBuf(
1967 llvm::MemoryBuffer::getMemBufferCopy(
1968 StringRef(newText.data(), newText.size()), file->getName()));
1969 SmallString<64> filePath(file->getName());
1970 FileMgr.FixupRelativePath(filePath);
1971 Remapper.remap(filePath.str(), std::move(memBuf));
1972 }
1973
1974 if (IsOutputFile) {
1975 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1976 } else {
1977 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1978 }
1979}
1980
1981bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
1982 CI.getDiagnostics().setIgnoreAllWarnings(true);
1983 return true;
1984}
1985
1986static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1987 using namespace llvm::sys::fs;
1988 using namespace llvm::sys::path;
1989
1990 std::vector<std::string> Filenames;
1991 if (DirPath.empty() || !is_directory(DirPath))
1992 return Filenames;
1993
1994 std::error_code EC;
1995 directory_iterator DI = directory_iterator(DirPath, EC);
1996 directory_iterator DE;
1997 for (; !EC && DI != DE; DI = DI.increment(EC)) {
1998 if (is_regular_file(DI->path()))
1999 Filenames.push_back(filename(DI->path()));
2000 }
2001
2002 return Filenames;
2003}
2004
2005std::unique_ptr<ASTConsumer>
2006MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
2007 PPConditionalDirectiveRecord *
2008 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
2009 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
2010 unsigned ObjCMTOpts = ObjCMTAction;
2011 // These are companion flags, they do not enable transformations.
2012 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2013 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2014 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
2015 // If no specific option was given, enable literals+subscripting transforms
2016 // by default.
2017 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2018 FrontendOptions::ObjCMT_Subscripting;
2019 }
2020 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
2021 std::vector<std::string> WhiteList =
2022 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
2023 return llvm::make_unique<ObjCMigrateASTConsumer>(
2024 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2025 CI.getFileManager(), PPRec, CI.getPreprocessor(),
2026 /*isOutputFile=*/true, WhiteList);
2027}
2028
2029namespace {
2030struct EditEntry {
2031 const FileEntry *File;
2032 unsigned Offset;
2033 unsigned RemoveLen;
2034 std::string Text;
2035
2036 EditEntry() : File(), Offset(), RemoveLen() {}
2037};
2038} // end anonymous namespace
2039
2040namespace llvm {
2041template<> struct DenseMapInfo<EditEntry> {
2042 static inline EditEntry getEmptyKey() {
2043 EditEntry Entry;
2044 Entry.Offset = unsigned(-1);
2045 return Entry;
2046 }
2047 static inline EditEntry getTombstoneKey() {
2048 EditEntry Entry;
2049 Entry.Offset = unsigned(-2);
2050 return Entry;
2051 }
2052 static unsigned getHashValue(const EditEntry& Val) {
2053 llvm::FoldingSetNodeID ID;
2054 ID.AddPointer(Val.File);
2055 ID.AddInteger(Val.Offset);
2056 ID.AddInteger(Val.RemoveLen);
2057 ID.AddString(Val.Text);
2058 return ID.ComputeHash();
2059 }
2060 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2061 return LHS.File == RHS.File &&
2062 LHS.Offset == RHS.Offset &&
2063 LHS.RemoveLen == RHS.RemoveLen &&
2064 LHS.Text == RHS.Text;
2065 }
2066};
2067} // end namespace llvm
2068
2069namespace {
2070class RemapFileParser {
2071 FileManager &FileMgr;
2072
2073public:
2074 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2075
2076 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2077 using namespace llvm::yaml;
2078
2079 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2080 llvm::MemoryBuffer::getFile(File);
2081 if (!FileBufOrErr)
2082 return true;
2083
2084 llvm::SourceMgr SM;
2085 Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
2086 document_iterator I = YAMLStream.begin();
2087 if (I == YAMLStream.end())
2088 return true;
2089 Node *Root = I->getRoot();
2090 if (!Root)
2091 return true;
2092
2093 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2094 if (!SeqNode)
2095 return true;
2096
2097 for (SequenceNode::iterator
2098 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2099 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2100 if (!MapNode)
2101 continue;
2102 parseEdit(MapNode, Entries);
2103 }
2104
2105 return false;
2106 }
2107
2108private:
2109 void parseEdit(llvm::yaml::MappingNode *Node,
2110 SmallVectorImpl<EditEntry> &Entries) {
2111 using namespace llvm::yaml;
2112 EditEntry Entry;
2113 bool Ignore = false;
2114
2115 for (MappingNode::iterator
2116 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2117 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2118 if (!KeyString)
2119 continue;
2120 SmallString<10> KeyStorage;
2121 StringRef Key = KeyString->getValue(KeyStorage);
2122
2123 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2124 if (!ValueString)
2125 continue;
2126 SmallString<64> ValueStorage;
2127 StringRef Val = ValueString->getValue(ValueStorage);
2128
2129 if (Key == "file") {
2130 const FileEntry *FE = FileMgr.getFile(Val);
2131 if (!FE)
2132 Ignore = true;
2133 Entry.File = FE;
2134 } else if (Key == "offset") {
2135 if (Val.getAsInteger(10, Entry.Offset))
2136 Ignore = true;
2137 } else if (Key == "remove") {
2138 if (Val.getAsInteger(10, Entry.RemoveLen))
2139 Ignore = true;
2140 } else if (Key == "text") {
2141 Entry.Text = Val;
2142 }
2143 }
2144
2145 if (!Ignore)
2146 Entries.push_back(Entry);
2147 }
2148};
2149} // end anonymous namespace
2150
2151static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
2152 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2153 << Err.str();
2154 return true;
2155}
2156
2157static std::string applyEditsToTemp(const FileEntry *FE,
2158 ArrayRef<EditEntry> Edits,
2159 FileManager &FileMgr,
2160 DiagnosticsEngine &Diag) {
2161 using namespace llvm::sys;
2162
2163 SourceManager SM(Diag, FileMgr);
2164 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2165 LangOptions LangOpts;
2166 edit::EditedSource Editor(SM, LangOpts);
2167 for (ArrayRef<EditEntry>::iterator
2168 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2169 const EditEntry &Entry = *I;
2170 assert(Entry.File == FE)(static_cast <bool> (Entry.File == FE) ? void (0) : __assert_fail
("Entry.File == FE", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/ARCMigrate/ObjCMT.cpp"
, 2170, __extension__ __PRETTY_FUNCTION__))
;
2171 SourceLocation Loc =
2172 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2173 CharSourceRange Range;
2174 if (Entry.RemoveLen != 0) {
2175 Range = CharSourceRange::getCharRange(Loc,
2176 Loc.getLocWithOffset(Entry.RemoveLen));
2177 }
2178
2179 edit::Commit commit(Editor);
2180 if (Range.isInvalid()) {
2181 commit.insert(Loc, Entry.Text);
2182 } else if (Entry.Text.empty()) {
2183 commit.remove(Range);
2184 } else {
2185 commit.replace(Range, Entry.Text);
2186 }
2187 Editor.commit(commit);
2188 }
2189
2190 Rewriter rewriter(SM, LangOpts);
2191 RewritesReceiver Rec(rewriter);
2192 Editor.applyRewrites(Rec, /*adjustRemovals=*/false);
2193
2194 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2195 SmallString<512> NewText;
2196 llvm::raw_svector_ostream OS(NewText);
2197 Buf->write(OS);
2198
2199 SmallString<64> TempPath;
2200 int FD;
2201 if (fs::createTemporaryFile(path::filename(FE->getName()),
2202 path::extension(FE->getName()).drop_front(), FD,
2203 TempPath)) {
2204 reportDiag("Could not create file: " + TempPath.str(), Diag);
2205 return std::string();
2206 }
2207
2208 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2209 TmpOut.write(NewText.data(), NewText.size());
2210 TmpOut.close();
2211
2212 return TempPath.str();
2213}
2214
2215bool arcmt::getFileRemappingsFromFileList(
2216 std::vector<std::pair<std::string,std::string> > &remap,
2217 ArrayRef<StringRef> remapFiles,
2218 DiagnosticConsumer *DiagClient) {
2219 bool hasErrorOccurred = false;
2220
2221 FileSystemOptions FSOpts;
2222 FileManager FileMgr(FSOpts);
2223 RemapFileParser Parser(FileMgr);
2224
2225 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2226 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2227 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2228 DiagClient, /*ShouldOwnClient=*/false));
2229
2230 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2231 FileEditEntriesTy;
2232 FileEditEntriesTy FileEditEntries;
2233
2234 llvm::DenseSet<EditEntry> EntriesSet;
2235
2236 for (ArrayRef<StringRef>::iterator
2237 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2238 SmallVector<EditEntry, 16> Entries;
2239 if (Parser.parse(*I, Entries))
2240 continue;
2241
2242 for (SmallVectorImpl<EditEntry>::iterator
2243 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2244 EditEntry &Entry = *EI;
2245 if (!Entry.File)
2246 continue;
2247 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2248 Insert = EntriesSet.insert(Entry);
2249 if (!Insert.second)
2250 continue;
2251
2252 FileEditEntries[Entry.File].push_back(Entry);
2253 }
2254 }
2255
2256 for (FileEditEntriesTy::iterator
2257 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2258 std::string TempFile = applyEditsToTemp(I->first, I->second,
2259 FileMgr, *Diags);
2260 if (TempFile.empty()) {
2261 hasErrorOccurred = true;
2262 continue;
2263 }
2264
2265 remap.emplace_back(I->first->getName(), TempFile);
2266 }
2267
2268 return hasErrorOccurred;
2269}

/usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/unique_ptr.h

1// unique_ptr implementation -*- C++ -*-
2
3// Copyright (C) 2008-2017 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/unique_ptr.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{memory}
28 */
29
30#ifndef _UNIQUE_PTR_H1
31#define _UNIQUE_PTR_H1 1
32
33#include <bits/c++config.h>
34#include <debug/assertions.h>
35#include <type_traits>
36#include <utility>
37#include <tuple>
38#include <bits/stl_function.h>
39#include <bits/functional_hash.h>
40
41namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
42{
43_GLIBCXX_BEGIN_NAMESPACE_VERSION
44
45 /**
46 * @addtogroup pointer_abstractions
47 * @{
48 */
49
50#if _GLIBCXX_USE_DEPRECATED1
51 template<typename> class auto_ptr;
52#endif
53
54 /// Primary template of default_delete, used by unique_ptr
55 template<typename _Tp>
56 struct default_delete
57 {
58 /// Default constructor
59 constexpr default_delete() noexcept = default;
60
61 /** @brief Converting constructor.
62 *
63 * Allows conversion from a deleter for arrays of another type, @p _Up,
64 * only if @p _Up* is convertible to @p _Tp*.
65 */
66 template<typename _Up, typename = typename
67 enable_if<is_convertible<_Up*, _Tp*>::value>::type>
68 default_delete(const default_delete<_Up>&) noexcept { }
69
70 /// Calls @c delete @p __ptr
71 void
72 operator()(_Tp* __ptr) const
73 {
74 static_assert(!is_void<_Tp>::value,
75 "can't delete pointer to incomplete type");
76 static_assert(sizeof(_Tp)>0,
77 "can't delete pointer to incomplete type");
78 delete __ptr;
5
Memory is released
79 }
80 };
81
82 // _GLIBCXX_RESOLVE_LIB_DEFECTS
83 // DR 740 - omit specialization for array objects with a compile time length
84 /// Specialization for arrays, default_delete.
85 template<typename _Tp>
86 struct default_delete<_Tp[]>
87 {
88 public:
89 /// Default constructor
90 constexpr default_delete() noexcept = default;
91
92 /** @brief Converting constructor.
93 *
94 * Allows conversion from a deleter for arrays of another type, such as
95 * a const-qualified version of @p _Tp.
96 *
97 * Conversions from types derived from @c _Tp are not allowed because
98 * it is unsafe to @c delete[] an array of derived types through a
99 * pointer to the base type.
100 */
101 template<typename _Up, typename = typename
102 enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type>
103 default_delete(const default_delete<_Up[]>&) noexcept { }
104
105 /// Calls @c delete[] @p __ptr
106 template<typename _Up>
107 typename enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value>::type
108 operator()(_Up* __ptr) const
109 {
110 static_assert(sizeof(_Tp)>0,
111 "can't delete pointer to incomplete type");
112 delete [] __ptr;
113 }
114 };
115
116 template <typename _Tp, typename _Dp>
117 class __uniq_ptr_impl
118 {
119 template <typename _Up, typename _Ep, typename = void>
120 struct _Ptr
121 {
122 using type = _Up*;
123 };
124
125 template <typename _Up, typename _Ep>
126 struct
127 _Ptr<_Up, _Ep, __void_t<typename remove_reference<_Ep>::type::pointer>>
128 {
129 using type = typename remove_reference<_Ep>::type::pointer;
130 };
131
132 public:
133 using _DeleterConstraint = enable_if<
134 __and_<__not_<is_pointer<_Dp>>,
135 is_default_constructible<_Dp>>::value>;
136
137 using pointer = typename _Ptr<_Tp, _Dp>::type;
138
139 __uniq_ptr_impl() = default;
140 __uniq_ptr_impl(pointer __p) : _M_t() { _M_ptr() = __p; }
141
142 template<typename _Del>
143 __uniq_ptr_impl(pointer __p, _Del&& __d)
144 : _M_t(__p, std::forward<_Del>(__d)) { }
145
146 pointer& _M_ptr() { return std::get<0>(_M_t); }
147 pointer _M_ptr() const { return std::get<0>(_M_t); }
148 _Dp& _M_deleter() { return std::get<1>(_M_t); }
149 const _Dp& _M_deleter() const { return std::get<1>(_M_t); }
150
151 private:
152 tuple<pointer, _Dp> _M_t;
153 };
154
155 /// 20.7.1.2 unique_ptr for single objects.
156 template <typename _Tp, typename _Dp = default_delete<_Tp>>
157 class unique_ptr
158 {
159 template <class _Up>
160 using _DeleterConstraint =
161 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
162
163 __uniq_ptr_impl<_Tp, _Dp> _M_t;
164
165 public:
166 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
167 using element_type = _Tp;
168 using deleter_type = _Dp;
169
170 // helper template for detecting a safe conversion from another
171 // unique_ptr
172 template<typename _Up, typename _Ep>
173 using __safe_conversion_up = __and_<
174 is_convertible<typename unique_ptr<_Up, _Ep>::pointer, pointer>,
175 __not_<is_array<_Up>>,
176 __or_<__and_<is_reference<deleter_type>,
177 is_same<deleter_type, _Ep>>,
178 __and_<__not_<is_reference<deleter_type>>,
179 is_convertible<_Ep, deleter_type>>
180 >
181 >;
182
183 // Constructors.
184
185 /// Default constructor, creates a unique_ptr that owns nothing.
186 template <typename _Up = _Dp,
187 typename = _DeleterConstraint<_Up>>
188 constexpr unique_ptr() noexcept
189 : _M_t()
190 { }
191
192 /** Takes ownership of a pointer.
193 *
194 * @param __p A pointer to an object of @c element_type
195 *
196 * The deleter will be value-initialized.
197 */
198 template <typename _Up = _Dp,
199 typename = _DeleterConstraint<_Up>>
200 explicit
201 unique_ptr(pointer __p) noexcept
202 : _M_t(__p)
203 { }
204
205 /** Takes ownership of a pointer.
206 *
207 * @param __p A pointer to an object of @c element_type
208 * @param __d A reference to a deleter.
209 *
210 * The deleter will be initialized with @p __d
211 */
212 unique_ptr(pointer __p,
213 typename conditional<is_reference<deleter_type>::value,
214 deleter_type, const deleter_type&>::type __d) noexcept
215 : _M_t(__p, __d) { }
216
217 /** Takes ownership of a pointer.
218 *
219 * @param __p A pointer to an object of @c element_type
220 * @param __d An rvalue reference to a deleter.
221 *
222 * The deleter will be initialized with @p std::move(__d)
223 */
224 unique_ptr(pointer __p,
225 typename remove_reference<deleter_type>::type&& __d) noexcept
226 : _M_t(std::move(__p), std::move(__d))
227 { static_assert(!std::is_reference<deleter_type>::value,
228 "rvalue deleter bound to reference"); }
229
230 /// Creates a unique_ptr that owns nothing.
231 template <typename _Up = _Dp,
232 typename = _DeleterConstraint<_Up>>
233 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
234
235 // Move constructors.
236
237 /// Move constructor.
238 unique_ptr(unique_ptr&& __u) noexcept
239 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
240
241 /** @brief Converting constructor from another type
242 *
243 * Requires that the pointer owned by @p __u is convertible to the
244 * type of pointer owned by this object, @p __u does not own an array,
245 * and @p __u has a compatible deleter type.
246 */
247 template<typename _Up, typename _Ep, typename = _Require<
248 __safe_conversion_up<_Up, _Ep>,
249 typename conditional<is_reference<_Dp>::value,
250 is_same<_Ep, _Dp>,
251 is_convertible<_Ep, _Dp>>::type>>
252 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
253 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
254 { }
255
256#if _GLIBCXX_USE_DEPRECATED1
257 /// Converting constructor from @c auto_ptr
258 template<typename _Up, typename = _Require<
259 is_convertible<_Up*, _Tp*>, is_same<_Dp, default_delete<_Tp>>>>
260 unique_ptr(auto_ptr<_Up>&& __u) noexcept;
261#endif
262
263 /// Destructor, invokes the deleter if the stored pointer is not null.
264 ~unique_ptr() noexcept
265 {
266 auto& __ptr = _M_t._M_ptr();
267 if (__ptr != nullptr)
3
Taking true branch
268 get_deleter()(__ptr);
4
Calling 'default_delete::operator()'
6
Returning; memory was released via 2nd parameter
269 __ptr = pointer();
270 }
271
272 // Assignment.
273
274 /** @brief Move assignment operator.
275 *
276 * @param __u The object to transfer ownership from.
277 *
278 * Invokes the deleter first if this object owns a pointer.
279 */
280 unique_ptr&
281 operator=(unique_ptr&& __u) noexcept
282 {
283 reset(__u.release());
284 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
285 return *this;
286 }
287
288 /** @brief Assignment from another type.
289 *
290 * @param __u The object to transfer ownership from, which owns a
291 * convertible pointer to a non-array object.
292 *
293 * Invokes the deleter first if this object owns a pointer.
294 */
295 template<typename _Up, typename _Ep>
296 typename enable_if< __and_<
297 __safe_conversion_up<_Up, _Ep>,
298 is_assignable<deleter_type&, _Ep&&>
299 >::value,
300 unique_ptr&>::type
301 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
302 {
303 reset(__u.release());
304 get_deleter() = std::forward<_Ep>(__u.get_deleter());
305 return *this;
306 }
307
308 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
309 unique_ptr&
310 operator=(nullptr_t) noexcept
311 {
312 reset();
313 return *this;
314 }
315
316 // Observers.
317
318 /// Dereference the stored pointer.
319 typename add_lvalue_reference<element_type>::type
320 operator*() const
321 {
322 __glibcxx_assert(get() != pointer());
323 return *get();
324 }
325
326 /// Return the stored pointer.
327 pointer
328 operator->() const noexcept
329 {
330 _GLIBCXX_DEBUG_PEDASSERT(get() != pointer());
331 return get();
332 }
333
334 /// Return the stored pointer.
335 pointer
336 get() const noexcept
337 { return _M_t._M_ptr(); }
338
339 /// Return a reference to the stored deleter.
340 deleter_type&
341 get_deleter() noexcept
342 { return _M_t._M_deleter(); }
343
344 /// Return a reference to the stored deleter.
345 const deleter_type&
346 get_deleter() const noexcept
347 { return _M_t._M_deleter(); }
348
349 /// Return @c true if the stored pointer is not null.
350 explicit operator bool() const noexcept
351 { return get() == pointer() ? false : true; }
352
353 // Modifiers.
354
355 /// Release ownership of any stored pointer.
356 pointer
357 release() noexcept
358 {
359 pointer __p = get();
360 _M_t._M_ptr() = pointer();
361 return __p;
362 }
363
364 /** @brief Replace the stored pointer.
365 *
366 * @param __p The new pointer to store.
367 *
368 * The deleter will be invoked if a pointer is already owned.
369 */
370 void
371 reset(pointer __p = pointer()) noexcept
372 {
373 using std::swap;
374 swap(_M_t._M_ptr(), __p);
375 if (__p != pointer())
376 get_deleter()(__p);
377 }
378
379 /// Exchange the pointer and deleter with another object.
380 void
381 swap(unique_ptr& __u) noexcept
382 {
383 using std::swap;
384 swap(_M_t, __u._M_t);
385 }
386
387 // Disable copy from lvalue.
388 unique_ptr(const unique_ptr&) = delete;
389 unique_ptr& operator=(const unique_ptr&) = delete;
390 };
391
392 /// 20.7.1.3 unique_ptr for array objects with a runtime length
393 // [unique.ptr.runtime]
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // DR 740 - omit specialization for array objects with a compile time length
396 template<typename _Tp, typename _Dp>
397 class unique_ptr<_Tp[], _Dp>
398 {
399 template <typename _Up>
400 using _DeleterConstraint =
401 typename __uniq_ptr_impl<_Tp, _Up>::_DeleterConstraint::type;
402
403 __uniq_ptr_impl<_Tp, _Dp> _M_t;
404
405 template<typename _Up>
406 using __remove_cv = typename remove_cv<_Up>::type;
407
408 // like is_base_of<_Tp, _Up> but false if unqualified types are the same
409 template<typename _Up>
410 using __is_derived_Tp
411 = __and_< is_base_of<_Tp, _Up>,
412 __not_<is_same<__remove_cv<_Tp>, __remove_cv<_Up>>> >;
413
414 public:
415 using pointer = typename __uniq_ptr_impl<_Tp, _Dp>::pointer;
416 using element_type = _Tp;
417 using deleter_type = _Dp;
418
419 // helper template for detecting a safe conversion from another
420 // unique_ptr
421 template<typename _Up, typename _Ep,
422 typename _Up_up = unique_ptr<_Up, _Ep>,
423 typename _Up_element_type = typename _Up_up::element_type>
424 using __safe_conversion_up = __and_<
425 is_array<_Up>,
426 is_same<pointer, element_type*>,
427 is_same<typename _Up_up::pointer, _Up_element_type*>,
428 is_convertible<_Up_element_type(*)[], element_type(*)[]>,
429 __or_<__and_<is_reference<deleter_type>, is_same<deleter_type, _Ep>>,
430 __and_<__not_<is_reference<deleter_type>>,
431 is_convertible<_Ep, deleter_type>>>
432 >;
433
434 // helper template for detecting a safe conversion from a raw pointer
435 template<typename _Up>
436 using __safe_conversion_raw = __and_<
437 __or_<__or_<is_same<_Up, pointer>,
438 is_same<_Up, nullptr_t>>,
439 __and_<is_pointer<_Up>,
440 is_same<pointer, element_type*>,
441 is_convertible<
442 typename remove_pointer<_Up>::type(*)[],
443 element_type(*)[]>
444 >
445 >
446 >;
447
448 // Constructors.
449
450 /// Default constructor, creates a unique_ptr that owns nothing.
451 template <typename _Up = _Dp,
452 typename = _DeleterConstraint<_Up>>
453 constexpr unique_ptr() noexcept
454 : _M_t()
455 { }
456
457 /** Takes ownership of a pointer.
458 *
459 * @param __p A pointer to an array of a type safely convertible
460 * to an array of @c element_type
461 *
462 * The deleter will be value-initialized.
463 */
464 template<typename _Up,
465 typename _Vp = _Dp,
466 typename = _DeleterConstraint<_Vp>,
467 typename = typename enable_if<
468 __safe_conversion_raw<_Up>::value, bool>::type>
469 explicit
470 unique_ptr(_Up __p) noexcept
471 : _M_t(__p)
472 { }
473
474 /** Takes ownership of a pointer.
475 *
476 * @param __p A pointer to an array of a type safely convertible
477 * to an array of @c element_type
478 * @param __d A reference to a deleter.
479 *
480 * The deleter will be initialized with @p __d
481 */
482 template<typename _Up,
483 typename = typename enable_if<
484 __safe_conversion_raw<_Up>::value, bool>::type>
485 unique_ptr(_Up __p,
486 typename conditional<is_reference<deleter_type>::value,
487 deleter_type, const deleter_type&>::type __d) noexcept
488 : _M_t(__p, __d) { }
489
490 /** Takes ownership of a pointer.
491 *
492 * @param __p A pointer to an array of a type safely convertible
493 * to an array of @c element_type
494 * @param __d A reference to a deleter.
495 *
496 * The deleter will be initialized with @p std::move(__d)
497 */
498 template<typename _Up,
499 typename = typename enable_if<
500 __safe_conversion_raw<_Up>::value, bool>::type>
501 unique_ptr(_Up __p, typename
502 remove_reference<deleter_type>::type&& __d) noexcept
503 : _M_t(std::move(__p), std::move(__d))
504 { static_assert(!is_reference<deleter_type>::value,
505 "rvalue deleter bound to reference"); }
506
507 /// Move constructor.
508 unique_ptr(unique_ptr&& __u) noexcept
509 : _M_t(__u.release(), std::forward<deleter_type>(__u.get_deleter())) { }
510
511 /// Creates a unique_ptr that owns nothing.
512 template <typename _Up = _Dp,
513 typename = _DeleterConstraint<_Up>>
514 constexpr unique_ptr(nullptr_t) noexcept : unique_ptr() { }
515
516 template<typename _Up, typename _Ep,
517 typename = _Require<__safe_conversion_up<_Up, _Ep>>>
518 unique_ptr(unique_ptr<_Up, _Ep>&& __u) noexcept
519 : _M_t(__u.release(), std::forward<_Ep>(__u.get_deleter()))
520 { }
521
522 /// Destructor, invokes the deleter if the stored pointer is not null.
523 ~unique_ptr()
524 {
525 auto& __ptr = _M_t._M_ptr();
526 if (__ptr != nullptr)
527 get_deleter()(__ptr);
528 __ptr = pointer();
529 }
530
531 // Assignment.
532
533 /** @brief Move assignment operator.
534 *
535 * @param __u The object to transfer ownership from.
536 *
537 * Invokes the deleter first if this object owns a pointer.
538 */
539 unique_ptr&
540 operator=(unique_ptr&& __u) noexcept
541 {
542 reset(__u.release());
543 get_deleter() = std::forward<deleter_type>(__u.get_deleter());
544 return *this;
545 }
546
547 /** @brief Assignment from another type.
548 *
549 * @param __u The object to transfer ownership from, which owns a
550 * convertible pointer to an array object.
551 *
552 * Invokes the deleter first if this object owns a pointer.
553 */
554 template<typename _Up, typename _Ep>
555 typename
556 enable_if<__and_<__safe_conversion_up<_Up, _Ep>,
557 is_assignable<deleter_type&, _Ep&&>
558 >::value,
559 unique_ptr&>::type
560 operator=(unique_ptr<_Up, _Ep>&& __u) noexcept
561 {
562 reset(__u.release());
563 get_deleter() = std::forward<_Ep>(__u.get_deleter());
564 return *this;
565 }
566
567 /// Reset the %unique_ptr to empty, invoking the deleter if necessary.
568 unique_ptr&
569 operator=(nullptr_t) noexcept
570 {
571 reset();
572 return *this;
573 }
574
575 // Observers.
576
577 /// Access an element of owned array.
578 typename std::add_lvalue_reference<element_type>::type
579 operator[](size_t __i) const
580 {
581 __glibcxx_assert(get() != pointer());
582 return get()[__i];
583 }
584
585 /// Return the stored pointer.
586 pointer
587 get() const noexcept
588 { return _M_t._M_ptr(); }
589
590 /// Return a reference to the stored deleter.
591 deleter_type&
592 get_deleter() noexcept
593 { return _M_t._M_deleter(); }
594
595 /// Return a reference to the stored deleter.
596 const deleter_type&
597 get_deleter() const noexcept
598 { return _M_t._M_deleter(); }
599
600 /// Return @c true if the stored pointer is not null.
601 explicit operator bool() const noexcept
602 { return get() == pointer() ? false : true; }
603
604 // Modifiers.
605
606 /// Release ownership of any stored pointer.
607 pointer
608 release() noexcept
609 {
610 pointer __p = get();
611 _M_t._M_ptr() = pointer();
612 return __p;
613 }
614
615 /** @brief Replace the stored pointer.
616 *
617 * @param __p The new pointer to store.
618 *
619 * The deleter will be invoked if a pointer is already owned.
620 */
621 template <typename _Up,
622 typename = _Require<
623 __or_<is_same<_Up, pointer>,
624 __and_<is_same<pointer, element_type*>,
625 is_pointer<_Up>,
626 is_convertible<
627 typename remove_pointer<_Up>::type(*)[],
628 element_type(*)[]
629 >
630 >
631 >
632 >>
633 void
634 reset(_Up __p) noexcept
635 {
636 pointer __ptr = __p;
637 using std::swap;
638 swap(_M_t._M_ptr(), __ptr);
639 if (__ptr != nullptr)
640 get_deleter()(__ptr);
641 }
642
643 void reset(nullptr_t = nullptr) noexcept
644 {
645 reset(pointer());
646 }
647
648 /// Exchange the pointer and deleter with another object.
649 void
650 swap(unique_ptr& __u) noexcept
651 {
652 using std::swap;
653 swap(_M_t, __u._M_t);
654 }
655
656 // Disable copy from lvalue.
657 unique_ptr(const unique_ptr&) = delete;
658 unique_ptr& operator=(const unique_ptr&) = delete;
659 };
660
661 template<typename _Tp, typename _Dp>
662 inline
663#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
664 // Constrained free swap overload, see p0185r1
665 typename enable_if<__is_swappable<_Dp>::value>::type
666#else
667 void
668#endif
669 swap(unique_ptr<_Tp, _Dp>& __x,
670 unique_ptr<_Tp, _Dp>& __y) noexcept
671 { __x.swap(__y); }
672
673#if __cplusplus201103L > 201402L || !defined(__STRICT_ANSI__1) // c++1z or gnu++11
674 template<typename _Tp, typename _Dp>
675 typename enable_if<!__is_swappable<_Dp>::value>::type
676 swap(unique_ptr<_Tp, _Dp>&,
677 unique_ptr<_Tp, _Dp>&) = delete;
678#endif
679
680 template<typename _Tp, typename _Dp,
681 typename _Up, typename _Ep>
682 inline bool
683 operator==(const unique_ptr<_Tp, _Dp>& __x,
684 const unique_ptr<_Up, _Ep>& __y)
685 { return __x.get() == __y.get(); }
686
687 template<typename _Tp, typename _Dp>
688 inline bool
689 operator==(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
690 { return !__x; }
691
692 template<typename _Tp, typename _Dp>
693 inline bool
694 operator==(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
695 { return !__x; }
696
697 template<typename _Tp, typename _Dp,
698 typename _Up, typename _Ep>
699 inline bool
700 operator!=(const unique_ptr<_Tp, _Dp>& __x,
701 const unique_ptr<_Up, _Ep>& __y)
702 { return __x.get() != __y.get(); }
703
704 template<typename _Tp, typename _Dp>
705 inline bool
706 operator!=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t) noexcept
707 { return (bool)__x; }
708
709 template<typename _Tp, typename _Dp>
710 inline bool
711 operator!=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x) noexcept
712 { return (bool)__x; }
713
714 template<typename _Tp, typename _Dp,
715 typename _Up, typename _Ep>
716 inline bool
717 operator<(const unique_ptr<_Tp, _Dp>& __x,
718 const unique_ptr<_Up, _Ep>& __y)
719 {
720 typedef typename
721 std::common_type<typename unique_ptr<_Tp, _Dp>::pointer,
722 typename unique_ptr<_Up, _Ep>::pointer>::type _CT;
723 return std::less<_CT>()(__x.get(), __y.get());
724 }
725
726 template<typename _Tp, typename _Dp>
727 inline bool
728 operator<(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
729 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
730 nullptr); }
731
732 template<typename _Tp, typename _Dp>
733 inline bool
734 operator<(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
735 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
736 __x.get()); }
737
738 template<typename _Tp, typename _Dp,
739 typename _Up, typename _Ep>
740 inline bool
741 operator<=(const unique_ptr<_Tp, _Dp>& __x,
742 const unique_ptr<_Up, _Ep>& __y)
743 { return !(__y < __x); }
744
745 template<typename _Tp, typename _Dp>
746 inline bool
747 operator<=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
748 { return !(nullptr < __x); }
749
750 template<typename _Tp, typename _Dp>
751 inline bool
752 operator<=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
753 { return !(__x < nullptr); }
754
755 template<typename _Tp, typename _Dp,
756 typename _Up, typename _Ep>
757 inline bool
758 operator>(const unique_ptr<_Tp, _Dp>& __x,
759 const unique_ptr<_Up, _Ep>& __y)
760 { return (__y < __x); }
761
762 template<typename _Tp, typename _Dp>
763 inline bool
764 operator>(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
765 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(nullptr,
766 __x.get()); }
767
768 template<typename _Tp, typename _Dp>
769 inline bool
770 operator>(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
771 { return std::less<typename unique_ptr<_Tp, _Dp>::pointer>()(__x.get(),
772 nullptr); }
773
774 template<typename _Tp, typename _Dp,
775 typename _Up, typename _Ep>
776 inline bool
777 operator>=(const unique_ptr<_Tp, _Dp>& __x,
778 const unique_ptr<_Up, _Ep>& __y)
779 { return !(__x < __y); }
780
781 template<typename _Tp, typename _Dp>
782 inline bool
783 operator>=(const unique_ptr<_Tp, _Dp>& __x, nullptr_t)
784 { return !(__x < nullptr); }
785
786 template<typename _Tp, typename _Dp>
787 inline bool
788 operator>=(nullptr_t, const unique_ptr<_Tp, _Dp>& __x)
789 { return !(nullptr < __x); }
790
791 /// std::hash specialization for unique_ptr.
792 template<typename _Tp, typename _Dp>
793 struct hash<unique_ptr<_Tp, _Dp>>
794 : public __hash_base<size_t, unique_ptr<_Tp, _Dp>>,
795 private __poison_hash<typename unique_ptr<_Tp, _Dp>::pointer>
796 {
797 size_t
798 operator()(const unique_ptr<_Tp, _Dp>& __u) const noexcept
799 {
800 typedef unique_ptr<_Tp, _Dp> _UP;
801 return std::hash<typename _UP::pointer>()(__u.get());
802 }
803 };
804
805#if __cplusplus201103L > 201103L
806
807#define __cpp_lib_make_unique 201304
808
809 template<typename _Tp>
810 struct _MakeUniq
811 { typedef unique_ptr<_Tp> __single_object; };
812
813 template<typename _Tp>
814 struct _MakeUniq<_Tp[]>
815 { typedef unique_ptr<_Tp[]> __array; };
816
817 template<typename _Tp, size_t _Bound>
818 struct _MakeUniq<_Tp[_Bound]>
819 { struct __invalid_type { }; };
820
821 /// std::make_unique for single objects
822 template<typename _Tp, typename... _Args>
823 inline typename _MakeUniq<_Tp>::__single_object
824 make_unique(_Args&&... __args)
825 { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
826
827 /// std::make_unique for arrays of unknown bound
828 template<typename _Tp>
829 inline typename _MakeUniq<_Tp>::__array
830 make_unique(size_t __num)
831 { return unique_ptr<_Tp>(new remove_extent_t<_Tp>[__num]()); }
832
833 /// Disable std::make_unique for arrays of known bound
834 template<typename _Tp, typename... _Args>
835 inline typename _MakeUniq<_Tp>::__invalid_type
836 make_unique(_Args&&...) = delete;
837#endif
838
839 // @} group pointer_abstractions
840
841_GLIBCXX_END_NAMESPACE_VERSION
842} // namespace
843
844#endif /* _UNIQUE_PTR_H */

/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
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// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39#ifdef EXPENSIVE_CHECKS
40#include <random> // for std::mt19937
41#endif
42
43namespace llvm {
44
45// Only used by compiler if both template types are the same. Useful when
46// using SFINAE to test for the existence of member functions.
47template <typename T, T> struct SameType;
48
49namespace detail {
50
51template <typename RangeT>
52using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
53
54template <typename RangeT>
55using ValueOfRange = typename std::remove_reference<decltype(
56 *std::begin(std::declval<RangeT &>()))>::type;
57
58} // end namespace detail
59
60//===----------------------------------------------------------------------===//
61// Extra additions to <functional>
62//===----------------------------------------------------------------------===//
63
64template <class Ty> struct identity {
65 using argument_type = Ty;
66
67 Ty &operator()(Ty &self) const {
68 return self;
69 }
70 const Ty &operator()(const Ty &self) const {
71 return self;
72 }
73};
74
75template <class Ty> struct less_ptr {
76 bool operator()(const Ty* left, const Ty* right) const {
77 return *left < *right;
78 }
79};
80
81template <class Ty> struct greater_ptr {
82 bool operator()(const Ty* left, const Ty* right) const {
83 return *right < *left;
84 }
85};
86
87/// An efficient, type-erasing, non-owning reference to a callable. This is
88/// intended for use as the type of a function parameter that is not used
89/// after the function in question returns.
90///
91/// This class does not own the callable, so it is not in general safe to store
92/// a function_ref.
93template<typename Fn> class function_ref;
94
95template<typename Ret, typename ...Params>
96class function_ref<Ret(Params...)> {
97 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
98 intptr_t callable;
99
100 template<typename Callable>
101 static Ret callback_fn(intptr_t callable, Params ...params) {
102 return (*reinterpret_cast<Callable*>(callable))(
103 std::forward<Params>(params)...);
104 }
105
106public:
107 function_ref() = default;
108 function_ref(std::nullptr_t) {}
109
110 template <typename Callable>
111 function_ref(Callable &&callable,
112 typename std::enable_if<
113 !std::is_same<typename std::remove_reference<Callable>::type,
114 function_ref>::value>::type * = nullptr)
115 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
116 callable(reinterpret_cast<intptr_t>(&callable)) {}
117
118 Ret operator()(Params ...params) const {
119 return callback(callable, std::forward<Params>(params)...);
120 }
121
122 operator bool() const { return callback; }
123};
124
125// deleter - Very very very simple method that is used to invoke operator
126// delete on something. It is used like this:
127//
128// for_each(V.begin(), B.end(), deleter<Interval>);
129template <class T>
130inline void deleter(T *Ptr) {
131 delete Ptr;
132}
133
134//===----------------------------------------------------------------------===//
135// Extra additions to <iterator>
136//===----------------------------------------------------------------------===//
137
138namespace adl_detail {
139
140using std::begin;
141
142template <typename ContainerTy>
143auto adl_begin(ContainerTy &&container)
144 -> decltype(begin(std::forward<ContainerTy>(container))) {
145 return begin(std::forward<ContainerTy>(container));
146}
147
148using std::end;
149
150template <typename ContainerTy>
151auto adl_end(ContainerTy &&container)
152 -> decltype(end(std::forward<ContainerTy>(container))) {
153 return end(std::forward<ContainerTy>(container));
154}
155
156using std::swap;
157
158template <typename T>
159void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
160 std::declval<T>()))) {
161 swap(std::forward<T>(lhs), std::forward<T>(rhs));
162}
163
164} // end namespace adl_detail
165
166template <typename ContainerTy>
167auto adl_begin(ContainerTy &&container)
168 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
169 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
170}
171
172template <typename ContainerTy>
173auto adl_end(ContainerTy &&container)
174 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
175 return adl_detail::adl_end(std::forward<ContainerTy>(container));
176}
177
178template <typename T>
179void adl_swap(T &&lhs, T &&rhs) noexcept(
180 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
181 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
182}
183
184// mapped_iterator - This is a simple iterator adapter that causes a function to
185// be applied whenever operator* is invoked on the iterator.
186
187template <typename ItTy, typename FuncTy,
188 typename FuncReturnTy =
189 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
190class mapped_iterator
191 : public iterator_adaptor_base<
192 mapped_iterator<ItTy, FuncTy>, ItTy,
193 typename std::iterator_traits<ItTy>::iterator_category,
194 typename std::remove_reference<FuncReturnTy>::type> {
195public:
196 mapped_iterator(ItTy U, FuncTy F)
197 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
198
199 ItTy getCurrent() { return this->I; }
200
201 FuncReturnTy operator*() { return F(*this->I); }
202
203private:
204 FuncTy F;
205};
206
207// map_iterator - Provide a convenient way to create mapped_iterators, just like
208// make_pair is useful for creating pairs...
209template <class ItTy, class FuncTy>
210inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
211 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
212}
213
214/// Helper to determine if type T has a member called rbegin().
215template <typename Ty> class has_rbegin_impl {
216 using yes = char[1];
217 using no = char[2];
218
219 template <typename Inner>
220 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
221
222 template <typename>
223 static no& test(...);
224
225public:
226 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
227};
228
229/// Metafunction to determine if T& or T has a member called rbegin().
230template <typename Ty>
231struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
232};
233
234// Returns an iterator_range over the given container which iterates in reverse.
235// Note that the container must have rbegin()/rend() methods for this to work.
236template <typename ContainerTy>
237auto reverse(ContainerTy &&C,
238 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
239 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
240 return make_range(C.rbegin(), C.rend());
241}
242
243// Returns a std::reverse_iterator wrapped around the given iterator.
244template <typename IteratorTy>
245std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
246 return std::reverse_iterator<IteratorTy>(It);
247}
248
249// Returns an iterator_range over the given container which iterates in reverse.
250// Note that the container must have begin()/end() methods which return
251// bidirectional iterators for this to work.
252template <typename ContainerTy>
253auto reverse(
254 ContainerTy &&C,
255 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
256 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
257 llvm::make_reverse_iterator(std::begin(C)))) {
258 return make_range(llvm::make_reverse_iterator(std::end(C)),
259 llvm::make_reverse_iterator(std::begin(C)));
260}
261
262/// An iterator adaptor that filters the elements of given inner iterators.
263///
264/// The predicate parameter should be a callable object that accepts the wrapped
265/// iterator's reference type and returns a bool. When incrementing or
266/// decrementing the iterator, it will call the predicate on each element and
267/// skip any where it returns false.
268///
269/// \code
270/// int A[] = { 1, 2, 3, 4 };
271/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
272/// // R contains { 1, 3 }.
273/// \endcode
274template <typename WrappedIteratorT, typename PredicateT>
275class filter_iterator
276 : public iterator_adaptor_base<
277 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
278 typename std::common_type<
279 std::forward_iterator_tag,
280 typename std::iterator_traits<
281 WrappedIteratorT>::iterator_category>::type> {
282 using BaseT = iterator_adaptor_base<
283 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
284 typename std::common_type<
285 std::forward_iterator_tag,
286 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
287 type>;
288
289 struct PayloadType {
290 WrappedIteratorT End;
291 PredicateT Pred;
292 };
293
294 Optional<PayloadType> Payload;
295
296 void findNextValid() {
297 assert(Payload && "Payload should be engaged when findNextValid is called")(static_cast <bool> (Payload && "Payload should be engaged when findNextValid is called"
) ? void (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 297, __extension__ __PRETTY_FUNCTION__))
;
298 while (this->I != Payload->End && !Payload->Pred(*this->I))
299 BaseT::operator++();
300 }
301
302 // Construct the begin iterator. The begin iterator requires to know where end
303 // is, so that it can properly stop when it hits end.
304 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
305 : BaseT(std::move(Begin)),
306 Payload(PayloadType{std::move(End), std::move(Pred)}) {
307 findNextValid();
308 }
309
310 // Construct the end iterator. It's not incrementable, so Payload doesn't
311 // have to be engaged.
312 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
313
314public:
315 using BaseT::operator++;
316
317 filter_iterator &operator++() {
318 BaseT::operator++();
319 findNextValid();
320 return *this;
321 }
322
323 template <typename RT, typename PT>
324 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
325 make_filter_range(RT &&, PT);
326};
327
328/// Convenience function that takes a range of elements and a predicate,
329/// and return a new filter_iterator range.
330///
331/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
332/// lifetime of that temporary is not kept by the returned range object, and the
333/// temporary is going to be dropped on the floor after the make_iterator_range
334/// full expression that contains this function call.
335template <typename RangeT, typename PredicateT>
336iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
337make_filter_range(RangeT &&Range, PredicateT Pred) {
338 using FilterIteratorT =
339 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
340 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
341 std::end(std::forward<RangeT>(Range)),
342 std::move(Pred)),
343 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
344}
345
346// forward declarations required by zip_shortest/zip_first
347template <typename R, typename UnaryPredicate>
348bool all_of(R &&range, UnaryPredicate P);
349
350template <size_t... I> struct index_sequence;
351
352template <class... Ts> struct index_sequence_for;
353
354namespace detail {
355
356using std::declval;
357
358// We have to alias this since inlining the actual type at the usage site
359// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
360template<typename... Iters> struct ZipTupleType {
361 using type = std::tuple<decltype(*declval<Iters>())...>;
362};
363
364template <typename ZipType, typename... Iters>
365using zip_traits = iterator_facade_base<
366 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
367 typename std::iterator_traits<
368 Iters>::iterator_category...>::type,
369 // ^ TODO: Implement random access methods.
370 typename ZipTupleType<Iters...>::type,
371 typename std::iterator_traits<typename std::tuple_element<
372 0, std::tuple<Iters...>>::type>::difference_type,
373 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
374 // inner iterators have the same difference_type. It would fail if, for
375 // instance, the second field's difference_type were non-numeric while the
376 // first is.
377 typename ZipTupleType<Iters...>::type *,
378 typename ZipTupleType<Iters...>::type>;
379
380template <typename ZipType, typename... Iters>
381struct zip_common : public zip_traits<ZipType, Iters...> {
382 using Base = zip_traits<ZipType, Iters...>;
383 using value_type = typename Base::value_type;
384
385 std::tuple<Iters...> iterators;
386
387protected:
388 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
389 return value_type(*std::get<Ns>(iterators)...);
390 }
391
392 template <size_t... Ns>
393 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
394 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
395 }
396
397 template <size_t... Ns>
398 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
399 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
400 }
401
402public:
403 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
404
405 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
406
407 const value_type operator*() const {
408 return deref(index_sequence_for<Iters...>{});
409 }
410
411 ZipType &operator++() {
412 iterators = tup_inc(index_sequence_for<Iters...>{});
413 return *reinterpret_cast<ZipType *>(this);
414 }
415
416 ZipType &operator--() {
417 static_assert(Base::IsBidirectional,
418 "All inner iterators must be at least bidirectional.");
419 iterators = tup_dec(index_sequence_for<Iters...>{});
420 return *reinterpret_cast<ZipType *>(this);
421 }
422};
423
424template <typename... Iters>
425struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
426 using Base = zip_common<zip_first<Iters...>, Iters...>;
427
428 bool operator==(const zip_first<Iters...> &other) const {
429 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
430 }
431
432 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
433};
434
435template <typename... Iters>
436class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
437 template <size_t... Ns>
438 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
439 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
440 std::get<Ns>(other.iterators)...},
441 identity<bool>{});
442 }
443
444public:
445 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
446
447 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
448
449 bool operator==(const zip_shortest<Iters...> &other) const {
450 return !test(other, index_sequence_for<Iters...>{});
451 }
452};
453
454template <template <typename...> class ItType, typename... Args> class zippy {
455public:
456 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
457 using iterator_category = typename iterator::iterator_category;
458 using value_type = typename iterator::value_type;
459 using difference_type = typename iterator::difference_type;
460 using pointer = typename iterator::pointer;
461 using reference = typename iterator::reference;
462
463private:
464 std::tuple<Args...> ts;
465
466 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
467 return iterator(std::begin(std::get<Ns>(ts))...);
468 }
469 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
470 return iterator(std::end(std::get<Ns>(ts))...);
471 }
472
473public:
474 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
475
476 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
477 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
478};
479
480} // end namespace detail
481
482/// zip iterator for two or more iteratable types.
483template <typename T, typename U, typename... Args>
484detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
485 Args &&... args) {
486 return detail::zippy<detail::zip_shortest, T, U, Args...>(
487 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
488}
489
490/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
491/// be the shortest.
492template <typename T, typename U, typename... Args>
493detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
494 Args &&... args) {
495 return detail::zippy<detail::zip_first, T, U, Args...>(
496 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
497}
498
499/// Iterator wrapper that concatenates sequences together.
500///
501/// This can concatenate different iterators, even with different types, into
502/// a single iterator provided the value types of all the concatenated
503/// iterators expose `reference` and `pointer` types that can be converted to
504/// `ValueT &` and `ValueT *` respectively. It doesn't support more
505/// interesting/customized pointer or reference types.
506///
507/// Currently this only supports forward or higher iterator categories as
508/// inputs and always exposes a forward iterator interface.
509template <typename ValueT, typename... IterTs>
510class concat_iterator
511 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
512 std::forward_iterator_tag, ValueT> {
513 using BaseT = typename concat_iterator::iterator_facade_base;
514
515 /// We store both the current and end iterators for each concatenated
516 /// sequence in a tuple of pairs.
517 ///
518 /// Note that something like iterator_range seems nice at first here, but the
519 /// range properties are of little benefit and end up getting in the way
520 /// because we need to do mutation on the current iterators.
521 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
522
523 /// Attempts to increment a specific iterator.
524 ///
525 /// Returns true if it was able to increment the iterator. Returns false if
526 /// the iterator is already at the end iterator.
527 template <size_t Index> bool incrementHelper() {
528 auto &IterPair = std::get<Index>(IterPairs);
529 if (IterPair.first == IterPair.second)
530 return false;
531
532 ++IterPair.first;
533 return true;
534 }
535
536 /// Increments the first non-end iterator.
537 ///
538 /// It is an error to call this with all iterators at the end.
539 template <size_t... Ns> void increment(index_sequence<Ns...>) {
540 // Build a sequence of functions to increment each iterator if possible.
541 bool (concat_iterator::*IncrementHelperFns[])() = {
542 &concat_iterator::incrementHelper<Ns>...};
543
544 // Loop over them, and stop as soon as we succeed at incrementing one.
545 for (auto &IncrementHelperFn : IncrementHelperFns)
546 if ((this->*IncrementHelperFn)())
547 return;
548
549 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 549)
;
550 }
551
552 /// Returns null if the specified iterator is at the end. Otherwise,
553 /// dereferences the iterator and returns the address of the resulting
554 /// reference.
555 template <size_t Index> ValueT *getHelper() const {
556 auto &IterPair = std::get<Index>(IterPairs);
557 if (IterPair.first == IterPair.second)
558 return nullptr;
559
560 return &*IterPair.first;
561 }
562
563 /// Finds the first non-end iterator, dereferences, and returns the resulting
564 /// reference.
565 ///
566 /// It is an error to call this with all iterators at the end.
567 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
568 // Build a sequence of functions to get from iterator if possible.
569 ValueT *(concat_iterator::*GetHelperFns[])() const = {
570 &concat_iterator::getHelper<Ns>...};
571
572 // Loop over them, and return the first result we find.
573 for (auto &GetHelperFn : GetHelperFns)
574 if (ValueT *P = (this->*GetHelperFn)())
575 return *P;
576
577 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 577)
;
578 }
579
580public:
581 /// Constructs an iterator from a squence of ranges.
582 ///
583 /// We need the full range to know how to switch between each of the
584 /// iterators.
585 template <typename... RangeTs>
586 explicit concat_iterator(RangeTs &&... Ranges)
587 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
588
589 using BaseT::operator++;
590
591 concat_iterator &operator++() {
592 increment(index_sequence_for<IterTs...>());
593 return *this;
594 }
595
596 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
597
598 bool operator==(const concat_iterator &RHS) const {
599 return IterPairs == RHS.IterPairs;
600 }
601};
602
603namespace detail {
604
605/// Helper to store a sequence of ranges being concatenated and access them.
606///
607/// This is designed to facilitate providing actual storage when temporaries
608/// are passed into the constructor such that we can use it as part of range
609/// based for loops.
610template <typename ValueT, typename... RangeTs> class concat_range {
611public:
612 using iterator =
613 concat_iterator<ValueT,
614 decltype(std::begin(std::declval<RangeTs &>()))...>;
615
616private:
617 std::tuple<RangeTs...> Ranges;
618
619 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
620 return iterator(std::get<Ns>(Ranges)...);
621 }
622 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
623 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
624 std::end(std::get<Ns>(Ranges)))...);
625 }
626
627public:
628 concat_range(RangeTs &&... Ranges)
629 : Ranges(std::forward<RangeTs>(Ranges)...) {}
630
631 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
632 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
633};
634
635} // end namespace detail
636
637/// Concatenated range across two or more ranges.
638///
639/// The desired value type must be explicitly specified.
640template <typename ValueT, typename... RangeTs>
641detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
642 static_assert(sizeof...(RangeTs) > 1,
643 "Need more than one range to concatenate!");
644 return detail::concat_range<ValueT, RangeTs...>(
645 std::forward<RangeTs>(Ranges)...);
646}
647
648//===----------------------------------------------------------------------===//
649// Extra additions to <utility>
650//===----------------------------------------------------------------------===//
651
652/// \brief Function object to check whether the first component of a std::pair
653/// compares less than the first component of another std::pair.
654struct less_first {
655 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
656 return lhs.first < rhs.first;
657 }
658};
659
660/// \brief Function object to check whether the second component of a std::pair
661/// compares less than the second component of another std::pair.
662struct less_second {
663 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
664 return lhs.second < rhs.second;
665 }
666};
667
668// A subset of N3658. More stuff can be added as-needed.
669
670/// \brief Represents a compile-time sequence of integers.
671template <class T, T... I> struct integer_sequence {
672 using value_type = T;
673
674 static constexpr size_t size() { return sizeof...(I); }
675};
676
677/// \brief Alias for the common case of a sequence of size_ts.
678template <size_t... I>
679struct index_sequence : integer_sequence<std::size_t, I...> {};
680
681template <std::size_t N, std::size_t... I>
682struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
683template <std::size_t... I>
684struct build_index_impl<0, I...> : index_sequence<I...> {};
685
686/// \brief Creates a compile-time integer sequence for a parameter pack.
687template <class... Ts>
688struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
689
690/// Utility type to build an inheritance chain that makes it easy to rank
691/// overload candidates.
692template <int N> struct rank : rank<N - 1> {};
693template <> struct rank<0> {};
694
695/// \brief traits class for checking whether type T is one of any of the given
696/// types in the variadic list.
697template <typename T, typename... Ts> struct is_one_of {
698 static const bool value = false;
699};
700
701template <typename T, typename U, typename... Ts>
702struct is_one_of<T, U, Ts...> {
703 static const bool value =
704 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
705};
706
707/// \brief traits class for checking whether type T is a base class for all
708/// the given types in the variadic list.
709template <typename T, typename... Ts> struct are_base_of {
710 static const bool value = true;
711};
712
713template <typename T, typename U, typename... Ts>
714struct are_base_of<T, U, Ts...> {
715 static const bool value =
716 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
717};
718
719//===----------------------------------------------------------------------===//
720// Extra additions for arrays
721//===----------------------------------------------------------------------===//
722
723/// Find the length of an array.
724template <class T, std::size_t N>
725constexpr inline size_t array_lengthof(T (&)[N]) {
726 return N;
727}
728
729/// Adapt std::less<T> for array_pod_sort.
730template<typename T>
731inline int array_pod_sort_comparator(const void *P1, const void *P2) {
732 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
733 *reinterpret_cast<const T*>(P2)))
734 return -1;
735 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
736 *reinterpret_cast<const T*>(P1)))
737 return 1;
738 return 0;
739}
740
741/// get_array_pod_sort_comparator - This is an internal helper function used to
742/// get type deduction of T right.
743template<typename T>
744inline int (*get_array_pod_sort_comparator(const T &))
745 (const void*, const void*) {
746 return array_pod_sort_comparator<T>;
747}
748
749/// array_pod_sort - This sorts an array with the specified start and end
750/// extent. This is just like std::sort, except that it calls qsort instead of
751/// using an inlined template. qsort is slightly slower than std::sort, but
752/// most sorts are not performance critical in LLVM and std::sort has to be
753/// template instantiated for each type, leading to significant measured code
754/// bloat. This function should generally be used instead of std::sort where
755/// possible.
756///
757/// This function assumes that you have simple POD-like types that can be
758/// compared with std::less and can be moved with memcpy. If this isn't true,
759/// you should use std::sort.
760///
761/// NOTE: If qsort_r were portable, we could allow a custom comparator and
762/// default to std::less.
763template<class IteratorTy>
764inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
765 // Don't inefficiently call qsort with one element or trigger undefined
766 // behavior with an empty sequence.
767 auto NElts = End - Start;
768 if (NElts <= 1) return;
769#ifdef EXPENSIVE_CHECKS
770 std::mt19937 Generator(std::random_device{}());
771 std::shuffle(Start, End, Generator);
772#endif
773 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
774}
775
776template <class IteratorTy>
777inline void array_pod_sort(
778 IteratorTy Start, IteratorTy End,
779 int (*Compare)(
780 const typename std::iterator_traits<IteratorTy>::value_type *,
781 const typename std::iterator_traits<IteratorTy>::value_type *)) {
782 // Don't inefficiently call qsort with one element or trigger undefined
783 // behavior with an empty sequence.
784 auto NElts = End - Start;
785 if (NElts <= 1) return;
786#ifdef EXPENSIVE_CHECKS
787 std::mt19937 Generator(std::random_device{}());
788 std::shuffle(Start, End, Generator);
789#endif
790 qsort(&*Start, NElts, sizeof(*Start),
791 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
792}
793
794// Provide wrappers to std::sort which shuffle the elements before sorting
795// to help uncover non-deterministic behavior (PR35135).
796template <typename IteratorTy>
797inline void sort(IteratorTy Start, IteratorTy End) {
798#ifdef EXPENSIVE_CHECKS
799 std::mt19937 Generator(std::random_device{}());
800 std::shuffle(Start, End, Generator);
801#endif
802 std::sort(Start, End);
803}
804
805template <typename IteratorTy, typename Compare>
806inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
807#ifdef EXPENSIVE_CHECKS
808 std::mt19937 Generator(std::random_device{}());
809 std::shuffle(Start, End, Generator);
810#endif
811 std::sort(Start, End, Comp);
812}
813
814//===----------------------------------------------------------------------===//
815// Extra additions to <algorithm>
816//===----------------------------------------------------------------------===//
817
818/// For a container of pointers, deletes the pointers and then clears the
819/// container.
820template<typename Container>
821void DeleteContainerPointers(Container &C) {
822 for (auto V : C)
823 delete V;
824 C.clear();
825}
826
827/// In a container of pairs (usually a map) whose second element is a pointer,
828/// deletes the second elements and then clears the container.
829template<typename Container>
830void DeleteContainerSeconds(Container &C) {
831 for (auto &V : C)
832 delete V.second;
833 C.clear();
834}
835
836/// Provide wrappers to std::for_each which take ranges instead of having to
837/// pass begin/end explicitly.
838template <typename R, typename UnaryPredicate>
839UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
840 return std::for_each(adl_begin(Range), adl_end(Range), P);
841}
842
843/// Provide wrappers to std::all_of which take ranges instead of having to pass
844/// begin/end explicitly.
845template <typename R, typename UnaryPredicate>
846bool all_of(R &&Range, UnaryPredicate P) {
847 return std::all_of(adl_begin(Range), adl_end(Range), P);
848}
849
850/// Provide wrappers to std::any_of which take ranges instead of having to pass
851/// begin/end explicitly.
852template <typename R, typename UnaryPredicate>
853bool any_of(R &&Range, UnaryPredicate P) {
854 return std::any_of(adl_begin(Range), adl_end(Range), P);
855}
856
857/// Provide wrappers to std::none_of which take ranges instead of having to pass
858/// begin/end explicitly.
859template <typename R, typename UnaryPredicate>
860bool none_of(R &&Range, UnaryPredicate P) {
861 return std::none_of(adl_begin(Range), adl_end(Range), P);
862}
863
864/// Provide wrappers to std::find which take ranges instead of having to pass
865/// begin/end explicitly.
866template <typename R, typename T>
867auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
868 return std::find(adl_begin(Range), adl_end(Range), Val);
869}
870
871/// Provide wrappers to std::find_if which take ranges instead of having to pass
872/// begin/end explicitly.
873template <typename R, typename UnaryPredicate>
874auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
875 return std::find_if(adl_begin(Range), adl_end(Range), P);
876}
877
878template <typename R, typename UnaryPredicate>
879auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
880 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
881}
882
883/// Provide wrappers to std::remove_if which take ranges instead of having to
884/// pass begin/end explicitly.
885template <typename R, typename UnaryPredicate>
886auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
887 return std::remove_if(adl_begin(Range), adl_end(Range), P);
888}
889
890/// Provide wrappers to std::copy_if which take ranges instead of having to
891/// pass begin/end explicitly.
892template <typename R, typename OutputIt, typename UnaryPredicate>
893OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
894 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
895}
896
897template <typename R, typename OutputIt>
898OutputIt copy(R &&Range, OutputIt Out) {
899 return std::copy(adl_begin(Range), adl_end(Range), Out);
900}
901
902/// Wrapper function around std::find to detect if an element exists
903/// in a container.
904template <typename R, typename E>
905bool is_contained(R &&Range, const E &Element) {
906 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
907}
908
909/// Wrapper function around std::count to count the number of times an element
910/// \p Element occurs in the given range \p Range.
911template <typename R, typename E>
912auto count(R &&Range, const E &Element) ->
913 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
914 return std::count(adl_begin(Range), adl_end(Range), Element);
915}
916
917/// Wrapper function around std::count_if to count the number of times an
918/// element satisfying a given predicate occurs in a range.
919template <typename R, typename UnaryPredicate>
920auto count_if(R &&Range, UnaryPredicate P) ->
921 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
922 return std::count_if(adl_begin(Range), adl_end(Range), P);
923}
924
925/// Wrapper function around std::transform to apply a function to a range and
926/// store the result elsewhere.
927template <typename R, typename OutputIt, typename UnaryPredicate>
928OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
929 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
930}
931
932/// Provide wrappers to std::partition which take ranges instead of having to
933/// pass begin/end explicitly.
934template <typename R, typename UnaryPredicate>
935auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
936 return std::partition(adl_begin(Range), adl_end(Range), P);
937}
938
939/// Provide wrappers to std::lower_bound which take ranges instead of having to
940/// pass begin/end explicitly.
941template <typename R, typename ForwardIt>
942auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
943 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
944}
945
946/// \brief Given a range of type R, iterate the entire range and return a
947/// SmallVector with elements of the vector. This is useful, for example,
948/// when you want to iterate a range and then sort the results.
949template <unsigned Size, typename R>
950SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
951to_vector(R &&Range) {
952 return {adl_begin(Range), adl_end(Range)};
953}
954
955/// Provide a container algorithm similar to C++ Library Fundamentals v2's
956/// `erase_if` which is equivalent to:
957///
958/// C.erase(remove_if(C, pred), C.end());
959///
960/// This version works for any container with an erase method call accepting
961/// two iterators.
962template <typename Container, typename UnaryPredicate>
963void erase_if(Container &C, UnaryPredicate P) {
964 C.erase(remove_if(C, P), C.end());
965}
966
967//===----------------------------------------------------------------------===//
968// Extra additions to <memory>
969//===----------------------------------------------------------------------===//
970
971// Implement make_unique according to N3656.
972
973/// \brief Constructs a `new T()` with the given args and returns a
974/// `unique_ptr<T>` which owns the object.
975///
976/// Example:
977///
978/// auto p = make_unique<int>();
979/// auto p = make_unique<std::tuple<int, int>>(0, 1);
980template <class T, class... Args>
981typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
982make_unique(Args &&... args) {
983 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
9
Use of memory after it is freed
984}
985
986/// \brief Constructs a `new T[n]` with the given args and returns a
987/// `unique_ptr<T[]>` which owns the object.
988///
989/// \param n size of the new array.
990///
991/// Example:
992///
993/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
994template <class T>
995typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
996 std::unique_ptr<T>>::type
997make_unique(size_t n) {
998 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
999}
1000
1001/// This function isn't used and is only here to provide better compile errors.
1002template <class T, class... Args>
1003typename std::enable_if<std::extent<T>::value != 0>::type
1004make_unique(Args &&...) = delete;
1005
1006struct FreeDeleter {
1007 void operator()(void* v) {
1008 ::free(v);
1009 }
1010};
1011
1012template<typename First, typename Second>
1013struct pair_hash {
1014 size_t operator()(const std::pair<First, Second> &P) const {
1015 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1016 }
1017};
1018
1019/// A functor like C++14's std::less<void> in its absence.
1020struct less {
1021 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1022 return std::forward<A>(a) < std::forward<B>(b);
1023 }
1024};
1025
1026/// A functor like C++14's std::equal<void> in its absence.
1027struct equal {
1028 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1029 return std::forward<A>(a) == std::forward<B>(b);
1030 }
1031};
1032
1033/// Binary functor that adapts to any other binary functor after dereferencing
1034/// operands.
1035template <typename T> struct deref {
1036 T func;
1037
1038 // Could be further improved to cope with non-derivable functors and
1039 // non-binary functors (should be a variadic template member function
1040 // operator()).
1041 template <typename A, typename B>
1042 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1043 assert(lhs)(static_cast <bool> (lhs) ? void (0) : __assert_fail ("lhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1043, __extension__ __PRETTY_FUNCTION__))
;
1044 assert(rhs)(static_cast <bool> (rhs) ? void (0) : __assert_fail ("rhs"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1044, __extension__ __PRETTY_FUNCTION__))
;
1045 return func(*lhs, *rhs);
1046 }
1047};
1048
1049namespace detail {
1050
1051template <typename R> class enumerator_iter;
1052
1053template <typename R> struct result_pair {
1054 friend class enumerator_iter<R>;
1055
1056 result_pair() = default;
1057 result_pair(std::size_t Index, IterOfRange<R> Iter)
1058 : Index(Index), Iter(Iter) {}
1059
1060 result_pair<R> &operator=(const result_pair<R> &Other) {
1061 Index = Other.Index;
1062 Iter = Other.Iter;
1063 return *this;
1064 }
1065
1066 std::size_t index() const { return Index; }
1067 const ValueOfRange<R> &value() const { return *Iter; }
1068 ValueOfRange<R> &value() { return *Iter; }
1069
1070private:
1071 std::size_t Index = std::numeric_limits<std::size_t>::max();
1072 IterOfRange<R> Iter;
1073};
1074
1075template <typename R>
1076class enumerator_iter
1077 : public iterator_facade_base<
1078 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1079 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1080 typename std::iterator_traits<IterOfRange<R>>::pointer,
1081 typename std::iterator_traits<IterOfRange<R>>::reference> {
1082 using result_type = result_pair<R>;
1083
1084public:
1085 explicit enumerator_iter(IterOfRange<R> EndIter)
1086 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1087
1088 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1089 : Result(Index, Iter) {}
1090
1091 result_type &operator*() { return Result; }
1092 const result_type &operator*() const { return Result; }
1093
1094 enumerator_iter<R> &operator++() {
1095 assert(Result.Index != std::numeric_limits<size_t>::max())(static_cast <bool> (Result.Index != std::numeric_limits
<size_t>::max()) ? void (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-7~svn329677/include/llvm/ADT/STLExtras.h"
, 1095, __extension__ __PRETTY_FUNCTION__))
;
1096 ++Result.Iter;
1097 ++Result.Index;
1098 return *this;
1099 }
1100
1101 bool operator==(const enumerator_iter<R> &RHS) const {
1102 // Don't compare indices here, only iterators. It's possible for an end
1103 // iterator to have different indices depending on whether it was created
1104 // by calling std::end() versus incrementing a valid iterator.
1105 return Result.Iter == RHS.Result.Iter;
1106 }
1107
1108 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1109 Result = Other.Result;
1110 return *this;
1111 }
1112
1113private:
1114 result_type Result;
1115};
1116
1117template <typename R> class enumerator {
1118public:
1119 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1120
1121 enumerator_iter<R> begin() {
1122 return enumerator_iter<R>(0, std::begin(TheRange));
1123 }
1124
1125 enumerator_iter<R> end() {
1126 return enumerator_iter<R>(std::end(TheRange));
1127 }
1128
1129private:
1130 R TheRange;
1131};
1132
1133} // end namespace detail
1134
1135/// Given an input range, returns a new range whose values are are pair (A,B)
1136/// such that A is the 0-based index of the item in the sequence, and B is
1137/// the value from the original sequence. Example:
1138///
1139/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1140/// for (auto X : enumerate(Items)) {
1141/// printf("Item %d - %c\n", X.index(), X.value());
1142/// }
1143///
1144/// Output:
1145/// Item 0 - A
1146/// Item 1 - B
1147/// Item 2 - C
1148/// Item 3 - D
1149///
1150template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1151 return detail::enumerator<R>(std::forward<R>(TheRange));
1152}
1153
1154namespace detail {
1155
1156template <typename F, typename Tuple, std::size_t... I>
1157auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1158 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1159 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1160}
1161
1162} // end namespace detail
1163
1164/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1165/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1166/// return the result.
1167template <typename F, typename Tuple>
1168auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1169 std::forward<F>(f), std::forward<Tuple>(t),
1170 build_index_impl<
1171 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1172 using Indices = build_index_impl<
1173 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1174
1175 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1176 Indices{});
1177}
1178
1179} // end namespace llvm
1180
1181#endif // LLVM_ADT_STLEXTRAS_H